repo_name
stringlengths
6
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
possible_versions
list
ChAnYaNG97/datasets
[ "0a45e2ea98716d325fc1c5e5494f2575f3bdb908", "0a45e2ea98716d325fc1c5e5494f2575f3bdb908", "0a45e2ea98716d325fc1c5e5494f2575f3bdb908", "0a45e2ea98716d325fc1c5e5494f2575f3bdb908", "0a45e2ea98716d325fc1c5e5494f2575f3bdb908", "0a45e2ea98716d325fc1c5e5494f2575f3bdb908", "0a45e2ea98716d325fc1c5e5494f2575f3bdb908", "0a45e2ea98716d325fc1c5e5494f2575f3bdb908", "0a45e2ea98716d325fc1c5e5494f2575f3bdb908", "0a45e2ea98716d325fc1c5e5494f2575f3bdb908", "0a45e2ea98716d325fc1c5e5494f2575f3bdb908" ]
[ "tensorflow_datasets/object_detection/voc.py", "tensorflow_datasets/summarization/opinion_abstracts.py", "tensorflow_datasets/text/eraser_multi_rc.py", "tensorflow_datasets/text/reddit_disentanglement.py", "tensorflow_datasets/image_classification/cmaterdb.py", "tensorflow_datasets/image_classification/diabetic_retinopathy_detection.py", "tensorflow_datasets/testing/fake_data_generation/curated_breast_imaging_ddsm.py", "tensorflow_datasets/object_detection/open_images_challenge2019_beam.py", "tensorflow_datasets/core/features/text/subword_text_encoder_test.py", "tensorflow_datasets/translate/opus.py", "tensorflow_datasets/core/features/text_feature_test.py" ]
[ "# coding=utf-8\n# Copyright 2020 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"PASCAL VOC datasets.\"\"\"\n\nimport os\nimport xml.etree.ElementTree\n\nimport tensorflow.compat.v2 as tf\nimport tensorflow_datasets.public_api as tfds\n\n\n_VOC_CITATION = \"\"\"\\\n@misc{{pascal-voc-{year},\n\tauthor = \"Everingham, M. and Van~Gool, L. and Williams, C. K. I. and Winn, J. and Zisserman, A.\",\n\ttitle = \"The {{PASCAL}} {{V}}isual {{O}}bject {{C}}lasses {{C}}hallenge {year} {{(VOC{year})}} {{R}}esults\",\n\thowpublished = \"http://www.pascal-network.org/challenges/VOC/voc{year}/workshop/index.html\"}}\n\"\"\"\n_VOC_DESCRIPTION = \"\"\"\\\nThis dataset contains the data from the PASCAL Visual Object Classes Challenge\n{year}, a.k.a. VOC{year}, corresponding to the Classification and Detection\ncompetitions.\nA total of {num_images} images are included in this dataset, where each image\ncontains a set of objects, out of 20 different classes, making a total of\n{num_objects} annotated objects.\nIn the Classification competition, the goal is to predict the set of labels\ncontained in the image, while in the Detection competition the goal is to\npredict the bounding box and label of each individual object.\nWARNING: As per the official dataset, the test set of VOC2012 does not contain\nannotations.\n\"\"\"\n_VOC_URL = \"http://host.robots.ox.ac.uk/pascal/VOC/voc{year}/\"\n# Original site, it is down very often.\n# _VOC_DATA_URL = \"http://host.robots.ox.ac.uk/pascal/VOC/voc{year}/\"\n# Data mirror:\n_VOC_DATA_URL = \"http://pjreddie.com/media/files/\"\n_VOC_LABELS = (\n \"aeroplane\",\n \"bicycle\",\n \"bird\",\n \"boat\",\n \"bottle\",\n \"bus\",\n \"car\",\n \"cat\",\n \"chair\",\n \"cow\",\n \"diningtable\",\n \"dog\",\n \"horse\",\n \"motorbike\",\n \"person\",\n \"pottedplant\",\n \"sheep\",\n \"sofa\",\n \"train\",\n \"tvmonitor\",\n)\n_VOC_POSES = (\n \"frontal\",\n \"rear\",\n \"left\",\n \"right\",\n \"unspecified\",\n)\n\n\ndef _get_example_objects(annon_filepath):\n \"\"\"Function to get all the objects from the annotation XML file.\"\"\"\n with tf.io.gfile.GFile(annon_filepath, \"r\") as f:\n root = xml.etree.ElementTree.parse(f).getroot()\n\n # Disable pytype to avoid attribute-error due to find returning\n # Optional[Element]\n # pytype: disable=attribute-error\n size = root.find(\"size\")\n width = float(size.find(\"width\").text)\n height = float(size.find(\"height\").text)\n\n for obj in root.findall(\"object\"):\n # Get object's label name.\n label = obj.find(\"name\").text.lower()\n # Get objects' pose name.\n pose = obj.find(\"pose\").text.lower()\n is_truncated = (obj.find(\"truncated\").text == \"1\")\n is_difficult = (obj.find(\"difficult\").text == \"1\")\n bndbox = obj.find(\"bndbox\")\n xmax = float(bndbox.find(\"xmax\").text)\n xmin = float(bndbox.find(\"xmin\").text)\n ymax = float(bndbox.find(\"ymax\").text)\n ymin = float(bndbox.find(\"ymin\").text)\n yield {\n \"label\": label,\n \"pose\": pose,\n \"bbox\": tfds.features.BBox(\n ymin / height, xmin / width, ymax / height, xmax / width),\n \"is_truncated\": is_truncated,\n \"is_difficult\": is_difficult,\n }\n # pytype: enable=attribute-error\n\n\nclass VocConfig(tfds.core.BuilderConfig):\n \"\"\"BuilderConfig for Voc.\"\"\"\n\n def __init__(\n self, year=None, filenames=None, has_test_annotations=True, **kwargs):\n self.year = year\n self.filenames = filenames\n self.has_test_annotations = has_test_annotations\n super(VocConfig, self).__init__(\n name=year,\n # Version history:\n # 4.0.0: Added BuildConfig and 2012 version support, deprecate Voc2007.\n # 3.0.0: S3 with new hashing function (different shuffle).\n # 2.0.0: S3 (new shuffling, sharding and slicing mechanism).\n version=tfds.core.Version(\"4.0.0\"),\n **kwargs)\n\n\nclass Voc(tfds.core.GeneratorBasedBuilder):\n \"\"\"Pascal VOC 2007 or 2012.\"\"\"\n\n BUILDER_CONFIGS = [\n VocConfig(\n year=\"2007\",\n description=_VOC_DESCRIPTION.format(\n year=2007, num_images=9963, num_objects=24640),\n filenames={\n \"trainval\": \"VOCtrainval_06-Nov-2007.tar\",\n \"test\": \"VOCtest_06-Nov-2007.tar\",\n },\n has_test_annotations=True,\n ),\n VocConfig(\n year=\"2012\",\n description=_VOC_DESCRIPTION.format(\n year=2012, num_images=11540, num_objects=27450),\n filenames={\n \"trainval\": \"VOCtrainval_11-May-2012.tar\",\n \"test\": \"VOC2012test.tar\",\n },\n has_test_annotations=False,\n ),\n ]\n\n def _info(self):\n return tfds.core.DatasetInfo(\n builder=self,\n description=self.builder_config.description,\n features=tfds.features.FeaturesDict({\n \"image\": tfds.features.Image(),\n \"image/filename\": tfds.features.Text(),\n \"objects\": tfds.features.Sequence({\n \"label\": tfds.features.ClassLabel(names=_VOC_LABELS),\n \"bbox\": tfds.features.BBoxFeature(),\n \"pose\": tfds.features.ClassLabel(names=_VOC_POSES),\n \"is_truncated\": tf.bool,\n \"is_difficult\": tf.bool,\n }),\n \"labels\": tfds.features.Sequence(\n tfds.features.ClassLabel(names=_VOC_LABELS)),\n \"labels_no_difficult\": tfds.features.Sequence(\n tfds.features.ClassLabel(names=_VOC_LABELS)),\n }),\n homepage=_VOC_URL.format(year=self.builder_config.year),\n citation=_VOC_CITATION.format(year=self.builder_config.year),\n )\n\n def _split_generators(self, dl_manager):\n paths = dl_manager.download_and_extract({\n k: os.path.join(_VOC_DATA_URL, v)\n for k, v in self.builder_config.filenames.items()\n })\n return [\n tfds.core.SplitGenerator(\n name=tfds.Split.TEST,\n gen_kwargs=dict(data_path=paths[\"test\"], set_name=\"test\")),\n tfds.core.SplitGenerator(\n name=tfds.Split.TRAIN,\n gen_kwargs=dict(data_path=paths[\"trainval\"], set_name=\"train\")),\n tfds.core.SplitGenerator(\n name=tfds.Split.VALIDATION,\n gen_kwargs=dict(data_path=paths[\"trainval\"], set_name=\"val\")),\n ]\n\n def _generate_examples(self, data_path, set_name):\n \"\"\"Yields examples.\"\"\"\n set_filepath = os.path.join(\n data_path,\n os.path.normpath(\"VOCdevkit/VOC{}/ImageSets/Main/{}.txt\".format(\n self.builder_config.year, set_name)))\n load_annotations = (\n self.builder_config.has_test_annotations or set_name != \"test\")\n with tf.io.gfile.GFile(set_filepath, \"r\") as f:\n for line in f:\n image_id = line.strip()\n example = self._generate_example(data_path, image_id, load_annotations)\n yield image_id, example\n\n def _generate_example(self, data_path, image_id, load_annotations):\n image_filepath = os.path.join(\n data_path,\n os.path.normpath(\"VOCdevkit/VOC{}/JPEGImages/{}.jpg\".format(\n self.builder_config.year, image_id)))\n annon_filepath = os.path.join(\n data_path,\n os.path.normpath(\"VOCdevkit/VOC{}/Annotations/{}.xml\".format(\n self.builder_config.year, image_id)))\n if load_annotations:\n objects = list(_get_example_objects(annon_filepath))\n # Use set() to remove duplicates\n labels = sorted(set(obj[\"label\"] for obj in objects))\n labels_no_difficult = sorted(set(\n obj[\"label\"] for obj in objects if obj[\"is_difficult\"] == 0\n ))\n else: # The test set of VOC2012 does not contain annotations\n objects = []\n labels = []\n labels_no_difficult = []\n return {\n \"image\": image_filepath,\n \"image/filename\": image_id + \".jpg\",\n \"objects\": objects,\n \"labels\": labels,\n \"labels_no_difficult\": labels_no_difficult,\n }\n", "# coding=utf-8\n# Copyright 2020 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Opinion Abstracts Dataset.\"\"\"\n\nimport json\nimport os\nfrom typing import Any, Dict, Iterator, List, Text, Tuple\n\nimport tensorflow.compat.v2 as tf\nimport tensorflow_datasets.public_api as tfds\n\n_CITATION = \"\"\"\n@inproceedings{wang-ling-2016-neural,\n title = \"Neural Network-Based Abstract Generation for Opinions and Arguments\",\n author = \"Wang, Lu and\n Ling, Wang\",\n booktitle = \"Proceedings of the 2016 Conference of the North {A}merican Chapter of the Association for Computational Linguistics: Human Language Technologies\",\n month = jun,\n year = \"2016\",\n address = \"San Diego, California\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/N16-1007\",\n doi = \"10.18653/v1/N16-1007\",\n pages = \"47--57\",\n}\n\"\"\"\n\n_DESCRIPTION = \"\"\"\nThere are two sub datasets:\n\n(1) RottenTomatoes: The movie critics and consensus crawled from\nhttp://rottentomatoes.com/. It has fields of \"_movie_name\", \"_movie_id\",\n\"_critics\", and \"_critic_consensus\".\n\n(2) IDebate: The arguments crawled from http://idebate.org/. It has fields of\n\"_debate_name\", \"_debate_id\", \"_claim\", \"_claim_id\", \"_argument_sentences\".\n\n\"\"\"\n\n_URL = \"http://www.ccs.neu.edu/home/luwang/datasets/opinion_abstracts.zip\"\n\n\nclass OpinionAbstractsConfig(tfds.core.BuilderConfig):\n \"\"\"BuilderConfig for OpinionAbstracts.\"\"\"\n\n def __init__(\n self,\n *,\n filename: Text = None,\n name_key: Text = None,\n id_key: Text = None,\n opinions_key: Text = None,\n summary_key: Text = None,\n **kwargs\n ):\n \"\"\"BuilderConfig for OpinionAbstracts.\"\"\"\n super(OpinionAbstractsConfig, self).__init__(\n version=tfds.core.Version(\"1.0.0\"), **kwargs)\n self.filename = filename\n self.name_key = name_key\n self.id_key = id_key\n self.opinions_key = opinions_key\n self.summary_key = summary_key\n\n\nclass OpinionAbstracts(tfds.core.GeneratorBasedBuilder):\n \"\"\"OpinionAbstracts Dataset Builder.\"\"\"\n\n VERSION = tfds.core.Version(\"1.0.0\")\n BUILDER_CONFIGS = [\n OpinionAbstractsConfig(\n name=\"rotten_tomatoes\",\n filename=\"rottentomatoes.json\",\n name_key=\"_movie_name\",\n id_key=\"_movie_id\",\n opinions_key=\"_critics\",\n summary_key=\"_critic_consensus\",\n description=\"Professional critics and consensus of 3,731 movies.\",\n ),\n OpinionAbstractsConfig(\n name=\"idebate\",\n filename=\"idebate.json\",\n name_key=\"_debate_name\",\n id_key=\"_claim_id\",\n opinions_key=\"_argument_sentences\",\n summary_key=\"_claim\",\n description=\"2,259 claims for 676 debates.\",\n )\n ]\n\n def _info(self) -> tfds.core.DatasetInfo:\n config = self.builder_config\n return tfds.core.DatasetInfo(\n builder=self,\n description=_DESCRIPTION,\n features=tfds.features.FeaturesDict({\n config.name_key:\n tf.string,\n config.id_key:\n tf.string,\n config.summary_key:\n tf.string,\n config.opinions_key:\n tfds.features.Sequence(\n tfds.features.FeaturesDict({\n \"key\": tf.string,\n \"value\": tf.string\n })),\n }),\n supervised_keys=(config.opinions_key, config.summary_key),\n homepage=\"http://www.ccs.neu.edu/home/luwang/data.html\",\n citation=_CITATION,\n )\n\n def _split_generators(\n self, dl_manager: tfds.download.DownloadManager\n ) -> List[tfds.core.SplitGenerator]:\n \"\"\"Returns SplitGenerators.\"\"\"\n dl_path = dl_manager.download_and_extract(_URL)\n path = os.path.join(dl_path, \"opinion_abstracts\",\n self.builder_config.filename)\n return [\n tfds.core.SplitGenerator(\n name=tfds.Split.TRAIN,\n gen_kwargs={\"path\": path},\n ),\n ]\n\n def _generate_examples(self,\n path: Text = None\n ) -> Iterator[Tuple[Text, Dict[Text, Any]]]:\n \"\"\"Yields examples.\"\"\"\n with tf.io.gfile.GFile(path, \"rb\") as f:\n for example in json.load(f):\n config = self.builder_config\n opinions = example[config.opinions_key].items()\n opinions = [{\"key\": k, \"value\": v} for k, v in opinions]\n features = {config.opinions_key: opinions}\n for k in [config.name_key, config.id_key, config.summary_key]:\n features[k] = example[k]\n yield example[config.id_key], features\n", "# coding=utf-8\n# Copyright 2020 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Passage, query, answers and answer classification with explanations.\"\"\"\n\nimport json\nimport os\nimport tensorflow.compat.v2 as tf\nimport tensorflow_datasets.public_api as tfds\n\n_CITATION = \"\"\"\n@unpublished{eraser2019,\n title = {ERASER: A Benchmark to Evaluate Rationalized NLP Models},\n author = {Jay DeYoung and Sarthak Jain and Nazneen Fatema Rajani and Eric Lehman and Caiming Xiong and Richard Socher and Byron C. Wallace}\n}\n@inproceedings{MultiRC2018,\n author = {Daniel Khashabi and Snigdha Chaturvedi and Michael Roth and Shyam Upadhyay and Dan Roth},\n title = {Looking Beyond the Surface:A Challenge Set for Reading Comprehension over Multiple Sentences},\n booktitle = {NAACL},\n year = {2018}\n}\n\"\"\"\n\n_DESCRIPTION = \"\"\"\nEraser Multi RC is a dataset for queries over multi-line passages, along with\nanswers and a rationalte. Each example in this dataset has the following 5 parts\n1. A Mutli-line Passage\n2. A Query about the passage\n3. An Answer to the query\n4. A Classification as to whether the answer is right or wrong\n5. An Explanation justifying the classification\n\"\"\"\n\n_DOWNLOAD_URL = 'http://www.eraserbenchmark.com/zipped/multirc.tar.gz'\n\n\nclass EraserMultiRc(tfds.core.GeneratorBasedBuilder):\n \"\"\"Multi Sentence Reasoning with Explanations (Eraser Benchmark).\"\"\"\n\n VERSION = tfds.core.Version('0.1.1')\n\n def _info(self):\n return tfds.core.DatasetInfo(\n builder=self,\n description=_DESCRIPTION,\n features=tfds.features.FeaturesDict({\n 'passage': tfds.features.Text(),\n 'query_and_answer': tfds.features.Text(),\n 'label': tfds.features.ClassLabel(names=['False', 'True']),\n 'evidences': tfds.features.Sequence(tfds.features.Text())\n }),\n supervised_keys=None,\n homepage='https://cogcomp.seas.upenn.edu/multirc/',\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager):\n \"\"\"Returns SplitGenerators.\"\"\"\n\n dl_dir = dl_manager.download_and_extract(_DOWNLOAD_URL)\n data_dir = os.path.join(dl_dir, 'multirc')\n return [\n tfds.core.SplitGenerator(\n name=tfds.Split.TRAIN,\n # These kwargs will be passed to _generate_examples\n gen_kwargs={'data_dir': data_dir,\n 'filepath': os.path.join(data_dir, 'train.jsonl')},\n ),\n tfds.core.SplitGenerator(\n name=tfds.Split.VALIDATION,\n # These kwargs will be passed to _generate_examples\n gen_kwargs={'data_dir': data_dir,\n 'filepath': os.path.join(data_dir, 'val.jsonl')},\n ),\n tfds.core.SplitGenerator(\n name=tfds.Split.TEST,\n # These kwargs will be passed to _generate_examples\n gen_kwargs={'data_dir': data_dir,\n 'filepath': os.path.join(data_dir, 'test.jsonl')},\n ),\n ]\n\n def _generate_examples(self, data_dir, filepath):\n \"\"\"Yields examples.\"\"\"\n\n multirc_dir = os.path.join(data_dir, 'docs')\n with tf.io.gfile.GFile(filepath) as f:\n for line in f:\n row = json.loads(line)\n evidences = []\n\n for evidence in row['evidences'][0]:\n docid = evidence['docid']\n evidences.append(evidence['text'])\n\n passage_file = os.path.join(multirc_dir, docid)\n with tf.io.gfile.GFile(passage_file) as f1:\n passage_text = f1.read()\n\n yield row['annotation_id'], {\n 'passage': passage_text,\n 'query_and_answer': row['query'],\n 'label': row['classification'],\n 'evidences': evidences\n }\n", "# coding=utf-8\n# Copyright 2020 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"reddit_disentanglement dataset.\"\"\"\n\nimport collections\nimport csv\nimport itertools\nimport os\n\nimport tensorflow.compat.v2 as tf\nimport tensorflow_datasets.public_api as tfds\n\n_CITATION = \"\"\"\n@article{zhu2019did,\n title={Who did They Respond to? Conversation Structure Modeling using Masked Hierarchical Transformer},\n author={Zhu, Henghui and Nan, Feng and Wang, Zhiguo and Nallapati, Ramesh and Xiang, Bing},\n journal={arXiv preprint arXiv:1911.10666},\n year={2019}\n}\n\"\"\"\n\n_DESCRIPTION = \"\"\"\nThis dataset contains ~3M messages from reddit.\nEvery message is labeled with metadata. The task is to predict the id of its\nparent message in the corresponding thread.\nEach record contains a list of messages from one thread.\nDuplicated and broken records are removed from the dataset.\n\n\nFeatures are:\n - id - message id\n - text - message text\n - author - message author\n - created_utc - message UTC timestamp\n - link_id - id of the post that the comment relates to\nTarget:\n - parent_id - id of the parent message in the current thread\n\"\"\"\n\n_THREAD_KEY = \"thread\"\n_MESSAGE_ID = \"id\"\n_MESSAGE_TEXT = \"text\"\n_MESSAGE_TIMESTAMP = \"created_utc\"\n_MESSAGE_AUTHOR = \"author\"\n_MESSAGE_LINK_ID = \"link_id\"\n_MESSAGE_PARENT_ID = \"parent_id\"\n\n\ndef _read_csv(path):\n with tf.io.gfile.GFile(path) as f:\n reader = csv.DictReader(f)\n for row in reader:\n if row[\"id\"]: # Filter out broken lines in the original dataset\n yield row\n\n\ndef _deduplicate(data):\n \"\"\"Remove duplicated records.\"\"\"\n cnt = collections.Counter(row[\"id\"] for row in data)\n nonuniq_ids = set(id for id, count in cnt.items() if count > 1)\n nonuniq_data = [row for row in data if row[\"id\"] in nonuniq_ids]\n\n unique_data = [row for row in data if row[\"id\"] not in nonuniq_ids]\n # Make sure same id records are next to each other for itertools.groupby\n nonuniq_data = sorted(nonuniq_data, key=lambda row: row[\"id\"])\n for _, same_id_data in itertools.groupby(nonuniq_data, lambda row: row[\"id\"]):\n same_id_data = list(same_id_data)\n if all(same_id_data[0] == x for x in same_id_data):\n unique_data.append(same_id_data[0])\n else:\n non_deleted_same_id_data = [row for row in same_id_data\n if row[\"author\"] != \"[deleted]\"]\n if len(non_deleted_same_id_data) != 1:\n raise ValueError(\"Found several message with id {} in the original\"\n \" data\".format(non_deleted_same_id_data[0][\"id\"]))\n unique_data.append(non_deleted_same_id_data[0])\n\n return sorted(unique_data,\n key=lambda row: (row[\"link_id\"], row[\"created_utc\"]))\n\n\nclass RedditDisentanglement(tfds.core.GeneratorBasedBuilder):\n \"\"\"Reddit Disentanglement dataset.\"\"\"\n\n VERSION = tfds.core.Version(\"2.0.0\")\n MANUAL_DOWNLOAD_INSTRUCTIONS = \"\"\"\\\n Download https://github.com/henghuiz/MaskedHierarchicalTransformer, decompress\n raw_data.zip and run generate_dataset.py with your reddit api credentials.\n Then put train.csv, val.csv and test.csv from the output directory into the\n manual folder.\n \"\"\"\n\n def _info(self):\n return tfds.core.DatasetInfo(\n builder=self,\n description=_DESCRIPTION,\n features=tfds.features.FeaturesDict({\n _THREAD_KEY: tfds.features.Sequence(\n tfds.features.FeaturesDict({\n _MESSAGE_ID: tfds.features.Text(),\n _MESSAGE_TEXT: tfds.features.Text(),\n _MESSAGE_TIMESTAMP: tfds.features.Text(),\n _MESSAGE_AUTHOR: tfds.features.Text(),\n _MESSAGE_LINK_ID: tfds.features.Text(),\n _MESSAGE_PARENT_ID: tfds.features.Text()\n }))}),\n homepage=\"https://github.com/henghuiz/MaskedHierarchicalTransformer\",\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager):\n \"\"\"Returns SplitGenerators.\"\"\"\n return [\n tfds.core.SplitGenerator(\n name=tfds.Split.TRAIN,\n gen_kwargs={\"path\": os.path.join(\n dl_manager.manual_dir, \"train.csv\")},\n ),\n tfds.core.SplitGenerator(\n name=tfds.Split.VALIDATION,\n gen_kwargs={\"path\": os.path.join(\n dl_manager.manual_dir, \"val.csv\")},\n ),\n tfds.core.SplitGenerator(\n name=tfds.Split.TEST,\n gen_kwargs={\"path\": os.path.join(\n dl_manager.manual_dir, \"test.csv\")},\n ),\n ]\n\n def _generate_examples(self, path):\n \"\"\"Yields examples.\"\"\"\n data = list(_read_csv(path))\n data = _deduplicate(data)\n for link_id, one_topic_data in itertools.groupby(\n data, lambda row: row[\"link_id\"]):\n one_topic_data = list(one_topic_data)\n for row in one_topic_data:\n row[\"text\"] = row.pop(\"body\")\n yield link_id, {_THREAD_KEY: one_topic_data}\n", "# coding=utf-8\n# Copyright 2020 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"CMATERdb dataset.\"\"\"\n\nimport numpy as np\nimport tensorflow.compat.v2 as tf\nimport tensorflow_datasets.public_api as tfds\n\n# CMATERdb constants\n_CMATERDB_IMAGE_SIZE = 32\n_CMATERDB_IMAGE_SHAPE = (_CMATERDB_IMAGE_SIZE, _CMATERDB_IMAGE_SIZE, 3)\n# GitHub npz mirror of https://code.google.com/archive/p/cmaterdb/\n_CMATERDB_TRAINING_URL = (\n \"https://raw.githubusercontent.com/prabhuomkar/CMATERdb/master/\"\n \"datasets/{type}-numerals/training-images.npz\")\n_CMATERDB_TESTING_URL = (\n \"https://raw.githubusercontent.com/prabhuomkar/CMATERdb/master/\"\n \"datasets/{type}-numerals/testing-images.npz\")\n\n_CITATION = \"\"\"\\\n@article{Das:2012:GAB:2161007.2161320,\n author = {Das, Nibaran and Sarkar, Ram and Basu, Subhadip and Kundu, Mahantapas \n and Nasipuri, Mita and Basu, Dipak Kumar},\n title = {A Genetic Algorithm Based Region Sampling for Selection of Local Features \n in Handwritten Digit Recognition Application},\n journal = {Appl. Soft Comput.},\n issue_date = {May, 2012},\n volume = {12},\n number = {5},\n month = may,\n year = {2012},\n issn = {1568-4946},\n pages = {1592--1606},\n numpages = {15},\n url = {http://dx.doi.org/10.1016/j.asoc.2011.11.030},\n doi = {10.1016/j.asoc.2011.11.030},\n acmid = {2161320},\n publisher = {Elsevier Science Publishers B. V.},\n address = {Amsterdam, The Netherlands, The Netherlands},\n keywords = {Feature selection, Genetic algorithm, N-Quality consensus, \n Optimal local regions, Region sampling, Variable sized local regions},\n}\n@article{Das:2012:SFC:2240301.2240421,\n author = {Das, Nibaran and Reddy, Jagan Mohan and Sarkar, Ram and Basu, Subhadip and Kundu, \n Mahantapas and Nasipuri, Mita and Basu, Dipak Kumar},\n title = {A Statistical-topological Feature Combination for Recognition of Handwritten Numerals},\n journal = {Appl. Soft Comput.},\n issue_date = {August, 2012},\n volume = {12},\n number = {8},\n month = aug,\n year = {2012},\n issn = {1568-4946},\n pages = {2486--2495},\n numpages = {10},\n url = {http://dx.doi.org/10.1016/j.asoc.2012.03.039},\n doi = {10.1016/j.asoc.2012.03.039},\n acmid = {2240421},\n publisher = {Elsevier Science Publishers B. V.},\n address = {Amsterdam, The Netherlands, The Netherlands},\n keywords = {Character recognition, Feature combination, MPCA, PCA, SVM, Statistical, Topological},\n}\n\"\"\"\n\n_DESCRIPTION = \"\"\"\\\nThis dataset contains images of -\n Handwritten Bangla numerals - balanced dataset of total 6000 Bangla numerals (32x32 RGB coloured, 6000 images), each having 600 images per class(per digit). \n Handwritten Devanagari numerals - balanced dataset of total 3000 Devanagari numerals (32x32 RGB coloured, 3000 images), each having 300 images per class(per digit). \n Handwritten Telugu numerals - balanced dataset of total 3000 Telugu numerals (32x32 RGB coloured, 3000 images), each having 300 images per class(per digit). \n\nCMATERdb is the pattern recognition database repository created at the 'Center for Microprocessor Applications for Training Education and Research' (CMATER) research lab, Jadavpur University, India.\n\"\"\"\n\n\nclass CmaterdbConfig(tfds.core.BuilderConfig):\n \"\"\"BuilderConfig for CMATERdb Config.\"\"\"\n\n\nclass Cmaterdb(tfds.core.GeneratorBasedBuilder):\n \"\"\"CMATERdb dataset.\"\"\"\n\n BUILDER_CONFIGS = [\n CmaterdbConfig(\n name=\"bangla\",\n description=\"CMATERdb Bangla Numerals\",\n version=\"1.0.0\",\n ),\n CmaterdbConfig(\n name=\"devanagari\",\n description=\"CMATERdb Devangari Numerals\",\n version=\"1.0.0\",\n ),\n CmaterdbConfig(\n name=\"telugu\",\n description=\"CMATERdb Telugu Numerals\",\n version=\"1.0.0\",\n ),\n ]\n\n def _info(self):\n return tfds.core.DatasetInfo(\n builder=self,\n description=_DESCRIPTION,\n features=tfds.features.FeaturesDict({\n \"image\": tfds.features.Image(shape=_CMATERDB_IMAGE_SHAPE),\n \"label\": tfds.features.ClassLabel(num_classes=10),\n }),\n supervised_keys=(\"image\", \"label\"),\n homepage=\"https://code.google.com/archive/p/cmaterdb/\",\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager):\n \"\"\"Returns SplitGenerators.\"\"\"\n # Download the CMATERdb dataset by mentioned numeral\n train_path, test_path = dl_manager.download([\n _CMATERDB_TRAINING_URL.format(type=self.builder_config.name),\n _CMATERDB_TESTING_URL.format(type=self.builder_config.name),\n ])\n\n # CMATERdb (mirrored) provides TRAIN and TEST splits,\n # not a VALIDATION split, so we only\n # write the TRAIN and TEST splits to disk.\n return [\n tfds.core.SplitGenerator(\n name=tfds.Split.TRAIN,\n gen_kwargs=dict(data_path=train_path),\n ),\n tfds.core.SplitGenerator(\n name=tfds.Split.TEST,\n gen_kwargs=dict(data_path=test_path),\n ),\n ]\n\n def _generate_examples(self, data_path):\n \"\"\"Generate CMATERdb examples as dicts.\n\n Args:\n data_path (str): Path to the data files\n\n Yields:\n Generator yielding the next examples\n \"\"\"\n with tf.io.gfile.GFile(data_path, mode=\"rb\") as f:\n data = np.load(f)\n\n data = list(zip(data[\"images\"], data[\"labels\"]))\n for index, (image, label) in enumerate(data):\n yield index, {\n \"image\": image,\n \"label\": label,\n }\n", "# coding=utf-8\n# Copyright 2020 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"https://www.kaggle.com/c/diabetic-retinopathy-detection/data.\n\"\"\"\n\nimport csv\nimport io\nimport os\n\nfrom absl import logging\nimport numpy as np\nimport tensorflow.compat.v2 as tf\nimport tensorflow_datasets.public_api as tfds\n\n\n_CITATION = \"\"\"\\\n@ONLINE {kaggle-diabetic-retinopathy,\n author = \"Kaggle and EyePacs\",\n title = \"Kaggle Diabetic Retinopathy Detection\",\n month = \"jul\",\n year = \"2015\",\n url = \"https://www.kaggle.com/c/diabetic-retinopathy-detection/data\"\n}\n\"\"\"\n_URL_TEST_LABELS = \"https://storage.googleapis.com/kaggle-forum-message-attachments/90528/2877/retinopathy_solution.csv\"\n_BTGRAHAM_DESCRIPTION_PATTERN = (\n \"Images have been preprocessed as the winner of the Kaggle competition did \"\n \"in 2015: first they are resized so that the radius of an eyeball is \"\n \"{} pixels, then they are cropped to 90% of the radius, and finally they \"\n \"are encoded with 72 JPEG quality.\")\n\n\nclass DiabeticRetinopathyDetectionConfig(tfds.core.BuilderConfig):\n \"\"\"BuilderConfig for DiabeticRetinopathyDetection.\"\"\"\n\n def __init__(self, target_pixels=None, **kwargs):\n \"\"\"BuilderConfig for DiabeticRetinopathyDetection.\n\n Args:\n target_pixels: If given, rescale the images so that the total number of\n pixels is roughly this value.\n **kwargs: keyword arguments forward to super.\n \"\"\"\n super(DiabeticRetinopathyDetectionConfig, self).__init__(\n version=tfds.core.Version(\n \"3.0.0\",\n \"New split API (https://tensorflow.org/datasets/splits)\"),\n **kwargs)\n self._target_pixels = target_pixels\n\n @property\n def target_pixels(self):\n return self._target_pixels\n\n\nclass DiabeticRetinopathyDetection(tfds.core.GeneratorBasedBuilder):\n \"\"\"Diabetic retinopathy detection.\"\"\"\n\n MANUAL_DOWNLOAD_INSTRUCTIONS = \"\"\"\\\n You have to download this dataset from Kaggle.\n https://www.kaggle.com/c/diabetic-retinopathy-detection/data\n After downloading, unpack the test.zip file into test/ directory in manual_dir\n and sample.zip to sample/. Also unpack the sampleSubmissions.csv and\n trainLabels.csv.\n \"\"\"\n\n BUILDER_CONFIGS = [\n DiabeticRetinopathyDetectionConfig(\n name=\"original\",\n description=\"Images at their original resolution and quality.\"),\n DiabeticRetinopathyDetectionConfig(\n name=\"1M\",\n description=\"Images have roughly 1,000,000 pixels, at 72 quality.\",\n target_pixels=1000000),\n DiabeticRetinopathyDetectionConfig(\n name=\"250K\",\n description=\"Images have roughly 250,000 pixels, at 72 quality.\",\n target_pixels=250000),\n DiabeticRetinopathyDetectionConfig(\n name=\"btgraham-300\",\n description=_BTGRAHAM_DESCRIPTION_PATTERN.format(300),\n target_pixels=300),\n ]\n\n def _info(self):\n return tfds.core.DatasetInfo(\n builder=self,\n description=\"A large set of high-resolution retina images taken under \"\n \"a variety of imaging conditions.\",\n features=tfds.features.FeaturesDict({\n \"name\": tfds.features.Text(), # patient ID + eye. eg: \"4_left\".\n \"image\": tfds.features.Image(),\n # From 0 (no DR - saine) to 4 (Proliferative DR). -1 means no label.\n \"label\": tfds.features.ClassLabel(num_classes=5),\n }),\n homepage=\"https://www.kaggle.com/c/diabetic-retinopathy-detection/data\",\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager):\n # TODO(pierrot): implement download using kaggle API.\n # TODO(pierrot): implement extraction of multiple files archives.\n path = dl_manager.manual_dir\n test_labels_path = dl_manager.download(_URL_TEST_LABELS)\n if tf.io.gfile.isdir(test_labels_path):\n # While testing: download() returns the dir containing the tests files.\n test_labels_path = os.path.join(test_labels_path,\n \"retinopathy_solution.csv\")\n return [\n tfds.core.SplitGenerator(\n name=\"sample\", # 10 images, to do quicktests using dataset.\n gen_kwargs={\n \"images_dir_path\": os.path.join(path, \"sample\"),\n },\n ),\n tfds.core.SplitGenerator(\n name=\"train\",\n gen_kwargs={\n \"images_dir_path\": os.path.join(path, \"train\"),\n \"csv_path\": os.path.join(path, \"trainLabels.csv\"),\n # CSV of the train split does not have the \"Usage\" column.\n # 35,126 examples.\n \"csv_usage\": None,\n },\n ),\n tfds.core.SplitGenerator(\n name=\"validation\",\n gen_kwargs={\n \"images_dir_path\": os.path.join(path, \"test\"),\n \"csv_path\": test_labels_path,\n # Validation split corresponds to the public leaderboard data.\n # 10,906 examples.\n \"csv_usage\": \"Public\",\n },\n ),\n tfds.core.SplitGenerator(\n name=\"test\",\n gen_kwargs={\n \"images_dir_path\": os.path.join(path, \"test\"),\n \"csv_path\": test_labels_path,\n # Test split corresponds to the public leaderboard data.\n # 42,670 examples.\n \"csv_usage\": \"Private\",\n },\n ),\n ]\n\n def _generate_examples(self, images_dir_path, csv_path=None, csv_usage=None):\n \"\"\"Yields Example instances from given CSV.\n\n Args:\n images_dir_path: path to dir in which images are stored.\n csv_path: optional, path to csv file with two columns: name of image and\n label. If not provided, just scan image directory, don't set labels.\n csv_usage: optional, subset of examples from the csv file to use based on\n the \"Usage\" column from the csv.\n \"\"\"\n if csv_path:\n with tf.io.gfile.GFile(csv_path) as csv_f:\n reader = csv.DictReader(csv_f)\n data = [(row[\"image\"], int(row[\"level\"]))\n for row in reader\n if csv_usage is None or row[\"Usage\"] == csv_usage]\n else:\n data = [(fname[:-5], -1)\n for fname in tf.io.gfile.listdir(images_dir_path)\n if fname.endswith(\".jpeg\")]\n for name, label in data:\n image_filepath = \"%s/%s.jpeg\" % (images_dir_path, name)\n record = {\n \"name\": name,\n \"image\": self._process_image(image_filepath),\n \"label\": label,\n }\n yield name, record\n\n def _process_image(self, filepath):\n with tf.io.gfile.GFile(filepath, mode=\"rb\") as image_fobj:\n if self.builder_config.name.startswith(\"btgraham\"):\n return _btgraham_processing(\n image_fobj=image_fobj,\n filepath=filepath,\n target_pixels=self.builder_config.target_pixels,\n crop_to_radius=True)\n else:\n return _resize_image_if_necessary(\n image_fobj=image_fobj,\n target_pixels=self.builder_config.target_pixels)\n\n\ndef _resize_image_if_necessary(image_fobj, target_pixels=None):\n \"\"\"Resize an image to have (roughly) the given number of target pixels.\n\n Args:\n image_fobj: File object containing the original image.\n target_pixels: If given, number of pixels that the image must have.\n\n Returns:\n A file object.\n \"\"\"\n if target_pixels is None:\n return image_fobj\n\n cv2 = tfds.core.lazy_imports.cv2\n # Decode image using OpenCV2.\n image = cv2.imdecode(\n np.fromstring(image_fobj.read(), dtype=np.uint8), flags=3)\n # Get image height and width.\n height, width, _ = image.shape\n actual_pixels = height * width\n if actual_pixels > target_pixels:\n factor = np.sqrt(target_pixels / actual_pixels)\n image = cv2.resize(image, dsize=None, fx=factor, fy=factor)\n # Encode the image with quality=72 and store it in a BytesIO object.\n _, buff = cv2.imencode(\".jpg\", image, [int(cv2.IMWRITE_JPEG_QUALITY), 72])\n return io.BytesIO(buff.tostring())\n\n\ndef _btgraham_processing(\n image_fobj, filepath, target_pixels, crop_to_radius=False):\n \"\"\"Process an image as the winner of the 2015 Kaggle competition.\n\n Args:\n image_fobj: File object containing the original image.\n filepath: Filepath of the image, for logging purposes only.\n target_pixels: The number of target pixels for the radius of the image.\n crop_to_radius: If True, crop the borders of the image to remove gray areas.\n\n Returns:\n A file object.\n \"\"\"\n cv2 = tfds.core.lazy_imports.cv2\n # Decode image using OpenCV2.\n image = cv2.imdecode(\n np.fromstring(image_fobj.read(), dtype=np.uint8), flags=3)\n # Process the image.\n image = _scale_radius_size(image, filepath, target_radius_size=target_pixels)\n image = _subtract_local_average(image, target_radius_size=target_pixels)\n image = _mask_and_crop_to_radius(\n image, target_radius_size=target_pixels, radius_mask_ratio=0.9,\n crop_to_radius=crop_to_radius)\n # Encode the image with quality=72 and store it in a BytesIO object.\n _, buff = cv2.imencode(\".jpg\", image, [int(cv2.IMWRITE_JPEG_QUALITY), 72])\n return io.BytesIO(buff.tostring())\n\n\ndef _scale_radius_size(image, filepath, target_radius_size):\n \"\"\"Scale the input image so that the radius of the eyeball is the given.\"\"\"\n cv2 = tfds.core.lazy_imports.cv2\n x = image[image.shape[0] // 2, :, :].sum(axis=1)\n r = (x > x.mean() / 10.0).sum() / 2.0\n if r < 1.0:\n # Some images in the dataset are corrupted, causing the radius heuristic to\n # fail. In these cases, just assume that the radius is the height of the\n # original image.\n logging.info(\"Radius of image \\\"%s\\\" could not be determined.\", filepath)\n r = image.shape[0] / 2.0\n s = target_radius_size / r\n return cv2.resize(image, dsize=None, fx=s, fy=s)\n\n\ndef _subtract_local_average(image, target_radius_size):\n cv2 = tfds.core.lazy_imports.cv2\n image_blurred = cv2.GaussianBlur(image, (0, 0), target_radius_size / 30)\n image = cv2.addWeighted(image, 4, image_blurred, -4, 128)\n return image\n\n\ndef _mask_and_crop_to_radius(\n image, target_radius_size, radius_mask_ratio=0.9, crop_to_radius=False):\n \"\"\"Mask and crop image to the given radius ratio.\"\"\"\n cv2 = tfds.core.lazy_imports.cv2\n mask = np.zeros(image.shape)\n center = (image.shape[1]//2, image.shape[0]//2)\n radius = int(target_radius_size * radius_mask_ratio)\n cv2.circle(mask, center=center, radius=radius, color=(1, 1, 1), thickness=-1)\n image = image * mask + (1 - mask) * 128\n if crop_to_radius:\n x_max = min(image.shape[1] // 2 + radius, image.shape[1])\n x_min = max(image.shape[1] // 2 - radius, 0)\n y_max = min(image.shape[0] // 2 + radius, image.shape[0])\n y_min = max(image.shape[0] // 2 - radius, 0)\n image = image[y_min:y_max, x_min:x_max, :]\n return image\n", "# coding=utf-8\n# Copyright 2020 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nr\"\"\"Generate CBIS-DDSM like files, smaller and with fake data.\n\n\"\"\"\n\nimport csv\nimport os\n\nfrom absl import app\nfrom absl import flags\n\nimport numpy as np\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_datasets.core.utils import py_utils\nimport tensorflow_datasets.public_api as tfds\n\nflags.DEFINE_string('tfds_dir', py_utils.tfds_dir(),\n 'Path to tensorflow_datasets directory')\nFLAGS = flags.FLAGS\n\nMAMMOGRAPHY_HEIGHT = 100 # Note: Much smaller than original images.\nMAMMOGRAPHY_WIDTH = 80\nABNORMALITY_SIZE_MIN = 10\nABNORMALITY_SIZE_MAX = 20\nNUM_ABNORMALITIES_MAX = 5\nBREAST_INTENSITY_MIN = 20\nBREAST_INTENSITY_MAX = 200\n\n\ndef remake_dirs(path):\n if not tf.io.gfile.exists(path):\n tf.io.gfile.makedirs(path)\n\n\ndef write_png(filepath, img):\n cv2 = tfds.core.lazy_imports.cv2\n with tf.io.gfile.GFile(filepath, 'wb') as f:\n _, buf = cv2.imencode('.png', img, (cv2.IMWRITE_PNG_COMPRESSION, 9))\n f.write(buf.tobytes())\n\n\ndef _yield_mammography_with_abnormalities():\n \"\"\"Generate a fake mammography image containing a set of abnormalities.\"\"\"\n mammography = np.zeros((MAMMOGRAPHY_HEIGHT, MAMMOGRAPHY_WIDTH),\n dtype=np.uint8)\n # Draw a rectangle representing the breast region.\n breast_h = np.random.randint(\n int(MAMMOGRAPHY_HEIGHT * 0.7), int(MAMMOGRAPHY_HEIGHT * 0.9) + 1)\n breast_w = np.random.randint(\n int(MAMMOGRAPHY_WIDTH * 0.7), int(MAMMOGRAPHY_WIDTH * 0.9) + 1)\n breast_y = np.random.randint(0, MAMMOGRAPHY_HEIGHT - breast_h)\n breast_x = np.random.randint(0, MAMMOGRAPHY_WIDTH - breast_w)\n breast_intensity = np.random.randint(BREAST_INTENSITY_MIN,\n BREAST_INTENSITY_MAX + 1)\n mammography[\n breast_y:(breast_y + breast_h),\n breast_x:(breast_x + breast_w)] = breast_intensity\n\n abnormalities = [] # Note: pairs of (mask, crop).\n for _ in range(np.random.randint(1, NUM_ABNORMALITIES_MAX + 1)):\n abnorm_h = np.random.randint(ABNORMALITY_SIZE_MIN, ABNORMALITY_SIZE_MAX + 1)\n abnorm_w = np.random.randint(ABNORMALITY_SIZE_MIN, ABNORMALITY_SIZE_MAX + 1)\n abnorm_y = np.random.randint(0, breast_h - abnorm_h) + breast_y\n abnorm_x = np.random.randint(0, breast_w - abnorm_w) + breast_x\n abnorm_intensity = np.random.randint(int(BREAST_INTENSITY_MIN * 1.2), 256)\n while np.absolute(abnorm_intensity - breast_intensity) < 10:\n abnorm_intensity = np.random.randint(int(BREAST_INTENSITY_MIN * 1.2), 256)\n # Draw abnormality in the mammography.\n mammography[\n abnorm_y:(abnorm_y + abnorm_h),\n abnorm_x:(abnorm_x + abnorm_w)] = abnorm_intensity\n # Abnormality mask w.r.t the full mammography.\n abnorm_mask = np.zeros_like(mammography)\n abnorm_mask[\n abnorm_y:(abnorm_y + abnorm_h), abnorm_x:(abnorm_x + abnorm_w)] = 255\n # Abnormality crop.\n abnorm_crop = np.ones((abnorm_h, abnorm_w)) * abnorm_intensity\n abnormalities.append((abnorm_mask, abnorm_crop))\n\n return mammography, abnormalities\n\n\ndef _yield_csv_rows_base(output_dir, row_extra_info_gen_fn):\n \"\"\"Yield rows for the CSV ground-truth files, also creates fake images.\"\"\"\n mammography, abnormalities = _yield_mammography_with_abnormalities()\n patient_id = 'P_%05d' % np.random.randint(0, 1000)\n breast_density = np.random.randint(1, 5)\n left_or_right_breast = np.random.choice(['LEFT', 'RIGHT'])\n image_view = np.random.choice(['CC', 'MLO'])\n study_id = tuple(np.random.randint(0, 999999999+1, size=2))\n study_id = '1.3.6.1.4.1.9590.100.1.2.%010d.%010d' % study_id\n series_id = tuple(np.random.randint(0, 999999999+1, size=2))\n series_id = '1.3.6.1.4.1.9590.100.1.2.%010d.%010d' % series_id\n remake_dirs(os.path.join(output_dir, '%s/%s' % (study_id, series_id)))\n # Write mammography image.\n mammography_basename = '%s/%s/000000' % (study_id, series_id)\n write_png(\n os.path.join(output_dir, mammography_basename + '.png'), mammography)\n\n for abnormality_id, abnormality in enumerate(abnormalities, 1):\n # Write abnormality crop image.\n crop_basename = '%s/%s/%06d' % (study_id, series_id, abnormality_id * 2 - 1)\n write_png(\n os.path.join(output_dir, crop_basename + '.png'), abnormality[1])\n # Write abnormality mask image.\n mask_basename = '%s/%s/%06d' % (study_id, series_id, abnormality_id * 2)\n write_png(\n os.path.join(output_dir, mask_basename + '.png'), abnormality[0])\n row = {\n 'patient_id': patient_id,\n 'breast density': breast_density,\n 'left or right breast': left_or_right_breast,\n 'image view': image_view,\n 'abnormality id': abnormality_id,\n 'abnormality type': 'calcification',\n 'assessment': np.random.randint(1, 5),\n 'pathology': np.random.choice(\n ['BENIGN', 'BENIGN_WITHOUT_CALLBACK', 'MALIGNANT']),\n 'subtlety': np.random.randint(1, 5),\n 'image file path': mammography_basename + '.dcm',\n 'cropped image file path': crop_basename + '.dcm',\n 'ROI mask file path': mask_basename + '.dcm',\n }\n row.update(row_extra_info_gen_fn())\n yield row\n\n\ndef _yield_csv_rows_calc(output_dir, calc_types, calc_distributions):\n \"\"\"Generate a row for the calcification abnormalities.\"\"\"\n def _row_extra_info_gen_fn():\n return {\n 'calc type': np.random.choice(calc_types),\n 'calc distribution': np.random.choice(calc_distributions),\n }\n\n return _yield_csv_rows_base(output_dir, _row_extra_info_gen_fn)\n\n\ndef _yield_csv_rows_mass(output_dir, mass_shapes, mass_margins):\n \"\"\"Generate a row for the mass abnormalities.\"\"\"\n def _row_extra_info_gen_fn():\n return {\n 'mass shape': np.random.choice(mass_shapes),\n 'mass margins': np.random.choice(mass_margins),\n }\n\n return _yield_csv_rows_base(output_dir, _row_extra_info_gen_fn)\n\n\ndef _generate_csv(csv_filepath, row_yielder, number_of_mammograms):\n \"\"\"Generate a csv file with `number_of_examples` mammograms.\"\"\"\n with tf.io.gfile.GFile(os.path.join(csv_filepath), 'w') as f:\n writer = None\n for _ in range(number_of_mammograms):\n for row in row_yielder():\n if writer is None:\n writer = csv.DictWriter(f, row.keys())\n writer.writeheader()\n writer.writerow(row)\n\n\ndef _generate_data_calc(output_dir, number_of_mammograms):\n \"\"\"Generate train/test CSV and images of calcification abnormalities.\"\"\"\n calc_types = tfds.features.ClassLabel(\n names_file=tfds.core.get_tfds_path(\n os.path.join('image', 'cbis_ddsm_calc_types.txt'))).names\n calc_distributions = tfds.features.ClassLabel(\n names_file=tfds.core.get_tfds_path(\n os.path.join('image', 'cbis_ddsm_calc_distributions.txt'))).names\n _generate_csv(\n os.path.join(output_dir, 'calc_case_description_train_set.csv'),\n lambda: _yield_csv_rows_calc(output_dir, calc_types, calc_distributions),\n number_of_mammograms[0])\n _generate_csv(\n os.path.join(output_dir, 'calc_case_description_test_set.csv'),\n lambda: _yield_csv_rows_calc(output_dir, calc_types, calc_distributions),\n number_of_mammograms[1])\n\n\ndef _generate_data_mass(output_dir, number_of_mammograms):\n \"\"\"Generate train/test CSV and images of mass abnormalities.\"\"\"\n mass_shapes = tfds.features.ClassLabel(\n names_file=tfds.core.get_tfds_path(\n os.path.join('image', 'cbis_ddsm_mass_shapes.txt'))).names\n mass_margins = tfds.features.ClassLabel(\n names_file=tfds.core.get_tfds_path(\n os.path.join('image', 'cbis_ddsm_mass_margins.txt'))).names\n\n _generate_csv(\n os.path.join(output_dir, 'mass_case_description_train_set.csv'),\n lambda: _yield_csv_rows_mass(output_dir, mass_shapes, mass_margins),\n number_of_mammograms[0])\n _generate_csv(\n os.path.join(output_dir, 'mass_case_description_test_set.csv'),\n lambda: _yield_csv_rows_mass(output_dir, mass_shapes, mass_margins),\n number_of_mammograms[1])\n\n\ndef main(_):\n output_dir = os.path.join(FLAGS.tfds_dir, 'testing', 'test_data',\n 'fake_examples', 'curated_breast_imaging_ddsm')\n np.random.seed(0x12345)\n _generate_data_calc(output_dir, (3, 2))\n _generate_data_mass(output_dir, (3, 2))\n\n\nif __name__ == '__main__':\n app.run(main)\n", "# coding=utf-8\n# Copyright 2020 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Classes and functions to generate the OI Challenge 2019 dataset using Apache Beam.\"\"\"\n\nimport collections\nimport csv\nimport io\nimport json\nimport os\n\nfrom absl import logging\nimport numpy as np\nimport tensorflow.compat.v2 as tf\nimport tensorflow_datasets.public_api as tfds\n\nbeam = tfds.core.lazy_imports.apache_beam\ncv2 = tfds.core.lazy_imports.cv2\n\nMetrics = beam.metrics.Metrics\n\n\nclass ReadZipFn(beam.DoFn):\n \"\"\"Iterates a zip file, yielding filenames and file contents.\"\"\"\n\n def process(self, zip_filepath):\n for filename, file in tfds.download.iter_archive(\n zip_filepath, tfds.download.ExtractMethod.ZIP):\n if filename.endswith(\".jpg\"):\n yield filename, file.read()\n\n\nclass ProcessImageFn(beam.DoFn):\n \"\"\"Resizes images, re-compresses them in JPEG and yields the result.\"\"\"\n\n def __init__(self, target_pixels, jpeg_quality=72):\n self._target_pixels = target_pixels\n self._jpeg_quality = [int(cv2.IMWRITE_JPEG_QUALITY), jpeg_quality]\n self._images_failed = Metrics.counter(self.__class__, \"images_failed\")\n\n def process(self, element):\n filename, content = element\n try:\n image = cv2.imdecode(np.fromstring(content, dtype=np.uint8), flags=3)\n except:\n logging.info(\"Exception raised while decoding image %s\", filename)\n raise\n if image is None:\n self._images_failed.inc()\n logging.info(\"Image %s could not be decoded\", filename)\n else:\n # GIF images contain a single frame.\n if len(image.shape) == 4: # rank=4 -> rank=3\n image = image.reshape(image.shape[1:])\n # Get image height and width.\n height, width, _ = image.shape\n actual_pixels = height * width\n # If necessary, resize the image to have at most self._target_pixels,\n # keeping the aspect ratio.\n if self._target_pixels and actual_pixels > self._target_pixels:\n factor = np.sqrt(self._target_pixels / actual_pixels)\n image = cv2.resize(image, dsize=None, fx=factor, fy=factor)\n # Encode the image with quality=72 and store it in a BytesIO object.\n _, buff = cv2.imencode(\".jpg\", image, self._jpeg_quality)\n yield filename, io.BytesIO(buff.tostring())\n\n\nclass CreateDetectionExampleFn(beam.DoFn):\n \"\"\"Creates TFDS examples for the Detection track.\"\"\"\n\n def __init__(self, image_labels_filepath, box_labels_filepath,\n hierarchy_filepath, classes_filepath):\n self._image_labels_filepath = image_labels_filepath\n self._box_labels_filepath = box_labels_filepath\n self._hierarchy_filepath = hierarchy_filepath\n self._classes_filepath = classes_filepath\n self._image2labels = None\n self._image2boxes = None\n self._hierarchy = None\n self._mid2int = None\n\n def start(self):\n if self._image_labels_filepath:\n self._image2labels = load_image_level_labels(self._image_labels_filepath)\n if self._box_labels_filepath:\n self._image2boxes = load_box_level_labels(self._box_labels_filepath)\n if self._hierarchy_filepath:\n self._hierarchy = load_class_hierarchy(self._hierarchy_filepath)\n if self._classes_filepath:\n class_descriptions = load_class_descriptions(self._classes_filepath)\n self._mid2int = {mid: i for i, (mid, _) in enumerate(class_descriptions)}\n\n def process(self, element):\n filename, image_bytes = element\n image_id = os.path.basename(filename).split(\".\")[0]\n # Image-level annotations.\n objects = []\n if self._image2labels:\n for label, source, confidence in self._image2labels[image_id]:\n objects.append({\n \"label\": self._mid2int[label],\n \"source\": source,\n \"confidence\": confidence,\n })\n # Bounding box-level annotations.\n bobjects = []\n if self._image2boxes:\n for annotation in self._image2boxes[image_id]:\n label, xmin, xmax, ymin, ymax, is_group_of = annotation\n bbox = tfds.features.BBox(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax)\n bobjects.append({\n \"label\": self._mid2int[label],\n \"bbox\": bbox,\n \"is_group_of\": is_group_of,\n })\n\n yield image_id, {\n \"id\": image_id,\n \"image\": image_bytes,\n \"objects\": objects,\n \"bobjects\": bobjects,\n }\n\n\ndef load_image_level_labels(filepath):\n \"\"\"Returns a dictionary mapping image IDs to a list of image-level labels.\"\"\"\n image2labels = collections.defaultdict(list)\n with tf.io.gfile.GFile(filepath, \"r\") as csvfile:\n reader = csv.reader(csvfile)\n next(reader) # Skip header.\n for row in reader:\n if len(row) == 3:\n image_id, label, confidence = row\n source = \"verification\"\n elif len(row) == 4:\n image_id, source, label, confidence = row\n image2labels[image_id].append((label, source, float(confidence)))\n return image2labels\n\n\ndef load_box_level_labels(filepath):\n \"\"\"Returns a dictionary mapping image IDs to a list of bounding box annotations.\"\"\"\n image2boxes = collections.defaultdict(list)\n with tf.io.gfile.GFile(filepath, \"r\") as csvfile:\n reader = csv.reader(csvfile)\n next(reader) # Skip header.\n for row in reader:\n if len(row) == 7:\n image_id, label, xmin_s, xmax_s, ymin_s, ymax_s, is_group_of_s = row\n elif len(row) == 13:\n image_id, label = row[0], row[2]\n xmin_s, xmax_s, ymin_s, ymax_s = row[4:8]\n is_group_of_s = row[10]\n xmin, xmax, ymin, ymax = map(float, (xmin_s, xmax_s, ymin_s, ymax_s))\n is_group_of = bool(int(is_group_of_s))\n image2boxes[image_id].append((label, xmin, xmax, ymin, ymax, is_group_of))\n return image2boxes\n\n\ndef load_class_hierarchy(filepath):\n with tf.io.gfile.GFile(filepath, \"r\") as jsonfile:\n return json.load(jsonfile)\n\n\ndef load_class_descriptions(filepath):\n with tf.io.gfile.GFile(filepath, \"r\") as csvfile:\n reader = csv.reader(csvfile)\n # Note: this file doesn't have any header.\n return [row for row in reader]\n\n\ndef fill_class_names_in_tfds_info(classes_filepath, tfds_info_features):\n \"\"\"Fills the class names in ClassLabel features.\"\"\"\n class_descriptions = load_class_descriptions(classes_filepath)\n mids = [mid for mid, _ in class_descriptions]\n tfds_info_features[\"objects\"][\"label\"].names = mids\n tfds_info_features[\"bobjects\"][\"label\"].names = mids\n", "# coding=utf-8\n# Copyright 2020 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# coding=utf-8\n\"\"\"Tests for tensorflow_datasets.core.features.text.subword_text_encoder.\"\"\"\nfrom __future__ import unicode_literals\n\nimport os\n\nfrom absl.testing import parameterized\nimport tensorflow.compat.v2 as tf\nfrom tensorflow_datasets import testing\nfrom tensorflow_datasets.core.features.text import subword_text_encoder\nfrom tensorflow_datasets.core.features.text import text_encoder\nfrom tensorflow_datasets.core.utils import py_utils\n\nTEST_DATA_DIR = os.path.join(py_utils.tfds_dir(), 'testing', 'test_data')\n\n\nclass SubwordTextEncoderTest(parameterized.TestCase, testing.TestCase):\n\n def setUp(self):\n super(SubwordTextEncoderTest, self).setUp()\n # Vocab ids will be (offset for pad=0):\n # 1 2 3 4 5\n self.vocab_list = ['foo_', 'bar_', 'foo', 'bar', '<EOS>']\n self.encoder = subword_text_encoder.SubwordTextEncoder(\n vocab_list=self.vocab_list)\n\n def test_vocab_size(self):\n # Bytes + pad + subwords\n self.assertEqual((256 + 1 + len(self.vocab_list)), self.encoder.vocab_size)\n\n @parameterized.parameters(\n ('foo bar', [1, 4]),\n ('foobar foo bar<EOS>bar', [3, 2, 1, 4, 5, 4]),\n # Respects whitespace\n ('bar <EOS>bar', [2, 5, 4]),\n ('bar <EOS> bar', [2, 5, 38, 4]),\n ('bar<EOS> bar', [4, 5, 38, 4]),\n # Invertible even with oov, respecting underscores and backslashes\n ('a_b!', [103, 101, 104, 39]),\n ('foo \\\\bar_!', [3, 38, 98, 4, 101, 39]),\n ('foo \\\\\\\\bar_!', [3, 38, 98, 98, 4, 101, 39]),\n ('hello world!', None),\n ('foo_ bar', None),\n ('foo _ bar', None),\n ('foo _bar', None),\n ('hello_world', None),\n ('hello_ world', None),\n ('hello _ world', None),\n ('hello _world', None),\n ('_', None),\n # Test that the underscore replacement string is unharmed\n ('\\\\&undsc', None),\n # Unicode encoded as bytes but decoded back to unicode character\n ('你', [234, 195, 166]),\n )\n def test_encode_decode(self, text, expected_ids):\n ids = self.encoder.encode(text)\n # Test ids match if ids provided\n if expected_ids:\n self.assertEqual(expected_ids, ids)\n # Test invertibility\n self.assertEqual(tf.compat.as_text(text), self.encoder.decode(ids))\n\n def test_bad_bytes(self):\n valid_unicode = '你'\n bad_bytes = [220 + len(self.vocab_list) + 1]\n bad_ids = self.encoder.encode('你') + bad_bytes\n text = self.encoder.decode(bad_ids)\n # Valid unicode character preserved\n self.assertEqual(valid_unicode, text[0])\n # Invalid byte converted to unknown character\n self.assertEqual('\\uFFFD', text[1])\n\n def test_vocab_file(self):\n vocab_file = os.path.join(self.get_temp_dir(), 'vocab')\n self.encoder.save_to_file(vocab_file)\n encoder = subword_text_encoder.SubwordTextEncoder.load_from_file(vocab_file)\n self.assertEqual(encoder.subwords, self.vocab_list)\n\n\nclass SubwordTextEncoderBuildTest(testing.TestCase):\n\n def test_build(self):\n text_gen = lorem_ipsum_generator\n build_fn = subword_text_encoder.SubwordTextEncoder.build_from_corpus\n encoder = build_fn(text_gen(), 300)\n # Created some subwords\n self.assertGreater(encoder.vocab_size, text_encoder.NUM_BYTES + 1)\n\n base_encoder = subword_text_encoder.SubwordTextEncoder(vocab_list=[])\n for line in text_gen():\n # Invertible\n encoded = encoder.encode(line)\n self.assertEqual(line, encoder.decode(encoded))\n # Shorter than base\n if len(line) > 2:\n self.assertLess(len(encoded), len(base_encoder.encode(line)))\n\n def test_build_with_unicode(self):\n text_gen = lorem_ipsum_zh_generator\n build_fn = subword_text_encoder.SubwordTextEncoder.build_from_corpus\n encoder = build_fn(text_gen(), 300)\n # Created some subwords\n self.assertGreater(encoder.vocab_size, text_encoder.NUM_BYTES + 1)\n\n base_encoder = subword_text_encoder.SubwordTextEncoder(vocab_list=[])\n for line in text_gen():\n # Invertible\n encoded = encoder.encode(line)\n self.assertEqual(line, encoder.decode(encoded))\n # Shorter than base\n if len(line) > 2:\n self.assertLess(len(encoded), len(base_encoder.encode(line)))\n\n def test_max_subword_length(self):\n text_gen = lorem_ipsum_generator\n build_fn = subword_text_encoder.SubwordTextEncoder.build_from_corpus\n encoder = build_fn(text_gen(), 300, max_subword_length=1)\n # Created no subwords because there are no unicode characters in lorem ipsum\n # and single byte subwords are skipped because all bytes are in the vocab by\n # default.\n self.assertEqual(encoder.vocab_size, text_encoder.NUM_BYTES + 1)\n self.assertEqual(len(encoder.subwords), 0)\n\n # Not the case when there are unicode characters\n text_gen = lorem_ipsum_zh_generator\n build_fn = subword_text_encoder.SubwordTextEncoder.build_from_corpus\n encoder = build_fn(text_gen(), 300, max_subword_length=1)\n self.assertGreater(encoder.vocab_size, text_encoder.NUM_BYTES + 1)\n self.assertGreater(len(encoder.subwords), 0)\n\n def test_max_chars(self):\n text_gen = lorem_ipsum_zh_generator\n build_fn = subword_text_encoder.SubwordTextEncoder.build_from_corpus\n encoder = build_fn(text_gen(), 300, max_corpus_chars=1)\n self.assertGreater(encoder.vocab_size, text_encoder.NUM_BYTES + 1)\n self.assertEqual(1, len(encoder.subwords))\n first_letter = next(lorem_ipsum_zh_generator())[0]\n self.assertEqual(first_letter, encoder.subwords[0])\n\n def test_reserved_tokens(self):\n text_gen = lorem_ipsum_generator\n build_fn = subword_text_encoder.SubwordTextEncoder.build_from_corpus\n encoder = build_fn(text_gen(), 300, reserved_tokens=['<EOS>', '<EOD>'])\n self.assertEqual(2, encoder.encode('Lorem<EOD>')[-1])\n self.assertEqual(2, encoder.encode('Lorem<EOD>a')[-2])\n self.assertEqual(2, encoder.encode('Lorem<EOD>{')[-2])\n self.assertEqual(2, encoder.encode('Lorem<EOD> ')[-2])\n self.assertEqual('<EOS> <EOD>', encoder.decode([1, 78, 2]))\n self.assertEqual(['<EOS>', '<EOD>'], encoder.subwords[:2])\n\n\ndef _yield_lines_from_file(txt_file):\n with tf.io.gfile.GFile(txt_file, 'rb') as f:\n for line in f:\n yield tf.compat.as_text(line)\n\n\ndef lorem_ipsum_generator():\n txt_file = os.path.join(TEST_DATA_DIR, 'lorem_ipsum.txt')\n return _yield_lines_from_file(txt_file)\n\n\ndef lorem_ipsum_zh_generator():\n txt_file = os.path.join(TEST_DATA_DIR, 'lorem_ipsum_zh.txt')\n return _yield_lines_from_file(txt_file)\n\n\nif __name__ == '__main__':\n testing.test_main()\n", "# coding=utf-8\n# Copyright 2020 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"opus dataset.\"\"\"\n\nimport os\nfrom absl import logging\nimport tensorflow.compat.v2 as tf\nimport tensorflow_datasets.public_api as tfds\n\n_CITATION = \"\"\"\n@inproceedings{Tiedemann2012ParallelData,\n author = {Tiedemann, J},\n title = {Parallel Data, Tools and Interfaces in OPUS},\n booktitle = {LREC}\n year = {2012}}\n\"\"\"\n\n_DESCRIPTION = \"\"\"\nOPUS is a collection of translated texts from the web.\n\nCreate your own config to choose which data / language pair to load.\n\n```\nconfig = tfds.translate.opus.OpusConfig(\n version=tfds.core.Version('0.1.0'),\n language_pair=(\"de\", \"en\"),\n subsets=[\"GNOME\", \"EMEA\"]\n)\nbuilder = tfds.builder(\"opus\", config=config)\n```\n\"\"\"\n\n\nclass SubDataset():\n \"\"\"Class to keep track of information on a sub-dataset of OPUS.\"\"\"\n\n def __init__(self, name, description, homepage, url, languages):\n \"\"\"Sub-dataset of OPUS.\n\n Args:\n name: `string`, a unique dataset identifier.\n description: `string`, a description of the dataset.\n homepage: `string`, homepage of the dataset.\n url: `string`, download url for the dataset.\n languages: `<list>(string)`, a list of supported languages.\n \"\"\"\n self.name = name\n self.description = description\n self.homepage = homepage\n self.url = url\n\n sorted_languages = sorted(languages)\n language_pairs = []\n for idx, source in enumerate(sorted_languages):\n for target in sorted_languages[idx + 1:]:\n language_pairs.append((source, target))\n\n self.language_pairs = language_pairs\n\nDATASET_MAP = {ds.name: ds for ds in [ # pylint:disable=g-complex-comprehension\n # pylint:disable=line-too-long\n SubDataset(\n name=\"EMEA\",\n description=\"A parallel corpus made out of PDF documents from the European Medicines Agency.\",\n homepage=\"http://opus.nlpl.eu/EMEA.php\",\n url=\"http://opus.nlpl.eu/download.php?f=EMEA/v3/moses/\",\n languages=[\"bg\", \"cs\", \"da\", \"de\", \"el\", \"en\", \"es\", \"et\", \"fi\", \"fr\", \"hu\", \"it\", \"lt\", \"lv\", \"mt\", \"nl\", \"pl\", \"pt\", \"ro\", \"sk\", \"sl\", \"sv\"]\n ),\n SubDataset(\n name=\"JRC-Acquis\",\n description=\"A collection of legislative text of the European Union and currently comprises selected texts written between the 1950s and now.\",\n homepage=\"http://opus.nlpl.eu/JRC-Acquis.php\",\n url=\"http://opus.nlpl.eu/download.php?f=JRC-Acquis/\",\n languages=[\"bg\", \"cs\", \"da\", \"de\", \"el\", \"en\", \"es\", \"et\", \"fi\", \"fr\", \"hu\", \"it\", \"lt\", \"lv\", \"mt\", \"nl\", \"pl\", \"pt\", \"ro\", \"sk\", \"sl\", \"sv\"]\n ),\n SubDataset(\n name=\"Tanzil\",\n description=\"A collection of Quran translations compiled by the Tanzil project.\",\n homepage=\"http://opus.nlpl.eu/Tanzil.php\",\n url=\"http://opus.nlpl.eu/download.php?f=Tanzil/v1/moses/\",\n languages=[\"am\", \"ar\", \"az\", \"bg\", \"bn\", \"bs\", \"cs\", \"de\", \"dv\", \"en\", \"es\", \"fa\", \"fr\", \"ha\", \"hi\", \"id\", \"it\", \"ja\", \"ko\", \"ku\", \"ml\", \"ms\", \"nl\", \"no\", \"pl\", \"pt\", \"ro\", \"ru\", \"sd\", \"so\", \"sq\", \"sv\", \"sw\", \"ta\", \"tg\", \"th\", \"tr\", \"tt\", \"ug\", \"ur\", \"uz\", \"zh\"]\n ),\n SubDataset(\n name=\"GNOME\",\n description=\"A parallel corpus of GNOME localization files. Source: https://l10n.gnome.org\",\n homepage=\"http://opus.nlpl.eu/GNOME.php\",\n url=\"http://opus.nlpl.eu/download.php?f=GNOME/v1/moses/\",\n languages=[\"af\", \"am\", \"an\", \"ang\", \"ar\", \"ar_TN\", \"ara\", \"as\", \"ast\", \"az\", \"az_IR\", \"bal\", \"be\", \"bem\", \"bg\", \"bg_BG\", \"bn\", \"bn_IN\", \"bo\", \"br\", \"brx\", \"bs\", \"ca\", \"cat\", \"crh\", \"cs\", \"csb\", \"cy\", \"da\", \"da_DK\", \"de\", \"de_CH\", \"dv\", \"dz\", \"el\", \"en\", \"en_AU\", \"en_CA\", \"en_GB\", \"en_NZ\", \"en_US\", \"en_ZA\", \"eo\", \"es\", \"es_AR\", \"es_CL\", \"es_CO\", \"es_CR\", \"es_DO\", \"es_EC\", \"es_ES\", \"es_GT\", \"es_HN\", \"es_MX\", \"es_NI\", \"es_PA\", \"es_PE\", \"es_PR\", \"es_SV\", \"es_UY\", \"es_VE\", \"et\", \"eu\", \"fa\", \"fa_IR\", \"fi\", \"fo\", \"foo\", \"fr\", \"fur\", \"fy\", \"ga\", \"gd\", \"gl\", \"gn\", \"gr\", \"gu\", \"gv\", \"ha\", \"he\", \"hi\", \"hi_IN\", \"hr\", \"hu\", \"hy\", \"ia\", \"id\", \"ig\", \"io\", \"is\", \"it\", \"it_IT\", \"ja\", \"jbo\", \"ka\", \"kg\", \"kk\", \"km\", \"kn\", \"ko\", \"kr\", \"ks\", \"ku\", \"ky\", \"la\", \"lg\", \"li\", \"lo\", \"lt\", \"lv\", \"mai\", \"mg\", \"mi\", \"mk\", \"ml\", \"mn\", \"mr\", \"ms\", \"ms_MY\", \"mt\", \"mus\", \"my\", \"nb\", \"nb_NO\", \"nds\", \"ne\", \"nhn\", \"nl\", \"nn\", \"nn_NO\", \"no\", \"no_nb\", \"nqo\", \"nr\", \"nso\", \"oc\", \"or\", \"os\", \"pa\", \"pl\", \"ps\", \"pt\", \"pt_BR\", \"pt_PT\", \"quz\", \"ro\", \"ru\", \"rw\", \"si\", \"sk\", \"sl\", \"so\", \"sq\", \"sr\", \"sr_ME\", \"st\", \"sv\", \"sw\", \"szl\", \"ta\", \"te\", \"tg\", \"tg_TJ\", \"th\", \"tk\", \"tl\", \"tl_PH\", \"tmp\", \"tr\", \"tr_TR\", \"ts\", \"tt\", \"ug\", \"uk\", \"ur\", \"ur_PK\", \"uz\", \"vi\", \"vi_VN\", \"wa\", \"xh\", \"yi\", \"yo\", \"zh_CN\", \"zh_HK\", \"zh_TW\", \"zu\"]\n ),\n SubDataset(\n name=\"KDE4\",\n description=\"A parallel corpus of KDE4 localization files (v.2).\",\n homepage=\"http://opus.nlpl.eu/KDE4.php\",\n url=\"http://opus.nlpl.eu/download.php?f=KDE4/v2/moses/\",\n languages=[\"af\", \"ar\", \"as\", \"ast\", \"be\", \"bg\", \"bn\", \"bn_IN\", \"br\", \"ca\", \"crh\", \"cs\", \"csb\", \"cy\", \"da\", \"de\", \"el\", \"en\", \"en_GB\", \"eo\", \"es\", \"et\", \"eu\", \"fa\", \"fi\", \"fr\", \"fy\", \"ga\", \"gl\", \"gu\", \"ha\", \"he\", \"hi\", \"hne\", \"hr\", \"hsb\", \"hu\", \"hy\", \"id\", \"is\", \"it\", \"ja\", \"ka\", \"kk\", \"km\", \"kn\", \"ko\", \"ku\", \"lb\", \"lt\", \"lv\", \"mai\", \"mk\", \"ml\", \"mr\", \"ms\", \"mt\", \"nb\", \"nds\", \"ne\", \"nl\", \"nn\", \"nso\", \"oc\", \"or\", \"pa\", \"pl\", \"ps\", \"pt\", \"pt_BR\", \"ro\", \"ru\", \"rw\", \"se\", \"si\", \"sk\", \"sl\", \"sr\", \"sv\", \"ta\", \"te\", \"tg\", \"th\", \"tr\", \"uk\", \"uz\", \"vi\", \"wa\", \"xh\", \"zh_CN\", \"zh_HK\", \"zh_TW\"]\n ),\n SubDataset(\n name=\"PHP\",\n description=\"A parallel corpus originally extracted from http://se.php.net/download-docs.php.\",\n homepage=\"http://opus.nlpl.eu/PHP.php\",\n url=\"http://opus.nlpl.eu/download.php?f=PHP/v1/moses/\",\n languages=[\"cs\", \"de\", \"en\", \"es\", \"fi\", \"fr\", \"he\", \"hu\", \"it\", \"ja\", \"ko\", \"nl\", \"pl\", \"pt_BR\", \"ro\", \"ru\", \"sk\", \"sl\", \"sv\", \"tr\", \"tw\", \"zh\", \"zh_TW\"]\n ),\n SubDataset(\n name=\"Ubuntu\",\n description=\"A parallel corpus of Ubuntu localization files. Source: https://translations.launchpad.net\",\n homepage=\"http://opus.nlpl.eu/Ubuntu.php\",\n url=\"http://opus.nlpl.eu/download.php?f=Ubuntu/v14.10/moses/\",\n languages=[\"ace\", \"af\", \"ak\", \"am\", \"an\", \"ang\", \"ar\", \"ar_SY\", \"ary\", \"as\", \"ast\", \"az\", \"ba\", \"bal\", \"be\", \"bem\", \"ber\", \"bg\", \"bho\", \"bn\", \"bn_IN\", \"bo\", \"br\", \"brx\", \"bs\", \"bua\", \"byn\", \"ca\", \"ce\", \"ceb\", \"chr\", \"ckb\", \"co\", \"crh\", \"cs\", \"csb\", \"cv\", \"cy\", \"da\", \"de\", \"de_AT\", \"de_DE\", \"dsb\", \"dv\", \"dz\", \"el\", \"en\", \"en_AU\", \"en_CA\", \"en_GB\", \"en_NZ\", \"en_US\", \"eo\", \"es\", \"es_AR\", \"es_CL\", \"es_CO\", \"es_CR\", \"es_DO\", \"es_EC\", \"es_ES\", \"es_GT\", \"es_HN\", \"es_MX\", \"es_NI\", \"es_PA\", \"es_PE\", \"es_PR\", \"es_SV\", \"es_UY\", \"es_VE\", \"et\", \"eu\", \"fa\", \"fa_AF\", \"ff\", \"fi\", \"fil\", \"fo\", \"fr\", \"fr_CA\", \"fr_FR\", \"frm\", \"frp\", \"fur\", \"fy\", \"ga\", \"gd\", \"gl\", \"gn\", \"grc\", \"gu\", \"guc\", \"gv\", \"ha\", \"haw\", \"he\", \"hi\", \"hil\", \"hne\", \"hr\", \"hsb\", \"ht\", \"hu\", \"hy\", \"ia\", \"id\", \"ig\", \"io\", \"is\", \"it\", \"iu\", \"ja\", \"jbo\", \"jv\", \"ka\", \"kab\", \"kg\", \"kk\", \"kl\", \"km\", \"kn\", \"ko\", \"kok\", \"ks\", \"ksh\", \"ku\", \"kw\", \"ky\", \"la\", \"lb\", \"lg\", \"li\", \"lij\", \"lld\", \"ln\", \"lo\", \"lt\", \"ltg\", \"lv\", \"mai\", \"mg\", \"mh\", \"mhr\", \"mi\", \"miq\", \"mk\", \"ml\", \"mn\", \"mo\", \"mr\", \"ms\", \"mt\", \"mus\", \"my\", \"nan\", \"nap\", \"nb\", \"nds\", \"ne\", \"nhn\", \"nl\", \"nl_NL\", \"nn\", \"no\", \"nso\", \"ny\", \"oc\", \"oj\", \"om\", \"or\", \"os\", \"pa\", \"pam\", \"pap\", \"pl\", \"pms\", \"pmy\", \"ps\", \"pt\", \"pt_BR\", \"pt_PT\", \"qu\", \"rm\", \"ro\", \"rom\", \"ru\", \"rw\", \"sa\", \"sc\", \"sco\", \"sd\", \"se\", \"shn\", \"shs\", \"si\", \"sk\", \"sl\", \"sm\", \"sml\", \"sn\", \"so\", \"son\", \"sq\", \"sr\", \"st\", \"sv\", \"sw\", \"syr\", \"szl\", \"ta\", \"ta_LK\", \"te\", \"tet\", \"tg\", \"th\", \"ti\", \"tk\", \"tl\", \"tlh\", \"tr\", \"trv\", \"ts\", \"tt\", \"ug\", \"uk\", \"ur\", \"uz\", \"ve\", \"vec\", \"vi\", \"wa\", \"wae\", \"wo\", \"xal\", \"xh\", \"yi\", \"yo\", \"zh\", \"zh_CN\", \"zh_HK\", \"zh_TW\", \"zu\", \"zza\"]\n ),\n SubDataset(\n name=\"OpenOffice\",\n description=\"A collection of documents from http://www.openoffice.org/.\",\n homepage=\"http://opus.nlpl.eu/OpenOffice-v2.php\",\n url=\"http://opus.nlpl.eu/download.php?f=OpenOffice/v2/moses/\",\n languages=[\"de\", \"en\", \"es\", \"fr\", \"jp\", \"sv\"]\n ),\n SubDataset(\n name=\"OpenSubtitles\",\n description=\"A new collection of translated movie subtitles from http://www.opensubtitles.org/\",\n homepage=\"http://opus.nlpl.eu/OpenSubtitles-v2018.php\",\n url=\"http://opus.nlpl.eu/download.php?f=OpenSubtitles/v2018/moses/\",\n languages=[\"af\", \"ar\", \"bg\", \"bn\", \"br\", \"bs\", \"ca\", \"cs\", \"da\", \"de\", \"el\", \"en\", \"eo\", \"es\", \"et\", \"eu\", \"fa\", \"fi\", \"fr\", \"gl\", \"he\", \"hi\", \"hr\", \"hu\", \"hy\", \"id\", \"is\", \"it\", \"ja\", \"ka\", \"kk\", \"ko\", \"lt\", \"lv\", \"mk\", \"ml\", \"ms\", \"nl\", \"no\", \"pl\", \"pt\", \"pt_br\", \"ro\", \"ru\", \"si\", \"sk\", \"sl\", \"sq\", \"sr\", \"sv\", \"ta\", \"te\", \"th\", \"tl\", \"tr\", \"uk\", \"ur\", \"vi\", \"ze_en\", \"ze_zh\", \"zh_cn\", \"zh_tw\"]\n )\n]}\n\n\nclass OpusConfig(tfds.core.BuilderConfig):\n \"\"\"BuilderConfig for Opus.\"\"\"\n\n def __init__(self, *, language_pair, subsets, **kwargs):\n \"\"\"BuilderConfig for Opus.\n\n Args:\n language_pair: `(string, string)`, pair of languages used for translation.\n Should contain 2 letter coded strings (e.g. \"de\", \"en\")\n subsets: `<list>(string)`, list of the subdatasets to use.\n **kwargs: keyword arguments forwarded to super.\n \"\"\"\n sorted_language_pair = sorted(language_pair)\n name = kwargs.get(\"name\", \"%s-%s for %s\" % (\n sorted_language_pair[0], sorted_language_pair[1], \", \".join(subsets)))\n\n description = name + \" documents\"\n\n super(OpusConfig, self).__init__(\n description=description, **dict(kwargs, name=name))\n\n self.language_pair = sorted_language_pair\n self.subsets = subsets\n\n\nclass Opus(tfds.core.GeneratorBasedBuilder):\n \"\"\"OPUS is a collection of translated texts from the web.\"\"\"\n\n _KK_SUBSETS = [\n (\"medical\", [\"EMEA\"]),\n (\"law\", [\"JRC-Acquis\"]),\n (\"koran\", [\"Tanzil\"]),\n (\"IT\", [\"GNOME\", \"KDE4\", \"PHP\", \"Ubuntu\", \"OpenOffice\"]),\n (\"subtitles\", [\"OpenSubtitles\"])\n ]\n\n \"\"\"The following configurations reproduce the evaluation tasks from \"Six\n Challenges for Neural Machine Translation\" by Philipp Koehn and Rebecca\n Knowles (2017) https://www.aclweb.org/anthology/W17-3204.pdf\"\"\"\n BUILDER_CONFIGS = [\n OpusConfig( # pylint:disable=g-complex-comprehension\n version=tfds.core.Version(\"0.1.0\"),\n language_pair=(\"de\", \"en\"),\n subsets=subsets,\n name=name\n ) for name, subsets in _KK_SUBSETS\n ]\n\n @property\n def subsets(self):\n # Return only the datasets that exist for the language pair.\n source, target = self.builder_config.language_pair\n filtered_subsets = []\n for dataset in [DATASET_MAP[name] for name in self.builder_config.subsets]:\n if (source, target) in dataset.language_pairs:\n filtered_subsets.append(dataset)\n\n return filtered_subsets\n\n def _info(self):\n src, target = self.builder_config.language_pair\n return tfds.core.DatasetInfo(\n builder=self,\n description=_DESCRIPTION + \"\\n\" + self.builder_config.description,\n features=tfds.features.Translation(\n languages=self.builder_config.language_pair),\n supervised_keys=(src, target),\n homepage=\"http://opus.nlpl.eu/\",\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager):\n source, target = self.builder_config.language_pair\n file_ext = \"%s-%s\"%(source, target)\n\n subsets = []\n for item in self.subsets:\n dl_dir = dl_manager.download_and_extract(\n os.path.join(item.url, \"%s.txt.zip\"%file_ext))\n source_file = os.path.join(\n dl_dir, \"%s.%s.%s\"%(item.name, file_ext, source))\n target_file = os.path.join(\n dl_dir, \"%s.%s.%s\"%(item.name, file_ext, target))\n subsets.append({\n \"name\": item.name,\n \"source_file\": source_file,\n \"target_file\": target_file\n })\n\n return [\n tfds.core.SplitGenerator(\n name=tfds.Split.TRAIN,\n gen_kwargs={\"subsets\": subsets}\n )\n ]\n\n def _generate_examples(self, subsets):\n source, target = self.builder_config.language_pair\n\n for item in subsets:\n logging.info(\"Generating examples from: %s\", item[\"name\"])\n source_file = item[\"source_file\"]\n target_file = item[\"target_file\"]\n\n gens = [_gen_line(source_file), _gen_line(target_file)]\n for idx, (source_sent, target_sent) in enumerate(zip(*gens)):\n result = {source: source_sent, target: target_sent}\n if all(result.values()):\n key = \"%s/%d\"%(item[\"name\"], idx)\n yield key, result\n\n\ndef _gen_line(filename):\n \"\"\"Returns sentences from an OPUS data file.\"\"\"\n with tf.io.gfile.GFile(filename) as f:\n for line in f:\n yield line\n", "# coding=utf-8\n# Copyright 2020 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# coding=utf-8\n\"\"\"Tests for tensorflow_datasets.core.features.text_feature.\"\"\"\n\nimport tensorflow.compat.v2 as tf\nfrom tensorflow_datasets import testing\nfrom tensorflow_datasets.core import features\nfrom tensorflow_datasets.core.features.text import text_encoder\n\ntf.enable_v2_behavior()\n\n\nclass TextFeatureTest(testing.FeatureExpectationsTestCase):\n\n def test_text(self):\n nonunicode_text = 'hello world'\n unicode_text = u'你好'\n\n self.assertFeature(\n feature=features.Text(),\n shape=(),\n dtype=tf.string,\n tests=[\n # Non-unicode\n testing.FeatureExpectationItem(\n value=nonunicode_text,\n expected=tf.compat.as_bytes(nonunicode_text),\n ),\n # Unicode\n testing.FeatureExpectationItem(\n value=unicode_text,\n expected=tf.compat.as_bytes(unicode_text),\n ),\n # Empty string\n testing.FeatureExpectationItem(\n value='',\n expected=tf.compat.as_bytes(''),\n ),\n ],\n )\n\n def test_text_encoded(self):\n unicode_text = u'你好'\n\n # Unicode integer-encoded by byte\n self.assertFeature(\n feature=features.Text(encoder=text_encoder.ByteTextEncoder()),\n shape=(None,),\n dtype=tf.int64,\n tests=[\n testing.FeatureExpectationItem(\n value=unicode_text,\n expected=[i + 1 for i in [228, 189, 160, 229, 165, 189]],\n ),\n # Empty string\n testing.FeatureExpectationItem(\n value='',\n expected=[],\n ),\n ],\n )\n\n def test_text_conversion(self):\n text_f = features.Text(encoder=text_encoder.ByteTextEncoder())\n text = u'你好'\n self.assertEqual(text, text_f.ints2str(text_f.str2ints(text)))\n\n def test_save_load_metadata(self):\n text_f = features.Text(\n encoder=text_encoder.ByteTextEncoder(additional_tokens=['HI']))\n text = u'HI 你好'\n ids = text_f.str2ints(text)\n self.assertEqual(1, ids[0])\n\n with testing.tmp_dir(self.get_temp_dir()) as data_dir:\n feature_name = 'dummy'\n text_f.save_metadata(data_dir, feature_name)\n\n new_f = features.Text()\n new_f.load_metadata(data_dir, feature_name)\n self.assertEqual(ids, text_f.str2ints(text))\n\n\nif __name__ == '__main__':\n testing.test_main()\n" ]
[ [ "tensorflow.compat.v2.io.gfile.GFile" ], [ "tensorflow.compat.v2.io.gfile.GFile" ], [ "tensorflow.compat.v2.io.gfile.GFile" ], [ "tensorflow.compat.v2.io.gfile.GFile" ], [ "tensorflow.compat.v2.io.gfile.GFile", "numpy.load" ], [ "numpy.sqrt", "tensorflow.compat.v2.io.gfile.GFile", "tensorflow.compat.v2.io.gfile.isdir", "tensorflow.compat.v2.io.gfile.listdir", "numpy.zeros" ], [ "numpy.absolute", "numpy.random.seed", "numpy.random.choice", "tensorflow.compat.v2.io.gfile.GFile", "tensorflow.compat.v2.io.gfile.exists", "tensorflow.compat.v2.io.gfile.makedirs", "numpy.ones", "numpy.zeros_like", "numpy.zeros", "numpy.random.randint" ], [ "tensorflow.compat.v2.io.gfile.GFile", "numpy.fromstring", "numpy.sqrt" ], [ "tensorflow.compat.v2.io.gfile.GFile", "tensorflow.compat.v2.compat.as_text" ], [ "tensorflow.compat.v2.io.gfile.GFile" ], [ "tensorflow.compat.v2.enable_v2_behavior", "tensorflow.compat.v2.compat.as_bytes" ] ]
[ { "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": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
codeproject/DeepStack
[ "d96368a3db1bc0266cb500ba3701d130834da0e6", "d96368a3db1bc0266cb500ba3701d130834da0e6", "d96368a3db1bc0266cb500ba3701d130834da0e6", "d96368a3db1bc0266cb500ba3701d130834da0e6", "d96368a3db1bc0266cb500ba3701d130834da0e6", "d96368a3db1bc0266cb500ba3701d130834da0e6", "d96368a3db1bc0266cb500ba3701d130834da0e6", "d96368a3db1bc0266cb500ba3701d130834da0e6" ]
[ "windows_packages_gpu/torch/nn/grad.py", "windows_packages_gpu/torch/testing/_internal/jit_metaprogramming_utils.py", "windows_packages_gpu/matplotlib/tests/test_mathtext.py", "windows_packages_gpu/torch/testing/_internal/distributed/ddp_under_dist_autograd_test.py", "windows_packages_gpu/torch/distributions/cauchy.py", "windows_packages_gpu/torch/random.py", "windows_packages_gpu/torch/nn/utils/weight_norm.py", "windows_packages_gpu/matplotlib/axes/_axes.py" ]
[ "\"\"\"Gradient interface\"\"\"\r\n\r\nimport torch\r\nfrom .modules.utils import _single, _pair, _triple\r\nimport warnings\r\n\r\n\r\ndef _grad_input_padding(grad_output, input_size, stride, padding, kernel_size, dilation=None):\r\n if dilation is None:\r\n # For backward compatibility\r\n warnings.warn(\"_grad_input_padding 'dilation' argument not provided. Default of 1 is used.\")\r\n dilation = [1] * len(stride)\r\n\r\n input_size = list(input_size)\r\n k = grad_output.dim() - 2\r\n\r\n if len(input_size) == k + 2:\r\n input_size = input_size[-k:]\r\n if len(input_size) != k:\r\n raise ValueError(\"input_size must have {} elements (got {})\"\r\n .format(k + 2, len(input_size)))\r\n\r\n def dim_size(d):\r\n return ((grad_output.size(d + 2) - 1) * stride[d] - 2 * padding[d] + 1\r\n + dilation[d] * (kernel_size[d] - 1))\r\n\r\n min_sizes = [dim_size(d) for d in range(k)]\r\n max_sizes = [min_sizes[d] + stride[d] - 1 for d in range(k)]\r\n for size, min_size, max_size in zip(input_size, min_sizes, max_sizes):\r\n if size < min_size or size > max_size:\r\n raise ValueError(\r\n (\"requested an input grad size of {}, but valid sizes range \"\r\n \"from {} to {} (for a grad_output of {})\").format(\r\n input_size, min_sizes, max_sizes,\r\n grad_output.size()[2:]))\r\n\r\n return tuple(input_size[d] - min_sizes[d] for d in range(k))\r\n\r\n\r\ndef conv1d_input(input_size, weight, grad_output, stride=1, padding=0, dilation=1, groups=1):\r\n r\"\"\"\r\n Computes the gradient of conv1d with respect to the input of the convolution.\r\n This is same as the 1D transposed convolution operator under the hood but requires\r\n the shape of the gradient w.r.t. input to be specified explicitly.\r\n\r\n Args:\r\n input_size : Shape of the input gradient tensor\r\n weight: weight tensor (out_channels x in_channels/groups x kW)\r\n grad_output : output gradient tensor (minibatch x out_channels x oW)\r\n stride (int or tuple, optional): Stride of the convolution. Default: 1\r\n padding (int or tuple, optional): Zero-padding added to both sides of the input. Default: 0\r\n dilation (int or tuple, optional): Spacing between kernel elements. Default: 1\r\n groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1\r\n\r\n Examples::\r\n\r\n >>> input = torch.randn(1,1,3, requires_grad=True)\r\n >>> weight = torch.randn(1,1,1, requires_grad=True)\r\n >>> output = F.conv1d(input, weight)\r\n >>> grad_output = torch.randn(output.shape)\r\n >>> grad_input = torch.autograd.grad(output, input, grad_output)\r\n >>> F.grad.conv1d_input(input.shape, weight, grad_output)\r\n\r\n \"\"\"\r\n stride = _single(stride)\r\n padding = _single(padding)\r\n dilation = _single(dilation)\r\n kernel_size = [weight.shape[2]]\r\n\r\n if input_size is None:\r\n raise ValueError(\"grad.conv1d_input requires specifying an input_size\")\r\n\r\n grad_input_padding = _grad_input_padding(grad_output, input_size, stride,\r\n padding, kernel_size, dilation)\r\n\r\n return torch.conv_transpose1d(\r\n grad_output, weight, None, stride, padding, grad_input_padding, groups,\r\n dilation)\r\n\r\n\r\ndef conv1d_weight(input, weight_size, grad_output, stride=1, padding=0, dilation=1, groups=1):\r\n r\"\"\"\r\n Computes the gradient of conv1d with respect to the weight of the convolution.\r\n\r\n Args:\r\n input: input tensor of shape (minibatch x in_channels x iW)\r\n weight_size : Shape of the weight gradient tensor\r\n grad_output : output gradient tensor (minibatch x out_channels x oW)\r\n stride (int or tuple, optional): Stride of the convolution. Default: 1\r\n padding (int or tuple, optional): Zero-padding added to both sides of the input. Default: 0\r\n dilation (int or tuple, optional): Spacing between kernel elements. Default: 1\r\n groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1\r\n\r\n Examples::\r\n\r\n >>> input = torch.randn(1,1,3, requires_grad=True)\r\n >>> weight = torch.randn(1,1,1, requires_grad=True)\r\n >>> output = F.conv1d(input, weight)\r\n >>> grad_output = torch.randn(output.shape)\r\n >>> grad_weight = torch.autograd.grad(output, filter, grad_output)\r\n >>> F.grad.conv1d_weight(input, weight.shape, grad_output)\r\n\r\n \"\"\"\r\n stride = _single(stride)\r\n padding = _single(padding)\r\n dilation = _single(dilation)\r\n in_channels = input.shape[1]\r\n out_channels = grad_output.shape[1]\r\n min_batch = input.shape[0]\r\n\r\n grad_output = grad_output.contiguous().repeat(1, in_channels // groups, 1)\r\n grad_output = grad_output.contiguous().view(\r\n grad_output.shape[0] * grad_output.shape[1], 1, grad_output.shape[2])\r\n\r\n input = input.contiguous().view(1, input.shape[0] * input.shape[1],\r\n input.shape[2])\r\n\r\n grad_weight = torch.conv1d(input, grad_output, None, dilation, padding,\r\n stride, in_channels * min_batch)\r\n\r\n grad_weight = grad_weight.contiguous().view(\r\n min_batch, grad_weight.shape[1] // min_batch, grad_weight.shape[2])\r\n\r\n return grad_weight.sum(dim=0).view(\r\n in_channels // groups, out_channels, grad_weight.shape[2]).transpose(\r\n 0, 1).narrow(2, 0, weight_size[2])\r\n\r\n\r\ndef conv2d_input(input_size, weight, grad_output, stride=1, padding=0, dilation=1, groups=1):\r\n r\"\"\"\r\n Computes the gradient of conv2d with respect to the input of the convolution.\r\n This is same as the 2D transposed convolution operator under the hood but requires\r\n the shape of the gradient w.r.t. input to be specified explicitly.\r\n\r\n Args:\r\n input_size : Shape of the input gradient tensor\r\n weight: weight tensor (out_channels x in_channels/groups x kH x kW)\r\n grad_output : output gradient tensor (minibatch x out_channels x oH x oW)\r\n stride (int or tuple, optional): Stride of the convolution. Default: 1\r\n padding (int or tuple, optional): Zero-padding added to both sides of the input. Default: 0\r\n dilation (int or tuple, optional): Spacing between kernel elements. Default: 1\r\n groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1\r\n\r\n Examples::\r\n\r\n >>> input = torch.randn(1,1,3,3, requires_grad=True)\r\n >>> weight = torch.randn(1,1,1,2, requires_grad=True)\r\n >>> output = F.conv2d(input, weight)\r\n >>> grad_output = torch.randn(output.shape)\r\n >>> grad_input = torch.autograd.grad(output, input, grad_output)\r\n >>> F.grad.conv2d_input(input.shape, weight, grad_output)\r\n\r\n \"\"\"\r\n stride = _pair(stride)\r\n padding = _pair(padding)\r\n dilation = _pair(dilation)\r\n kernel_size = (weight.shape[2], weight.shape[3])\r\n\r\n if input_size is None:\r\n raise ValueError(\"grad.conv2d_input requires specifying an input_size\")\r\n\r\n grad_input_padding = _grad_input_padding(grad_output, input_size, stride,\r\n padding, kernel_size, dilation)\r\n\r\n return torch.conv_transpose2d(\r\n grad_output, weight, None, stride, padding, grad_input_padding, groups,\r\n dilation)\r\n\r\n\r\ndef conv2d_weight(input, weight_size, grad_output, stride=1, padding=0, dilation=1, groups=1):\r\n r\"\"\"\r\n Computes the gradient of conv2d with respect to the weight of the convolution.\r\n\r\n Args:\r\n input: input tensor of shape (minibatch x in_channels x iH x iW)\r\n weight_size : Shape of the weight gradient tensor\r\n grad_output : output gradient tensor (minibatch x out_channels x oH x oW)\r\n stride (int or tuple, optional): Stride of the convolution. Default: 1\r\n padding (int or tuple, optional): Zero-padding added to both sides of the input. Default: 0\r\n dilation (int or tuple, optional): Spacing between kernel elements. Default: 1\r\n groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1\r\n\r\n Examples::\r\n\r\n >>> input = torch.randn(1,1,3,3, requires_grad=True)\r\n >>> weight = torch.randn(1,1,1,2, requires_grad=True)\r\n >>> output = F.conv2d(input, weight)\r\n >>> grad_output = torch.randn(output.shape)\r\n >>> grad_weight = torch.autograd.grad(output, filter, grad_output)\r\n >>> F.grad.conv2d_weight(input, weight.shape, grad_output)\r\n\r\n \"\"\"\r\n stride = _pair(stride)\r\n padding = _pair(padding)\r\n dilation = _pair(dilation)\r\n in_channels = input.shape[1]\r\n out_channels = grad_output.shape[1]\r\n min_batch = input.shape[0]\r\n\r\n grad_output = grad_output.contiguous().repeat(1, in_channels // groups, 1,\r\n 1)\r\n grad_output = grad_output.contiguous().view(\r\n grad_output.shape[0] * grad_output.shape[1], 1, grad_output.shape[2],\r\n grad_output.shape[3])\r\n\r\n input = input.contiguous().view(1, input.shape[0] * input.shape[1],\r\n input.shape[2], input.shape[3])\r\n\r\n grad_weight = torch.conv2d(input, grad_output, None, dilation, padding,\r\n stride, in_channels * min_batch)\r\n\r\n grad_weight = grad_weight.contiguous().view(\r\n min_batch, grad_weight.shape[1] // min_batch, grad_weight.shape[2],\r\n grad_weight.shape[3])\r\n\r\n return grad_weight.sum(dim=0).view(\r\n in_channels // groups, out_channels,\r\n grad_weight.shape[2], grad_weight.shape[3]).transpose(0, 1).narrow(\r\n 2, 0, weight_size[2]).narrow(3, 0, weight_size[3])\r\n\r\n\r\ndef conv3d_input(input_size, weight, grad_output, stride=1, padding=0, dilation=1, groups=1):\r\n r\"\"\"\r\n Computes the gradient of conv3d with respect to the input of the convolution.\r\n This is same as the 3D transposed convolution operator under the hood but requires\r\n the shape of the gradient w.r.t. input to be specified explicitly.\r\n\r\n Args:\r\n input_size : Shape of the input gradient tensor\r\n weight: weights tensor (out_channels x in_channels/groups x kT x kH x kW)\r\n grad_output : output gradient tensor (minibatch x out_channels x oT x oH x oW)\r\n stride (int or tuple, optional): Stride of the convolution. Default: 1\r\n padding (int or tuple, optional): Zero-padding added to both sides of the input. Default: 0\r\n dilation (int or tuple, optional): Spacing between kernel elements. Default: 1\r\n groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1\r\n\r\n Examples::\r\n\r\n >>> input = torch.randn(2, 8, 10, 10, 20, requires_grad=True)\r\n >>> weight = torch.randn(4, 8, 2, 3, 3, requires_grad=True)\r\n >>> output = F.conv3d(input, weight)\r\n >>> grad_output = torch.randn(output.shape)\r\n >>> grad_input = torch.autograd.grad(output, input, grad_output)\r\n >>> F.grad.conv3d_input(input.shape, weight, grad_output)\r\n\r\n \"\"\"\r\n stride = _triple(stride)\r\n padding = _triple(padding)\r\n dilation = _triple(dilation)\r\n kernel_size = (weight.shape[2], weight.shape[3], weight.shape[4])\r\n\r\n if input_size is None:\r\n raise ValueError(\"grad.conv3d_input requires specifying an input_size\")\r\n\r\n grad_input_padding = _grad_input_padding(grad_output, input_size, stride,\r\n padding, kernel_size, dilation)\r\n\r\n return torch.conv_transpose3d(\r\n grad_output, weight, None, stride, padding, grad_input_padding, groups,\r\n dilation)\r\n\r\n\r\ndef conv3d_weight(input, weight_size, grad_output, stride=1, padding=0, dilation=1, groups=1):\r\n r\"\"\"\r\n Computes the gradient of conv3d with respect to the weight of the convolution.\r\n\r\n Args:\r\n input: input tensor of shape (minibatch x in_channels x iT x iH x iW)\r\n weight_size : Shape of the weight gradient tensor\r\n grad_output : output gradient tensor (minibatch x out_channels x oT x oH x oW)\r\n stride (int or tuple, optional): Stride of the convolution. Default: 1\r\n padding (int or tuple, optional): Zero-padding added to both sides of the input. Default: 0\r\n dilation (int or tuple, optional): Spacing between kernel elements. Default: 1\r\n groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1\r\n\r\n Examples::\r\n\r\n >>> input = torch.randn(2, 8, 10, 10, 20, requires_grad=True)\r\n >>> weight = torch.randn(4, 8, 2, 3, 3, requires_grad=True)\r\n >>> output = F.conv3d(input, weight)\r\n >>> grad_output = torch.randn(output.shape)\r\n >>> grad_weight = torch.autograd.grad(output, weight, grad_output)\r\n >>> F.grad.conv3d_weight(input, weight.shape, grad_output)\r\n\r\n \"\"\"\r\n stride = _triple(stride)\r\n padding = _triple(padding)\r\n dilation = _triple(dilation)\r\n in_channels = input.shape[1]\r\n out_channels = grad_output.shape[1]\r\n min_batch = input.shape[0]\r\n\r\n grad_output = grad_output.repeat(1, in_channels // groups, 1, 1, 1)\r\n grad_output = grad_output.contiguous().view(\r\n grad_output.shape[0] * grad_output.shape[1], 1, grad_output.shape[2],\r\n grad_output.shape[3], grad_output.shape[4])\r\n\r\n input = input.contiguous().view(1, input.shape[0] * input.shape[1],\r\n input.shape[2], input.shape[3],\r\n input.shape[4])\r\n\r\n grad_weight = torch.conv3d(input, grad_output, None, dilation, padding,\r\n stride, in_channels * min_batch)\r\n\r\n grad_weight = grad_weight.contiguous().view(\r\n min_batch, grad_weight.shape[1] // min_batch, grad_weight.shape[2],\r\n grad_weight.shape[3], grad_weight.shape[4])\r\n\r\n return grad_weight.sum(dim=0).view(\r\n in_channels // groups, out_channels, grad_weight.shape[2],\r\n grad_weight.shape[3], grad_weight.shape[4]).transpose(0, 1).narrow(\r\n 2, 0, weight_size[2]).narrow(3, 0, weight_size[3]).narrow(\r\n 4, 0, weight_size[4])\r\n", "# Torch\r\nfrom torch.jit.annotations import BroadcastingList2, BroadcastingList3 # noqa: F401\r\nfrom torch.testing._internal.common_methods_invocations import non_differentiable, create_input, \\\r\n unpack_variables\r\nimport torch.nn.functional as F\r\nimport torch\r\nimport torch.cuda\r\nimport torch.jit\r\nimport torch.jit._logging\r\nimport torch.jit.frontend\r\nfrom torch.testing._internal.common_nn import module_tests, new_module_tests\r\nfrom copy import deepcopy\r\nimport math # noqa: F401\r\n\r\n# Testing utils\r\nfrom torch._six import inf\r\ntorch.set_default_dtype(torch.double)\r\n\r\nL = 20\r\nM = 10\r\nS = 5\r\n\r\n# NB: JIT script tests for all nn functional interfaces, script mode does\r\n# not support in_place operations yet, so no inplace operation tests added.\r\n# removed all the deprecated functions\r\n#\r\n# (\r\n# method name,\r\n# input size/constructing fn,\r\n# args (tuple represents shape of a tensor arg),\r\n# test variant name(will be used at test name suffix,\r\n# 'inplace' skips grad tests), // optional\r\n# (True, nonfusible_nodes, fusible_nodes) for autodiff // optional\r\n# fn to determine if test should be skipped, // optional\r\n# fn mapping output to part that should be gradcheck'ed, // optional\r\n# kwargs for function, // optional\r\n# )\r\nnn_functional_tests = [\r\n ('conv1d', (S, S, S), ((S, S, S),)),\r\n ('conv2d', (S, S, S, S), ((S, S, S, S),)),\r\n ('conv3d', (S, S, S, S, S), ((S, S, S, S, S),)),\r\n ('conv_transpose1d', (S, S, S), ((S, S, S),)),\r\n ('conv_transpose2d', (S, S, S, S), ((S, S, S, S),)),\r\n ('conv_transpose3d', (S, S, S, S, S), ((S, S, S, S, S),)),\r\n ('conv_tbc', (S, S, S), ((S, S, S), (S,), 2)),\r\n ('avg_pool1d', (S, S, S), (3,)),\r\n ('avg_pool2d', (S, S, S, S), (3,), '', (True,)),\r\n ('avg_pool3d', (S, S, S, S, S), (3,)),\r\n ('fractional_max_pool2d', (S, S, S, S), (3, [2, 3],)),\r\n ('max_pool1d', (S, S, S), (2, 1)),\r\n ('max_pool1d', (S, S, S), (2, 1, 1, 1, False, True), 'with_indices'),\r\n ('max_pool2d', (S, S, S, S), (2, 1), '', (True, 'aten::max_pool2d_with_indices')),\r\n ('max_pool2d', (S, S, S, S), (2, 1, 1, 1, False, True), 'with_indices', (True, 'aten::max_pool2d_with_indices')),\r\n ('max_pool3d', (S, S, S, S, S), (2, 1)),\r\n ('max_unpool1d', torch.tensor([[[2., 4]]]), (torch.tensor([[[1, 3]]]), 2, 2, 0)),\r\n ('max_unpool2d', torch.tensor([[[[2., 4]]]]), (torch.tensor([[[[1, 3]]]]), 2, 2, 0)),\r\n ('max_unpool3d', torch.tensor([[[[[2., 4]]]]]), (torch.tensor([[[[[1, 3]]]]]), 2, 2, 0)),\r\n ('lp_pool1d', (S, S, S), (2., 3, 2,)),\r\n ('lp_pool2d', (S, S, S, S), (2., 3, 2,)),\r\n ('adaptive_max_pool1d', (S, S, S), (5,)),\r\n ('adaptive_max_pool2d', (S, S, S, S), ([5, 7],)),\r\n ('adaptive_max_pool3d', (S, S, S, S, S), ([3, 2, 2],)),\r\n ('adaptive_avg_pool1d', (S, S, S), (5,), '', (True,)),\r\n ('adaptive_avg_pool2d', (S, S, S, S), ([5, 7],), '', (True,)),\r\n ('adaptive_avg_pool3d', (S, S, S, S, S), ([3, 2, 2],), '', (True,)),\r\n ('dropout', (S, S, S), (0.5,), '', (True,\r\n ['aten::bernoulli_',\r\n 'aten::empty_like', 'aten::mul', 'aten::div'])),\r\n ('alpha_dropout', (S, S, S), (0.5,)),\r\n ('dropout2d', (S, S, S), (0.5,)),\r\n ('dropout3d', (S, S, S), (0.5,)),\r\n ('feature_alpha_dropout', (S, S, S), (0.5,)),\r\n ('threshold', (S, S, S), (0.1, 2.), '', (True,)),\r\n ('threshold', (S, S, S), (0.1, 2., True), 'inplace'),\r\n ('relu', (S, S, S), (), '', (True,)),\r\n ('relu', (S, S, S), (), 'inplace'),\r\n ('glu', (S - 1, S - 1, S - 1), (),),\r\n ('hardtanh', (S, S, S), (-0.5, 0.5),),\r\n ('hardtanh', (S, S, S), (-0.5, 0.5, True), 'inplace'),\r\n ('relu6', (S, S, S), (),),\r\n ('relu6', (S, S, S), (True), 'inplace'),\r\n ('elu', (S, S, S), (0.9,),),\r\n ('elu', (S, S, S), (0.9, True), 'inplace'),\r\n ('selu', (S, S, S), (),),\r\n ('selu', (S, S, S), (True), 'inplace'),\r\n ('celu', (S, S, S), (0.9,),),\r\n ('celu', (S, S, S), (0.9, True), 'inplace'),\r\n ('leaky_relu', (S, S, S), (0.02,),),\r\n ('leaky_relu', (S, S, S), (0.02,), 'inplace'),\r\n ('rrelu', (S, S), (0.1, 0.3, False),),\r\n ('rrelu', (S, S), (0.1, 0.3, False, True), 'inplace'),\r\n ('hardshrink', (S, S, S), (0.4,),),\r\n ('tanhshrink', (S, S, S), (),),\r\n ('softsign', (S, S, S), (),),\r\n ('softplus', (S, S, S), (),),\r\n ('softmin', (S, S, S), (0,),),\r\n ('softmax', (S, S, S), (0,), '', (True,)),\r\n ('softmax', (S, S, S), (0, 3, torch.double), 'with_all_args', (True,)),\r\n ('tanh', (S, S, S), (), '', (True,)),\r\n ('sigmoid', (S, S, S), (), '', (True,)),\r\n ('log_softmax', (S, S, S), (0,), '', (True,)),\r\n ('linear', (S, S), ((M, S),), '', (True, ['aten::t', 'aten::matmul'])),\r\n ('linear', (S, S), ((M, S), (M,)), 'addmm', (True, ['aten::add', 'aten::mm'])),\r\n ('bilinear', (S, S, S), ((S, S, M), torch.zeros(M, S, M),),),\r\n ('embedding', torch.tensor([[1, 2, 4, 5], [4, 3, 2, 5]]), (torch.rand(6, 3), ), '', (True,)),\r\n ('embedding_bag', torch.tensor([1, 2, 4, 2]), (torch.rand(5, 3), torch.tensor([0, 4]),),),\r\n ('batch_norm', (S, S), (non_differentiable(torch.randn(S)), non_differentiable(torch.ones(S)), ),\r\n '', (False, 'aten::_batch_norm_impl_index')),\r\n ('instance_norm', (S, S, S), (non_differentiable(torch.zeros(S)), non_differentiable(torch.ones(S))),),\r\n ('layer_norm', (S, S, S, S), ([5],), '',\r\n (False, ['aten::contiguous', 'aten::_batch_norm_impl_index'])),\r\n ('layer_norm', (S, S, S, S), ([5], non_differentiable(torch.rand(S)),), 'with_only_weight',\r\n (False, ['aten::contiguous', 'aten::_batch_norm_impl_index'])),\r\n ('layer_norm', (S, S, S, S), ([5], None, non_differentiable(torch.rand(S)),), 'with_only_bias',\r\n (False, ['aten::contiguous', 'aten::_batch_norm_impl_index'])),\r\n ('layer_norm', (S, S, S, S), ([5], non_differentiable(torch.rand(S)),\r\n non_differentiable(torch.rand(S))), 'with_weight_and_bias',\r\n (False, ['aten::contiguous', 'aten::_batch_norm_impl_index', 'aten::addcmul'])),\r\n ('group_norm', (S, S, S), (1, torch.rand(5),),),\r\n ('local_response_norm', (S, S, S), (2, ),),\r\n ('nll_loss', F.log_softmax(torch.randn(3, 5), dim=0), (torch.tensor([1, 0, 4]),), '', (True, 'aten::nll_loss_forward')),\r\n ('poisson_nll_loss', torch.rand(S, 2), (torch.rand(S, 2),),),\r\n ('poisson_nll_loss', torch.rand(S, 2), (torch.rand(S, 2), True, True), 'full'),\r\n ('kl_div', F.log_softmax(torch.randn(S, 10), 1), (F.softmax(torch.randn(S, 10), 1),),),\r\n ('cross_entropy', (3, S), (torch.randint(S, (3,), dtype=torch.int64),),),\r\n ('binary_cross_entropy_with_logits', (3,), (torch.empty(3).random_(2), ),),\r\n ('smooth_l1_loss', (3, S), (non_differentiable(torch.rand(3, S)),),),\r\n ('l1_loss', (3, S), (non_differentiable(torch.rand(3, S)),),),\r\n ('mse_loss', (3, S), (non_differentiable(torch.rand(3, S)),),),\r\n ('smooth_l1_loss', (3, S), ((torch.rand(3, S)),), 'with_grad'),\r\n ('l1_loss', (3, S), ((torch.rand(3, S)),), 'with_grad'),\r\n ('mse_loss', (3, S), ((torch.rand(3, S)),), 'with_grad'),\r\n ('margin_ranking_loss', (3, S), ((3, S), (S,)),),\r\n ('hinge_embedding_loss', (3, S), (non_differentiable(torch.rand(3, S)),),),\r\n ('soft_margin_loss', (3, S), (non_differentiable(torch.rand(3, S)),),),\r\n ('multilabel_soft_margin_loss', (3, S), (non_differentiable(torch.rand(3, S)),),),\r\n ('cosine_embedding_loss', (S, S), ((S, S), non_differentiable(torch.rand(S,))),),\r\n ('pixel_shuffle', (1, 9, 4, 4), (3,),),\r\n ('affine_grid', (S, 2, 3), (torch.Size([S, 1, 7, 7]),),),\r\n ('pad', (3, 3, 4, 2), ([1, 1],),),\r\n ('pairwise_distance', (S, S), ((S, S),),),\r\n ('pdist', (S, S), (),),\r\n ('cosine_similarity', (S, S), ((S, S),),),\r\n ('triplet_margin_loss', (S, S), ((S, S), (S, S)),),\r\n ('normalize', (S, S, S), (),),\r\n ('unfold', (S, S, S, S), ([2, 3]),),\r\n ('fold', (1, 3 * 2 * 2, 12), ([4, 5], [2, 2]),),\r\n ('grid_sample', (S, S, S, S), (non_differentiable(torch.rand(S, S, S, 2)),),),\r\n ('gumbel_softmax', (S, S), (2.,), '', (True, ['aten::softmax', 'aten::add', 'aten::div'], ['aten::neg'])),\r\n ('gumbel_softmax', (S, S), (2., True,), 'hard', (True, ['aten::softmax', 'aten::add', 'aten::div'], ['aten::neg'])),\r\n ('multilabel_margin_loss', torch.tensor([[0.2, -0.2, 0.07]]), (torch.tensor([[0, 0, 1]]),),),\r\n ('multi_margin_loss', (S, S), (non_differentiable(torch.randint(S, (S, ), dtype=torch.int64)),\r\n 1, 1., non_differentiable(torch.randn(S))),),\r\n ('binary_cross_entropy', torch.randn(3, 2).sigmoid(), (non_differentiable(torch.rand(3, 2)),\r\n non_differentiable(torch.randn(3, 2))),),\r\n ('binary_cross_entropy', torch.randn(3, 2).sigmoid(),\r\n (non_differentiable(torch.rand(3, 2)),\r\n non_differentiable(torch.randn(3, 2)), None, None, 'mean'), 'size_average'),\r\n ('ctc_loss', torch.rand(S, S, S).log_softmax(2).detach().requires_grad_(),\r\n (torch.randint(1, S, (S, S), dtype=torch.long), torch.full((S,), S, dtype=torch.long),\r\n torch.randint(1, S, (S,), dtype=torch.long))),\r\n ('upsample', torch.randn(S, S, M, M), (None, 2.), 'with_scale'),\r\n ('upsample', torch.randn(S, S, M, M), (4,), 'with_size'),\r\n ('interpolate', torch.zeros(3, 3).view(1, 1, 3, 3), (2,), 'nearest_4d'),\r\n ('interpolate', torch.randn(S, S, M, M), (None, 2.), 'nearest_4d_with_scale'),\r\n ('interpolate', torch.randn(S, S, M, M), (4,), 'nearest_4d_with_size'),\r\n ('interpolate', torch.zeros(3, 3).view(1, 1, 3, 3), (2,), 'area_4d'),\r\n ('interpolate', torch.randn(S, S, M, M), (None, 2.), 'area_4d_with_scale'),\r\n ('interpolate', torch.randn(S, S, M, M), (4,), 'area_4d_with_size'),\r\n ('interpolate', torch.zeros(3, 3).view(1, 1, 3, 3), (2,), 'bilinear_4d'),\r\n ('interpolate', torch.randn(S, S, M, M), (None, 2.), 'bilinear_4d_with_scale'),\r\n ('interpolate', torch.randn(S, S, M, M), (4,), 'bilinear_4d_with_size'),\r\n ('interpolate', torch.zeros(3, 3).view(1, 1, 3, 3), (2,), 'bicubic_4d'),\r\n ('interpolate', torch.randn(S, S, M, M), (None, 2.), 'bicubic_4d_with_scale'),\r\n ('interpolate', torch.randn(S, S, M, M), (4,), 'bicubic_4d_with_size'),\r\n ('interpolate', torch.zeros(3, 3).view(1, 3, 3), (2,), 'nearest_3d'),\r\n ('interpolate', torch.randn(S, M, M), (None, 2.), 'nearest_3d_with_scale'),\r\n ('interpolate', torch.randn(S, M, M), (4,), 'nearest_3d_with_size'),\r\n ('interpolate', torch.zeros(3, 3).view(1, 3, 3), (2,), 'area_3d'),\r\n ('interpolate', torch.randn(S, M, M), (None, 2.), 'area_3d_with_scale'),\r\n ('interpolate', torch.randn(S, M, M), (4,), 'area_3d_with_size'),\r\n ('interpolate', torch.zeros(3, 3).view(1, 3, 3), (2,), 'linear_3d'),\r\n ('interpolate', torch.randn(S, M, M), (None, 2.), 'linear_3d_with_scale'),\r\n ('interpolate', torch.randn(S, M, M), (4,), 'linear_3d_with_size'),\r\n ('interpolate', torch.randn(S, M, M, M, M), (None, 2.), 'nearest_5d_with_scale'),\r\n ('interpolate', torch.randn(S, M, M, M, M), (4,), 'nearest_5d_with_size'),\r\n ('interpolate', torch.zeros(3, 3, 3).view(1, 1, 3, 3, 3), (2,), 'area_5d'),\r\n ('interpolate', torch.randn(S, M, M, M, M), (None, 2.), 'area_5d_with_scale'),\r\n ('interpolate', torch.randn(S, M, M, M, M), (4,), 'area_5d_with_size'),\r\n ('interpolate', torch.zeros(3, 3, 3).view(1, 1, 3, 3, 3), (2,), 'trilinear_5d'),\r\n ('interpolate', torch.randn(S, M, M, M, M), (None, 2.), 'trilinear_5d_with_scale'),\r\n ('interpolate', torch.randn(S, M, M, M, M), (4,), 'trilinear_5d_with_size'),\r\n ('interpolate', torch.zeros(3, 3).view(1, 1, 3, 3), (2, None, 'nearest', None, False),\r\n 'nearest_4d_not_recompute_scale_factor'),\r\n ('interpolate', torch.randn(S, S, M, M), (4, None, 'nearest', None, False),\r\n 'nearest_4d_with_size_not_recompute_scale_factor'),\r\n ('interpolate', torch.randn(S, S, M, M), (None, 2., 'bilinear', None, False),\r\n 'bilinear_4d_with_scale_not_recompute_scale_factor'),\r\n ('interpolate', torch.randn(S, S, M, M), (4, None, 'bilinear', None, False),\r\n 'bilinear_4d_with_size_not_recompute_scale_factor'),\r\n ('interpolate', torch.randn(S, S, M, M), (None, 2., 'bicubic', None, False),\r\n 'bicubic_4d_with_scale_not_recompute_scale_factor'),\r\n ('interpolate', torch.randn(S, S, M, M), (4, None, 'bicubic', None, False),\r\n 'bicubic_4d_with_size_not_recompute_scale_factor'),\r\n ('interpolate', torch.randn(S, M, M), (None, 2., 'nearest', None, False),\r\n 'nearest_3d_with_scale_not_recompute_scale_factor'),\r\n ('interpolate', torch.randn(S, M, M), (4, None, 'nearest', None, False),\r\n 'nearest_3d_with_size_not_recompute_scale_factor'),\r\n ('interpolate', torch.randn(S, M, M), (None, 2., 'linear', None, False),\r\n 'linear_3d_with_scale_not_recompute_scale_factor'),\r\n ('interpolate', torch.randn(S, M, M), (4, None, 'linear', None, False),\r\n 'linear_3d_with_size_not_recompute_scale_factor'),\r\n ('interpolate', torch.randn(S, M, M, M, M), (None, 2., 'nearest', None, False),\r\n 'nearest_5d_with_scale_not_recompute_scale_factor'),\r\n ('interpolate', torch.randn(S, M, M, M, M), (4, None, 'nearest', None, False),\r\n 'nearest_5d_with_size_not_recompute_scale_factor'),\r\n ('interpolate', torch.randn(S, M, M, M, M), (None, 2., 'trilinear', None, False),\r\n 'trilinear_5d_with_scale_not_recompute_scale_factor'),\r\n ('interpolate', torch.randn(S, M, M, M, M), (4, None, 'trilinear', None, False),\r\n 'trilinear_5d_with_size_not_recompute_scale_factor'),\r\n]\r\n\r\nscript_template = '''\r\ndef the_method({}):\r\n return {}\r\n'''\r\n\r\ndef get_call(method_name, func_type, args, kwargs):\r\n kwargs_str = ', '.join([k + '=' + str(v) for k, v in kwargs.items()])\r\n self_arg = args[0]\r\n if(func_type == 'method'):\r\n args = args[1:]\r\n\r\n argument_str = ', '.join(args)\r\n argument_str += ', ' if len(args) and len(kwargs) else ''\r\n argument_str += kwargs_str\r\n\r\n if func_type == 'functional':\r\n call = 'torch.{}({})'.format(method_name, argument_str)\r\n elif func_type == 'method':\r\n call = '{}.{}({})'.format(self_arg, method_name, argument_str)\r\n elif func_type == 'nn_functional':\r\n call = 'torch.nn.functional.{}({})'.format(method_name, argument_str)\r\n else:\r\n raise 'Unsupported function type'\r\n\r\n return call\r\n\r\ndef get_constant(x):\r\n if x == inf:\r\n return 'math.inf'\r\n if x == -inf:\r\n return '-math.inf'\r\n return x\r\n\r\ndef get_script_args(args):\r\n formals = []\r\n tensors = []\r\n actuals = []\r\n for arg in args:\r\n if isinstance(arg, torch.Tensor):\r\n name = 'i{}'.format(len(formals))\r\n formals.append(name)\r\n actuals.append(name)\r\n tensors.append(arg)\r\n elif isinstance(arg, str):\r\n actuals.append(\"'{}'\".format(arg))\r\n else:\r\n actuals.append(str(get_constant(arg)))\r\n return (formals, tensors, actuals)\r\n\r\n# create a script function from (name, func_type, output_process_fn),\r\n# and returns the compiled function and example inputs\r\ndef gen_script_fn_and_args(method_name, func_type, *args, **kwargs):\r\n formals, tensors, actuals = get_script_args(args)\r\n call = get_call(method_name, func_type, actuals, kwargs)\r\n script = script_template.format(', '.join(formals), call)\r\n CU = torch.jit.CompilationUnit(script)\r\n return CU.the_method, tensors\r\n\r\n# create a script function from (name, func_type, output_process_fn),\r\n# returns a function takes in (args, kwargs) and runs the compiled function and\r\n# then applies the post process fn to the outputs\r\ndef create_script_fn(self, method_name, func_type, output_process_fn):\r\n def script_fn(*args, **kwargs):\r\n fn, tensors = gen_script_fn_and_args(method_name, func_type, *args, **kwargs)\r\n self.assertExportImport(fn.graph, tensors)\r\n output = output_process_fn(fn(*tensors))\r\n script_fn.last_graph = fn.graph_for(*tensors)\r\n return output\r\n return script_fn\r\n\r\n# make a new function where all non-tensor arguments in 'args' have been partially\r\n# applied, and all tensor arguments remain.\r\n# used to trace functions when some arguments are not tensors\r\ndef partial_apply_nontensors(fn, args, **kwargs):\r\n source = ['t' if isinstance(arg, torch.Tensor) else 's' for arg in args]\r\n\r\n def new_fn(*tensors_):\r\n tensors = iter(tensors_)\r\n return fn(*(args[i] if s == 's' else next(tensors) for i, s in enumerate(source)), **kwargs)\r\n\r\n return new_fn, [arg for arg in args if isinstance(arg, torch.Tensor)]\r\n\r\n# create a trace function from input fn\r\ndef create_traced_fn(self, fn):\r\n def traced_fn(*inputs, **kwargs):\r\n fn_tensors, inputs_tensors = partial_apply_nontensors(fn, inputs, **kwargs)\r\n # `check_trace` is set to False because check_trace is run with @no_grad\r\n # Also, `check_against_reference` already does all the checks\r\n # against python function\r\n traced = torch.jit.trace(fn_tensors, inputs_tensors, check_trace=False)\r\n self.assertExportImport(traced.graph, inputs_tensors)\r\n output = traced(*inputs_tensors)\r\n traced_fn.last_graph = traced.graph_for(*inputs_tensors)\r\n return output\r\n return traced_fn\r\n\r\n# known to be failing in script\r\nEXCLUDE_SCRIPT = {\r\n 'test_norm_fro_default',\r\n 'test_norm_fro_cpu',\r\n 'test_norm_nuc',\r\n 'test_norm_fro',\r\n 'test_norm_nuc_batched',\r\n\r\n # aten op has additional cudnn argument\r\n 'test_nn_unfold',\r\n\r\n # flaky test - TODO fix\r\n 'test_nn_ctc_loss',\r\n\r\n # unknown builtin op\r\n 'test_nn_fold',\r\n\r\n # jit doesn't support sparse tensors.\r\n 'test_to_sparse'\r\n}\r\n\r\n# generates a script function and set of example inputs\r\n# from a specified test in the format of nn_functional_tests\r\ndef get_nn_functional_compiled_fn_and_inputs(name, self_size, args, variant_name='', *extra_args):\r\n test_name = 'test_nn_' + name\r\n\r\n if variant_name != '':\r\n test_name = test_name + '_' + variant_name\r\n\r\n no_grad = variant_name == 'inplace'\r\n\r\n self_variable = create_input((self_size,))[0][0]\r\n kwargs = None\r\n\r\n # need to record this because methods can change the size (e.g. unsqueeze)\r\n args_variable, kwargs_variable = create_input(args)\r\n\r\n self_tensor = deepcopy(self_variable.data)\r\n args_tensor = deepcopy(unpack_variables(args_variable))\r\n\r\n f_args_variable = (self_variable,) + args_variable\r\n f_args_tensor = (self_tensor,) + args_tensor\r\n with torch.jit._disable_emit_hooks():\r\n script_fn, inputs = gen_script_fn_and_args(name, \"nn_functional\", *f_args_variable)\r\n return script_fn, inputs\r\n\r\n\r\n# additional modules test\r\n# TODO: delete this list once we make all nn_tests work\r\nadditional_module_tests = [\r\n {\r\n 'module_name': 'Bilinear',\r\n 'constructor_args': (S, S, M),\r\n 'input_size': (S, S),\r\n 'extra_args': ((S, S),)\r\n },\r\n {\r\n 'module_name': 'RNNCell',\r\n 'constructor_args': (S, S),\r\n 'input_size': (S, S),\r\n },\r\n {\r\n 'module_name': 'LSTMCell',\r\n 'constructor_args': (S, S),\r\n 'input_size': (S, S),\r\n },\r\n {\r\n 'module_name': 'GRUCell',\r\n 'constructor_args': (S, S),\r\n 'input_size': (S, S),\r\n },\r\n {\r\n 'module_name': 'MultiheadAttention',\r\n 'constructor_args': (128, 8),\r\n 'input_size': (10, 8, 128),\r\n 'extra_args': (torch.randn(10, 8, 128), torch.randn(10, 8, 128)),\r\n 'slowTest': True\r\n },\r\n {\r\n 'module_name': 'Transformer',\r\n 'constructor_args': (1, 1, 1, 1, 2),\r\n 'input_size': (3, 1, 1),\r\n 'extra_args': (torch.randn(1, 1, 1),),\r\n 'slowTest': True\r\n }\r\n]\r\n\r\nEXCLUDE_SCRIPT_MODULES = {\r\n 'test_nn_AdaptiveAvgPool2d_tuple_none',\r\n 'test_nn_AdaptiveAvgPool3d_tuple_none',\r\n 'test_nn_AdaptiveMaxPool2d_tuple_none',\r\n 'test_nn_AdaptiveMaxPool3d_tuple_none',\r\n\r\n # Doesn't use future division, so this is not supported\r\n 'test_nn_CrossMapLRN2d',\r\n}\r\n\r\nscript_method_template = '''\r\ndef forward({}):\r\n return {}\r\n'''\r\n\r\ndef create_script_module(self, nn_module, constructor_args, *args, **kwargs):\r\n def script_module(*args, **kwargs):\r\n formals, tensors, actuals = get_script_args(args)\r\n\r\n method_args = ', '.join(['self'] + actuals)\r\n call_args_str = ', '.join(actuals)\r\n call = \"self.submodule({})\".format(call_args_str)\r\n script = script_method_template.format(method_args, call)\r\n\r\n submodule_constants = []\r\n if kwargs.get('is_constant'):\r\n submodule_constants = ['submodule']\r\n\r\n # Create module to use the script method\r\n class TheModule(torch.jit.ScriptModule):\r\n __constants__ = submodule_constants\r\n\r\n def __init__(self):\r\n super(TheModule, self).__init__()\r\n self.submodule = nn_module(*constructor_args)\r\n\r\n def make_module(script):\r\n module = TheModule()\r\n # check __repr__\r\n str(module)\r\n module.define(script)\r\n return module\r\n\r\n module = make_module(script)\r\n if self:\r\n self.assertExportImportModule(module, tensors)\r\n module(*args)\r\n create_script_module.last_graph = module.graph\r\n return module\r\n return script_module\r\n\r\ndef get_nn_module_name_from_kwargs(**kwargs):\r\n if 'module_name' in kwargs:\r\n return kwargs['module_name']\r\n elif 'fullname' in kwargs:\r\n return kwargs['fullname']\r\n elif 'constructor' in kwargs:\r\n return kwargs['constructor'].__name__\r\n\r\ndef get_nn_mod_test_name(**kwargs):\r\n name = get_nn_module_name_from_kwargs(**kwargs)\r\n test_name = name\r\n if 'desc' in kwargs:\r\n test_name = \"{}_{}\".format(test_name, kwargs['desc'])\r\n return 'test_nn_{}'.format(test_name)\r\n\r\ndef get_nn_module_class_from_kwargs(**kwargs):\r\n name = get_nn_module_name_from_kwargs(**kwargs)\r\n index = name.find(\"_\")\r\n if index == -1:\r\n return name\r\n else:\r\n return name[0:name.find(\"_\")]\r\n\r\ndef try_get_nn_module_compiled_mod_and_inputs(*args, **kwargs):\r\n name = get_nn_module_name_from_kwargs(**kwargs)\r\n\r\n if 'desc' in kwargs and 'eval' in kwargs['desc']:\r\n # eval() is not supported, so skip these tests\r\n return\r\n\r\n test_name = name\r\n if 'desc' in kwargs:\r\n test_name = \"{}_{}\".format(test_name, kwargs['desc'])\r\n test_name = get_nn_mod_test_name(**kwargs)\r\n\r\n if test_name in EXCLUDE_SCRIPT_MODULES:\r\n return\r\n if 'constructor' in kwargs:\r\n nn_module = kwargs['constructor']\r\n else:\r\n nn_module = getattr(torch.nn, name)\r\n\r\n if \"FunctionalModule\" in str(nn_module):\r\n return\r\n\r\n if 'constructor_args_fn' in kwargs:\r\n constructor_args = kwargs['constructor_args_fn']()\r\n else:\r\n constructor_args = kwargs.get('constructor_args', ())\r\n\r\n # Set up inputs from tuple of sizes or constructor fn\r\n if 'input_fn' in kwargs:\r\n input = kwargs['input_fn']()\r\n else:\r\n input = (kwargs['input_size'],)\r\n\r\n # Extra parameters to forward()\r\n if 'extra_args' in kwargs:\r\n input = input + kwargs['extra_args']\r\n\r\n if 'target_size' in kwargs:\r\n input = input + (kwargs['target_size'],)\r\n elif 'target_fn' in kwargs:\r\n if torch.is_tensor(input):\r\n input = (input,)\r\n input = input + (kwargs['target_fn'](),)\r\n\r\n args_variable, kwargs_variable = create_input(input)\r\n f_args_variable = deepcopy(unpack_variables(args_variable))\r\n out_var = deepcopy(f_args_variable)\r\n\r\n args, mod = f_args_variable, create_script_module(None, nn_module, constructor_args, *f_args_variable)(*f_args_variable)\r\n\r\n return mod, out_var\r\n\r\n\r\ndef get_all_nn_module_tests():\r\n return module_tests + new_module_tests + additional_module_tests\r\n", "import io\r\nimport os\r\nimport re\r\n\r\nimport numpy as np\r\nimport pytest\r\n\r\nimport matplotlib as mpl\r\nfrom matplotlib.testing.decorators import check_figures_equal, image_comparison\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import mathtext\r\n\r\n\r\nmath_tests = [\r\n r'$a+b+\\dot s+\\dot{s}+\\ldots$',\r\n r'$x \\doteq y$',\r\n r'\\$100.00 $\\alpha \\_$',\r\n r'$\\frac{\\$100.00}{y}$',\r\n r'$x y$',\r\n r'$x+y\\ x=y\\ x<y\\ x:y\\ x,y\\ x@y$',\r\n r'$100\\%y\\ x*y\\ x/y x\\$y$',\r\n r'$x\\leftarrow y\\ x\\forall y\\ x-y$',\r\n r'$x \\sf x \\bf x {\\cal X} \\rm x$',\r\n r'$x\\ x\\,x\\;x\\quad x\\qquad x\\!x\\hspace{ 0.5 }y$',\r\n r'$\\{ \\rm braces \\}$',\r\n r'$\\left[\\left\\lfloor\\frac{5}{\\frac{\\left(3\\right)}{4}} y\\right)\\right]$',\r\n r'$\\left(x\\right)$',\r\n r'$\\sin(x)$',\r\n r'$x_2$',\r\n r'$x^2$',\r\n r'$x^2_y$',\r\n r'$x_y^2$',\r\n r'$\\prod_{i=\\alpha_{i+1}}^\\infty$',\r\n r'$x = \\frac{x+\\frac{5}{2}}{\\frac{y+3}{8}}$',\r\n r'$dz/dt = \\gamma x^2 + {\\rm sin}(2\\pi y+\\phi)$',\r\n r'Foo: $\\alpha_{i+1}^j = {\\rm sin}(2\\pi f_j t_i) e^{-5 t_i/\\tau}$',\r\n r'$\\mathcal{R}\\prod_{i=\\alpha_{i+1}}^\\infty a_i \\sin(2 \\pi f x_i)$',\r\n r'Variable $i$ is good',\r\n r'$\\Delta_i^j$',\r\n r'$\\Delta^j_{i+1}$',\r\n r'$\\ddot{o}\\acute{e}\\grave{e}\\hat{O}\\breve{\\imath}\\tilde{n}\\vec{q}$',\r\n r\"$\\arccos((x^i))$\",\r\n r\"$\\gamma = \\frac{x=\\frac{6}{8}}{y} \\delta$\",\r\n r'$\\limsup_{x\\to\\infty}$',\r\n r'$\\oint^\\infty_0$',\r\n r\"$f'\\quad f'''(x)\\quad ''/\\mathrm{yr}$\",\r\n r'$\\frac{x_2888}{y}$',\r\n r\"$\\sqrt[3]{\\frac{X_2}{Y}}=5$\",\r\n r\"$\\sqrt[5]{\\prod^\\frac{x}{2\\pi^2}_\\infty}$\",\r\n r\"$\\sqrt[3]{x}=5$\",\r\n r'$\\frac{X}{\\frac{X}{Y}}$',\r\n r\"$W^{3\\beta}_{\\delta_1 \\rho_1 \\sigma_2} = U^{3\\beta}_{\\delta_1 \\rho_1} + \\frac{1}{8 \\pi 2} \\int^{\\alpha_2}_{\\alpha_2} d \\alpha^\\prime_2 \\left[\\frac{ U^{2\\beta}_{\\delta_1 \\rho_1} - \\alpha^\\prime_2U^{1\\beta}_{\\rho_1 \\sigma_2} }{U^{0\\beta}_{\\rho_1 \\sigma_2}}\\right]$\",\r\n r'$\\mathcal{H} = \\int d \\tau \\left(\\epsilon E^2 + \\mu H^2\\right)$',\r\n r'$\\widehat{abc}\\widetilde{def}$',\r\n '$\\\\Gamma \\\\Delta \\\\Theta \\\\Lambda \\\\Xi \\\\Pi \\\\Sigma \\\\Upsilon \\\\Phi \\\\Psi \\\\Omega$',\r\n '$\\\\alpha \\\\beta \\\\gamma \\\\delta \\\\epsilon \\\\zeta \\\\eta \\\\theta \\\\iota \\\\lambda \\\\mu \\\\nu \\\\xi \\\\pi \\\\kappa \\\\rho \\\\sigma \\\\tau \\\\upsilon \\\\phi \\\\chi \\\\psi$',\r\n\r\n # The examples prefixed by 'mmltt' are from the MathML torture test here:\r\n # https://developer.mozilla.org/en-US/docs/Mozilla/MathML_Project/MathML_Torture_Test\r\n r'${x}^{2}{y}^{2}$',\r\n r'${}_{2}F_{3}$',\r\n r'$\\frac{x+{y}^{2}}{k+1}$',\r\n r'$x+{y}^{\\frac{2}{k+1}}$',\r\n r'$\\frac{a}{b/2}$',\r\n r'${a}_{0}+\\frac{1}{{a}_{1}+\\frac{1}{{a}_{2}+\\frac{1}{{a}_{3}+\\frac{1}{{a}_{4}}}}}$',\r\n r'${a}_{0}+\\frac{1}{{a}_{1}+\\frac{1}{{a}_{2}+\\frac{1}{{a}_{3}+\\frac{1}{{a}_{4}}}}}$',\r\n r'$\\binom{n}{k/2}$',\r\n r'$\\binom{p}{2}{x}^{2}{y}^{p-2}-\\frac{1}{1-x}\\frac{1}{1-{x}^{2}}$',\r\n r'${x}^{2y}$',\r\n r'$\\sum _{i=1}^{p}\\sum _{j=1}^{q}\\sum _{k=1}^{r}{a}_{ij}{b}_{jk}{c}_{ki}$',\r\n r'$\\sqrt{1+\\sqrt{1+\\sqrt{1+\\sqrt{1+\\sqrt{1+\\sqrt{1+\\sqrt{1+x}}}}}}}$',\r\n r'$\\left(\\frac{{\\partial }^{2}}{\\partial {x}^{2}}+\\frac{{\\partial }^{2}}{\\partial {y}^{2}}\\right){|\\varphi \\left(x+iy\\right)|}^{2}=0$',\r\n r'${2}^{{2}^{{2}^{x}}}$',\r\n r'${\\int }_{1}^{x}\\frac{\\mathrm{dt}}{t}$',\r\n r'$\\int {\\int }_{D}\\mathrm{dx} \\mathrm{dy}$',\r\n # mathtex doesn't support array\r\n # 'mmltt18' : r'$f\\left(x\\right)=\\left\\{\\begin{array}{cc}\\hfill 1/3\\hfill & \\text{if_}0\\le x\\le 1;\\hfill \\\\ \\hfill 2/3\\hfill & \\hfill \\text{if_}3\\le x\\le 4;\\hfill \\\\ \\hfill 0\\hfill & \\text{elsewhere.}\\hfill \\end{array}$',\r\n # mathtex doesn't support stackrel\r\n # 'mmltt19' : r'$\\stackrel{\\stackrel{k\\text{times}}{\\ufe37}}{x+...+x}$',\r\n r'${y}_{{x}^{2}}$',\r\n # mathtex doesn't support the \"\\text\" command\r\n # 'mmltt21' : r'$\\sum _{p\\text{\\prime}}f\\left(p\\right)={\\int }_{t>1}f\\left(t\\right) d\\pi \\left(t\\right)$',\r\n # mathtex doesn't support array\r\n # 'mmltt23' : r'$\\left(\\begin{array}{cc}\\hfill \\left(\\begin{array}{cc}\\hfill a\\hfill & \\hfill b\\hfill \\\\ \\hfill c\\hfill & \\hfill d\\hfill \\end{array}\\right)\\hfill & \\hfill \\left(\\begin{array}{cc}\\hfill e\\hfill & \\hfill f\\hfill \\\\ \\hfill g\\hfill & \\hfill h\\hfill \\end{array}\\right)\\hfill \\\\ \\hfill 0\\hfill & \\hfill \\left(\\begin{array}{cc}\\hfill i\\hfill & \\hfill j\\hfill \\\\ \\hfill k\\hfill & \\hfill l\\hfill \\end{array}\\right)\\hfill \\end{array}\\right)$',\r\n # mathtex doesn't support array\r\n # 'mmltt24' : r'$det|\\begin{array}{ccccc}\\hfill {c}_{0}\\hfill & \\hfill {c}_{1}\\hfill & \\hfill {c}_{2}\\hfill & \\hfill \\dots \\hfill & \\hfill {c}_{n}\\hfill \\\\ \\hfill {c}_{1}\\hfill & \\hfill {c}_{2}\\hfill & \\hfill {c}_{3}\\hfill & \\hfill \\dots \\hfill & \\hfill {c}_{n+1}\\hfill \\\\ \\hfill {c}_{2}\\hfill & \\hfill {c}_{3}\\hfill & \\hfill {c}_{4}\\hfill & \\hfill \\dots \\hfill & \\hfill {c}_{n+2}\\hfill \\\\ \\hfill \\u22ee\\hfill & \\hfill \\u22ee\\hfill & \\hfill \\u22ee\\hfill & \\hfill \\hfill & \\hfill \\u22ee\\hfill \\\\ \\hfill {c}_{n}\\hfill & \\hfill {c}_{n+1}\\hfill & \\hfill {c}_{n+2}\\hfill & \\hfill \\dots \\hfill & \\hfill {c}_{2n}\\hfill \\end{array}|>0$',\r\n r'${y}_{{x}_{2}}$',\r\n r'${x}_{92}^{31415}+\\pi $',\r\n r'${x}_{{y}_{b}^{a}}^{{z}_{c}^{d}}$',\r\n r'${y}_{3}^{\\prime \\prime \\prime }$',\r\n r\"$\\left( \\xi \\left( 1 - \\xi \\right) \\right)$\", # Bug 2969451\r\n r\"$\\left(2 \\, a=b\\right)$\", # Sage bug #8125\r\n r\"$? ! &$\", # github issue #466\r\n r'$\\operatorname{cos} x$', # github issue #553\r\n r'$\\sum _{\\genfrac{}{}{0}{}{0\\leq i\\leq m}{0<j<n}}P\\left(i,j\\right)$',\r\n r\"$\\left\\Vert a \\right\\Vert \\left\\vert b \\right\\vert \\left| a \\right| \\left\\| b\\right\\| \\Vert a \\Vert \\vert b \\vert$\",\r\n r'$\\mathring{A} \\AA$',\r\n r'$M \\, M \\thinspace M \\/ M \\> M \\: M \\; M \\ M \\enspace M \\quad M \\qquad M \\! M$',\r\n r'$\\Cup$ $\\Cap$ $\\leftharpoonup$ $\\barwedge$ $\\rightharpoonup$',\r\n r'$\\dotplus$ $\\doteq$ $\\doteqdot$ $\\ddots$',\r\n r'$xyz^kx_kx^py^{p-2} d_i^jb_jc_kd x^j_i E^0 E^0_u$', # github issue #4873\r\n r'${xyz}^k{x}_{k}{x}^{p}{y}^{p-2} {d}_{i}^{j}{b}_{j}{c}_{k}{d} {x}^{j}_{i}{E}^{0}{E}^0_u$',\r\n r'${\\int}_x^x x\\oint_x^x x\\int_{X}^{X}x\\int_x x \\int^x x \\int_{x} x\\int^{x}{\\int}_{x} x{\\int}^{x}_{x}x$',\r\n r'testing$^{123}$',\r\n ' '.join('$\\\\' + p + '$' for p in sorted(mathtext.Parser._accentprefixed)),\r\n r'$6-2$; $-2$; $ -2$; ${-2}$; ${ -2}$; $20^{+3}_{-2}$',\r\n r'$\\overline{\\omega}^x \\frac{1}{2}_0^x$', # github issue #5444\r\n r'$,$ $.$ $1{,}234{, }567{ , }890$ and $1,234,567,890$', # github issue 5799\r\n r'$\\left(X\\right)_{a}^{b}$', # github issue 7615\r\n r'$\\dfrac{\\$100.00}{y}$', # github issue #1888\r\n]\r\n\r\ndigits = \"0123456789\"\r\nuppercase = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\r\nlowercase = \"abcdefghijklmnopqrstuvwxyz\"\r\nuppergreek = (\"\\\\Gamma \\\\Delta \\\\Theta \\\\Lambda \\\\Xi \\\\Pi \\\\Sigma \\\\Upsilon \\\\Phi \\\\Psi \"\r\n \"\\\\Omega\")\r\nlowergreek = (\"\\\\alpha \\\\beta \\\\gamma \\\\delta \\\\epsilon \\\\zeta \\\\eta \\\\theta \\\\iota \"\r\n \"\\\\lambda \\\\mu \\\\nu \\\\xi \\\\pi \\\\kappa \\\\rho \\\\sigma \\\\tau \\\\upsilon \"\r\n \"\\\\phi \\\\chi \\\\psi\")\r\nall = [digits, uppercase, lowercase, uppergreek, lowergreek]\r\n\r\n# Use stubs to reserve space if tests are removed\r\n# stub should be of the form (None, N) where N is the number of strings that\r\n# used to be tested\r\n# Add new tests at the end.\r\nfont_test_specs = [\r\n ([], all),\r\n (['mathrm'], all),\r\n (['mathbf'], all),\r\n (['mathit'], all),\r\n (['mathtt'], [digits, uppercase, lowercase]),\r\n (None, 3),\r\n (None, 3),\r\n (None, 3),\r\n (['mathbb'], [digits, uppercase, lowercase,\r\n r'\\Gamma \\Pi \\Sigma \\gamma \\pi']),\r\n (['mathrm', 'mathbb'], [digits, uppercase, lowercase,\r\n r'\\Gamma \\Pi \\Sigma \\gamma \\pi']),\r\n (['mathbf', 'mathbb'], [digits, uppercase, lowercase,\r\n r'\\Gamma \\Pi \\Sigma \\gamma \\pi']),\r\n (['mathcal'], [uppercase]),\r\n (['mathfrak'], [uppercase, lowercase]),\r\n (['mathbf', 'mathfrak'], [uppercase, lowercase]),\r\n (['mathscr'], [uppercase, lowercase]),\r\n (['mathsf'], [digits, uppercase, lowercase]),\r\n (['mathrm', 'mathsf'], [digits, uppercase, lowercase]),\r\n (['mathbf', 'mathsf'], [digits, uppercase, lowercase])\r\n ]\r\n\r\nfont_tests = []\r\nfor fonts, chars in font_test_specs:\r\n if fonts is None:\r\n font_tests.extend([None] * chars)\r\n else:\r\n wrapper = ''.join([\r\n ' '.join(fonts),\r\n ' $',\r\n *(r'\\%s{' % font for font in fonts),\r\n '%s',\r\n *('}' for font in fonts),\r\n '$',\r\n ])\r\n for set in chars:\r\n font_tests.append(wrapper % set)\r\n\r\nfont_tests = list(filter(lambda x: x[1] is not None, enumerate(font_tests)))\r\n\r\n\r\[email protected]\r\ndef baseline_images(request, fontset, index):\r\n return ['%s_%s_%02d' % (request.param, fontset, index)]\r\n\r\n\r\[email protected]('index, test', enumerate(math_tests),\r\n ids=[str(index) for index in range(len(math_tests))])\r\[email protected]('fontset',\r\n ['cm', 'stix', 'stixsans', 'dejavusans',\r\n 'dejavuserif'])\r\[email protected]('baseline_images', ['mathtext'], indirect=True)\r\n@image_comparison(baseline_images=None)\r\ndef test_mathtext_rendering(baseline_images, fontset, index, test):\r\n mpl.rcParams['mathtext.fontset'] = fontset\r\n fig = plt.figure(figsize=(5.25, 0.75))\r\n fig.text(0.5, 0.5, test,\r\n horizontalalignment='center', verticalalignment='center')\r\n\r\n\r\[email protected]('index, test', font_tests,\r\n ids=[str(index) for index, _ in font_tests])\r\[email protected]('fontset',\r\n ['cm', 'stix', 'stixsans', 'dejavusans',\r\n 'dejavuserif'])\r\[email protected]('baseline_images', ['mathfont'], indirect=True)\r\n@image_comparison(baseline_images=None, extensions=['png'])\r\ndef test_mathfont_rendering(baseline_images, fontset, index, test):\r\n mpl.rcParams['mathtext.fontset'] = fontset\r\n fig = plt.figure(figsize=(5.25, 0.75))\r\n fig.text(0.5, 0.5, test,\r\n horizontalalignment='center', verticalalignment='center')\r\n\r\n\r\ndef test_fontinfo():\r\n fontpath = mpl.font_manager.findfont(\"DejaVu Sans\")\r\n font = mpl.ft2font.FT2Font(fontpath)\r\n table = font.get_sfnt_table(\"head\")\r\n assert table['version'] == (1, 0)\r\n\r\n\r\[email protected](\r\n 'math, msg',\r\n [\r\n (r'$\\hspace{}$', r'Expected \\hspace{n}'),\r\n (r'$\\hspace{foo}$', r'Expected \\hspace{n}'),\r\n (r'$\\frac$', r'Expected \\frac{num}{den}'),\r\n (r'$\\frac{}{}$', r'Expected \\frac{num}{den}'),\r\n (r'$\\binom$', r'Expected \\binom{num}{den}'),\r\n (r'$\\binom{}{}$', r'Expected \\binom{num}{den}'),\r\n (r'$\\genfrac$',\r\n r'Expected \\genfrac{ldelim}{rdelim}{rulesize}{style}{num}{den}'),\r\n (r'$\\genfrac{}{}{}{}{}{}$',\r\n r'Expected \\genfrac{ldelim}{rdelim}{rulesize}{style}{num}{den}'),\r\n (r'$\\sqrt$', r'Expected \\sqrt{value}'),\r\n (r'$\\sqrt f$', r'Expected \\sqrt{value}'),\r\n (r'$\\overline$', r'Expected \\overline{value}'),\r\n (r'$\\overline{}$', r'Expected \\overline{value}'),\r\n (r'$\\leftF$', r'Expected a delimiter'),\r\n (r'$\\rightF$', r'Unknown symbol: \\rightF'),\r\n (r'$\\left(\\right$', r'Expected a delimiter'),\r\n (r'$\\left($', r'Expected \"\\right\"'),\r\n (r'$\\dfrac$', r'Expected \\dfrac{num}{den}'),\r\n (r'$\\dfrac{}{}$', r'Expected \\dfrac{num}{den}'),\r\n ],\r\n ids=[\r\n 'hspace without value',\r\n 'hspace with invalid value',\r\n 'frac without parameters',\r\n 'frac with empty parameters',\r\n 'binom without parameters',\r\n 'binom with empty parameters',\r\n 'genfrac without parameters',\r\n 'genfrac with empty parameters',\r\n 'sqrt without parameters',\r\n 'sqrt with invalid value',\r\n 'overline without parameters',\r\n 'overline with empty parameter',\r\n 'left with invalid delimiter',\r\n 'right with invalid delimiter',\r\n 'unclosed parentheses with sizing',\r\n 'unclosed parentheses without sizing',\r\n 'dfrac without parameters',\r\n 'dfrac with empty parameters',\r\n ]\r\n)\r\ndef test_mathtext_exceptions(math, msg):\r\n parser = mathtext.MathTextParser('agg')\r\n\r\n with pytest.raises(ValueError, match=re.escape(msg)):\r\n parser.parse(math)\r\n\r\n\r\ndef test_single_minus_sign():\r\n plt.figure(figsize=(0.3, 0.3))\r\n plt.text(0.5, 0.5, '$-$')\r\n for spine in plt.gca().spines.values():\r\n spine.set_visible(False)\r\n plt.gca().set_xticks([])\r\n plt.gca().set_yticks([])\r\n\r\n buff = io.BytesIO()\r\n plt.savefig(buff, format=\"rgba\", dpi=1000)\r\n array = np.frombuffer(buff.getvalue(), dtype=np.uint8)\r\n\r\n # If this fails, it would be all white\r\n assert not np.all(array == 0xff)\r\n\r\n\r\n@check_figures_equal(extensions=[\"png\"])\r\ndef test_spaces(fig_test, fig_ref):\r\n fig_test.subplots().set_title(r\"$1\\,2\\>3\\ 4$\")\r\n fig_ref.subplots().set_title(r\"$1\\/2\\:3~4$\")\r\n\r\n\r\ndef test_mathtext_fallback_valid():\r\n for fallback in ['cm', 'stix', 'stixsans', 'None']:\r\n mpl.rcParams['mathtext.fallback'] = fallback\r\n\r\n\r\[email protected]\r\ndef test_mathtext_fallback_invalid():\r\n for fallback in ['abc', '']:\r\n mpl.rcParams['mathtext.fallback'] = fallback\r\n\r\n\r\[email protected]\r\ndef test_mathtext_fallback_to_cm_invalid():\r\n for fallback in [True, False]:\r\n mpl.rcParams['mathtext.fallback_to_cm'] = fallback\r\n\r\n\r\[email protected](\r\n \"fallback,fontlist\",\r\n [(\"cm\", ['DejaVu Sans', 'mpltest', 'STIXGeneral', 'cmr10', 'STIXGeneral']),\r\n (\"stix\", ['DejaVu Sans', 'mpltest', 'STIXGeneral'])])\r\ndef test_mathtext_fallback(fallback, fontlist):\r\n mpl.font_manager.fontManager.addfont(\r\n os.path.join((os.path.dirname(os.path.realpath(__file__))), 'mpltest.ttf'))\r\n mpl.rcParams[\"svg.fonttype\"] = 'none'\r\n mpl.rcParams['mathtext.fontset'] = 'custom'\r\n mpl.rcParams['mathtext.rm'] = 'mpltest'\r\n mpl.rcParams['mathtext.it'] = 'mpltest:italic'\r\n mpl.rcParams['mathtext.bf'] = 'mpltest:bold'\r\n mpl.rcParams['mathtext.fallback'] = fallback\r\n\r\n test_str = r'a$A\\AA\\breve\\gimel$'\r\n\r\n buff = io.BytesIO()\r\n fig, ax = plt.subplots()\r\n fig.text(.5, .5, test_str, fontsize=40, ha='center')\r\n fig.savefig(buff, format=\"svg\")\r\n char_fonts = [\r\n line.split(\"font-family:\")[-1].split(\";\")[0]\r\n for line in str(buff.getvalue()).split(r\"\\n\") if \"tspan\" in line\r\n ]\r\n assert char_fonts == fontlist\r\n mpl.font_manager.fontManager.ttflist = mpl.font_manager.fontManager.ttflist[:-1]\r\n\r\n\r\ndef test_math_to_image(tmpdir):\r\n mathtext.math_to_image('$x^2$', str(tmpdir.join('example.png')))\r\n mathtext.math_to_image('$x^2$', io.BytesIO())\r\n\r\n\r\ndef test_mathtext_to_png(tmpdir):\r\n mt = mathtext.MathTextParser('bitmap')\r\n mt.to_png(str(tmpdir.join('example.png')), '$x^2$')\r\n mt.to_png(io.BytesIO(), '$x^2$')\r\n", "#!/usr/bin/env python3\r\n\r\nfrom typing import NamedTuple\r\nimport enum\r\nimport logging\r\nimport os\r\nimport threading\r\nfrom torch.distributed.nn import RemoteModule\r\n\r\nimport torch\r\nfrom torch.distributed import rpc\r\nfrom torch.nn.parallel import DistributedDataParallel\r\nfrom torch.testing._internal.common_distributed import (\r\n MultiProcessTestCase,\r\n requires_gloo,\r\n requires_nccl,\r\n skip_if_lt_x_gpu,\r\n)\r\nfrom torch.testing._internal.common_utils import (\r\n TEST_WITH_ASAN,\r\n)\r\nfrom torch.testing._internal.dist_utils import dist_init\r\nimport torch.distributed as dist\r\nimport torch.distributed.autograd as dist_autograd\r\nimport torch.nn as nn\r\nimport unittest\r\nfrom torch.testing._internal.distributed.rpc.rpc_agent_test_fixture import (\r\n RpcAgentTestFixture,\r\n)\r\n\r\nNUM_EM_ROW = 2\r\nD_SPARSE = 3\r\nD_DENSE = 2\r\nD_HID = 3\r\nD_OUT = 1\r\nNUM_TRAINERS = 4\r\n# Trainers + the master + the remote worker\r\nWORLD_SIZE = NUM_TRAINERS + 2\r\nTRAINER_RANKS = list(range(NUM_TRAINERS))\r\nREMOTE_WORKER_RANK = TRAINER_RANKS[-1] + 1\r\nMASTER_RANK = REMOTE_WORKER_RANK + 1\r\n\r\n\r\nclass DdpMode(enum.Enum):\r\n # Don't apply DDP\r\n NONE = enum.auto()\r\n # Apply DDP to the top level nn.Module\r\n OUTSIDE = enum.auto()\r\n # Embed DDP inside the top level nn.Module\r\n INSIDE = enum.auto()\r\n\r\n\r\ndef init_logger():\r\n logger = logging.getLogger(__name__)\r\n level = logging.DEBUG if \"debug\" in os.environ else logging.INFO\r\n logger.setLevel(level)\r\n console = logging.StreamHandler()\r\n formatter = logging.Formatter(\r\n \"%(asctime)s %(filename)s:%(lineno)s %(levelname)s p:%(processName)s t:%(threadName)s: %(message)s\"\r\n )\r\n console.setFormatter(formatter)\r\n console.setLevel(level)\r\n # add the handlers to the logger\r\n logger.addHandler(console)\r\n logger.propagate = False\r\n return logger\r\n\r\n\r\ngLogger = init_logger()\r\n\r\n\r\nclass FeatureSet(NamedTuple):\r\n \"\"\" A feature set has 2 types of features\"\"\"\r\n\r\n dense_features: torch.Tensor\r\n sparse_features: torch.LongTensor\r\n values: torch.Tensor\r\n\r\n\r\ndef _call_method(method, rref, *args, **kwargs):\r\n return method(rref.local_value(), *args, **kwargs)\r\n\r\n\r\ndef _remote_method(method, rref, *args, **kwargs):\r\n args_tup = tuple([method, rref] + list(args))\r\n return rpc.rpc_sync(\r\n rref.owner(), _call_method, args=args_tup, kwargs=kwargs\r\n )\r\n\r\n\r\ndef _remote_method_async(method, rref, *args, **kwargs):\r\n args_tup = tuple([method, rref] + list(args))\r\n return rpc.rpc_async(\r\n rref.owner(), _call_method, args=args_tup, kwargs=kwargs\r\n )\r\n\r\n\r\nclass RemoteEM(nn.Module):\r\n def __init__(self, num_embeddings: int, embedding_dim: int):\r\n gLogger.info(f\"Initing RemoteEM with {num_embeddings} {embedding_dim}\")\r\n super(RemoteEM, self).__init__()\r\n init_em = [0.5] * embedding_dim\r\n self.em = nn.EmbeddingBag(\r\n num_embeddings,\r\n embedding_dim,\r\n _weight=torch.Tensor([init_em] * num_embeddings),\r\n )\r\n\r\n def forward(self, input: torch.Tensor):\r\n gLogger.debug(f\"Running RemoteEM.forward() on: {input}\")\r\n return self.em(input, offsets=torch.LongTensor(range(input.shape[0])))\r\n\r\n\r\n# Return a linear module with predefined parameters.\r\ndef getLinear(d_in, d_out):\r\n l = nn.Linear(d_in, d_out, bias=False)\r\n w = torch.ones((d_out, d_in))\r\n w[0][0] = -1\r\n w.requires_grad_()\r\n l.weight.data = w\r\n return l\r\n\r\n\r\nclass RemoteNet(nn.Module):\r\n def __init__(self, d_in: int, d_out: int):\r\n gLogger.info(f\"Initing RemoteNet with {d_in} {d_out}\")\r\n super(RemoteNet, self).__init__()\r\n self.fc = getLinear(d_in, d_out)\r\n self.relu = nn.ReLU()\r\n\r\n def forward(self, input: torch.Tensor):\r\n gLogger.debug(f\"Running RemoteNet.forward() on: {input}\")\r\n return self.relu(self.fc(input))\r\n\r\n\r\nclass HybridModel(nn.Module):\r\n def __init__(\r\n self,\r\n remote_em_rref: rpc.RRef,\r\n remote_net_rref: rpc.RRef,\r\n process_group_for_ddp: dist.ProcessGroup = None,\r\n ):\r\n super(HybridModel, self).__init__()\r\n self.remote_em_rref = remote_em_rref\r\n self.remote_net_rref = remote_net_rref\r\n self.fc1 = getLinear(D_DENSE, D_DENSE)\r\n self.fc2 = getLinear(D_HID, D_OUT)\r\n\r\n self.non_ddp_params = tuple(self.fc1.parameters()) + tuple(\r\n self.fc2.parameters()\r\n )\r\n self.ddp_params = ()\r\n\r\n if process_group_for_ddp is not None:\r\n self.non_ddp_params, self.ddp_params = (\r\n tuple(self.fc1.parameters()),\r\n tuple(self.fc2.parameters()),\r\n )\r\n gLogger.info(\"Use DDP for the second local net.\")\r\n self.fc2 = DistributedDataParallel(\r\n self.fc2,\r\n check_reduction=True,\r\n process_group=process_group_for_ddp,\r\n )\r\n\r\n gLogger.info(\r\n f\"HybridModel has {len(list(self.parameters()))} groups of parameters.\"\r\n )\r\n\r\n def forward(self, input: FeatureSet):\r\n gLogger.debug(f\"Running HybridModel.forward on {input}\")\r\n sparse = _remote_method(\r\n RemoteEM.forward, self.remote_em_rref, input.sparse_features\r\n )\r\n # The same size of mini batch.\r\n assert sparse.shape[0] == input.dense_features.shape[0]\r\n dense = self.fc1(input.dense_features)\r\n x = torch.cat((dense, sparse), 1)\r\n gLogger.debug(f\"Concatenated feature: {x}\")\r\n x = _remote_method(RemoteNet.forward, self.remote_net_rref, x)\r\n return self.fc2(x)\r\n\r\n\r\nclass Trainer:\r\n def __init__(\r\n self,\r\n remote_em_rref: rpc.RRef,\r\n remote_net_rref: rpc.RRef,\r\n ddp_mode: DdpMode,\r\n rank: int,\r\n ):\r\n self.rank = rank\r\n self.trainer_group = dist.new_group(TRAINER_RANKS)\r\n self.remote_em_rref = remote_em_rref\r\n self.remote_net_rref = remote_net_rref\r\n self.hybrid_module = HybridModel(\r\n self.remote_em_rref,\r\n self.remote_net_rref,\r\n self.trainer_group\r\n if ddp_mode in (DdpMode.INSIDE,)\r\n else None,\r\n )\r\n self.ddp_params, self.non_ddp_params = (\r\n self.hybrid_module.ddp_params,\r\n self.hybrid_module.non_ddp_params,\r\n )\r\n if ddp_mode == DdpMode.OUTSIDE:\r\n gLogger.info(\"Wrapping the whole hybrid module into DDP.\")\r\n self.ddp_params += self.non_ddp_params\r\n self.non_ddp_params = ()\r\n self.hybrid_module = DistributedDataParallel(\r\n self.hybrid_module,\r\n check_reduction=True,\r\n process_group=self.trainer_group,\r\n )\r\n gLogger.info(\r\n f\"Succeeded in creating a HybridModel instance with \"\r\n f\"{len(self.ddp_params)} ddp params and {len(self.non_ddp_params)} \"\r\n f\"other local params.\"\r\n )\r\n\r\n def destroy_pg(self):\r\n dist.destroy_process_group(self.trainer_group)\r\n\r\n def train_batch(self, mini_batch: FeatureSet):\r\n grads_dict = None\r\n with dist_autograd.context() as context_id:\r\n output = self.hybrid_module.forward(mini_batch)\r\n loss = (output * mini_batch.values).sum()\r\n dist_autograd.backward(context_id, [loss])\r\n grads_dict = dist_autograd.get_gradients(context_id)\r\n gLogger.info(\r\n f\"Loss is {loss} for mini batch: {mini_batch}. \"\r\n f\"Grads dict has {len(grads_dict)} entries: {grads_dict}\"\r\n )\r\n return (\r\n tuple(grads_dict[param] for param in self.ddp_params),\r\n tuple(grads_dict[param] for param in self.non_ddp_params),\r\n )\r\n\r\n\r\ndef get_training_examples():\r\n n = 16\r\n training_examples = FeatureSet(\r\n dense_features=torch.zeros((n, D_DENSE)),\r\n sparse_features=torch.zeros(n, dtype=torch.long),\r\n values=torch.zeros(n),\r\n )\r\n idx = 0\r\n # Every example has another one that has exactly the same features but an\r\n # opposite value. Therefore, their grads cancel each other in all-reduce.\r\n for value in (-1, 1):\r\n for x in (-1 * value, 1 * value):\r\n for y in (1 * value, -1 * value):\r\n for z in (0, 1):\r\n training_examples.dense_features[idx, :] = torch.Tensor(\r\n (x, y)\r\n )\r\n training_examples.sparse_features[idx] = z\r\n training_examples.values[idx] = value\r\n idx += 1\r\n\r\n # Split the examples among NUM_TRAINERS trainers\r\n assert 0 == (n % NUM_TRAINERS)\r\n examples_per_trainer = int(n / NUM_TRAINERS)\r\n return [\r\n FeatureSet(\r\n dense_features=training_examples.dense_features[\r\n start : start + examples_per_trainer, :\r\n ],\r\n sparse_features=training_examples.sparse_features[\r\n start : start + examples_per_trainer\r\n ],\r\n values=training_examples.values[\r\n start : start + examples_per_trainer\r\n ],\r\n )\r\n for start in range(0, n, examples_per_trainer)\r\n ]\r\n\r\n\r\nshutdown_signal = threading.Condition()\r\n\r\ndef set_shutdown_signal():\r\n global shutdown_signal\r\n with shutdown_signal:\r\n shutdown_signal.notify()\r\n\r\[email protected](\r\n TEST_WITH_ASAN,\r\n \"Skip ASAN as torch + multiprocessing spawn have known issues\",\r\n)\r\nclass TestDdpUnderDistAutograd(MultiProcessTestCase, RpcAgentTestFixture):\r\n\r\n @property\r\n def world_size(self) -> int:\r\n return WORLD_SIZE\r\n\r\n def remote_worker_name(self) -> str:\r\n # The name has to be consistent with that in 'dist_init' decorator.\r\n return f\"worker{REMOTE_WORKER_RANK}\"\r\n\r\n def trainer_name(self, rank):\r\n # The name has to be consistent with that in 'dist_init' decorator.\r\n return f\"worker{rank}\"\r\n\r\n def setUp(self):\r\n super(TestDdpUnderDistAutograd, self).setUp()\r\n\r\n self._spawn_processes()\r\n\r\n def tearDown(self):\r\n super(TestDdpUnderDistAutograd, self).tearDown()\r\n\r\n def _remote_worker_process(self):\r\n gLogger.info(\"The remote worker is running.\")\r\n dist.init_process_group(\r\n backend=\"gloo\",\r\n init_method=\"file://{}\".format(self.file_name),\r\n world_size=self.world_size,\r\n rank=self.rank)\r\n global shutdown_signal\r\n with shutdown_signal:\r\n shutdown_signal.wait()\r\n gLogger.info(\"Exiting remote worker.\")\r\n dist.destroy_process_group()\r\n\r\n def _trainer_process(self, rank: int):\r\n gLogger.info(f\"Running the trainer #{rank}...\")\r\n gLogger.info(\r\n f\"Initing trainer process group by trainer #{rank} with ranks {TRAINER_RANKS}\"\r\n )\r\n dist.init_process_group(\r\n backend=\"gloo\",\r\n init_method=\"file://{}\".format(self.file_name),\r\n world_size=self.world_size,\r\n rank=self.rank)\r\n\r\n gLogger.info(f\"Waiting for shutdown signal on trainer #{rank}...\")\r\n\r\n global shutdown_signal\r\n with shutdown_signal:\r\n shutdown_signal.wait()\r\n gLogger.info(f\"Exiting the trainer #{rank}...\")\r\n dist.destroy_process_group()\r\n\r\n def _master_process(self, ddp_mode: DdpMode):\r\n gLogger.info(\"Running the master process...\")\r\n dist.init_process_group(\r\n backend=\"gloo\",\r\n init_method=\"file://{}\".format(self.file_name),\r\n world_size=self.world_size,\r\n rank=self.rank)\r\n remote_em_rref = rpc.remote(\r\n self.remote_worker_name(), RemoteEM, args=(NUM_EM_ROW, D_SPARSE)\r\n )\r\n remote_net_rref = rpc.remote(\r\n self.remote_worker_name(),\r\n RemoteNet,\r\n args=(D_DENSE + D_SPARSE, D_HID),\r\n )\r\n gLogger.info(\"Created remote rrefs on master\")\r\n self.do_test_on_master(ddp_mode, remote_em_rref, remote_net_rref)\r\n\r\n def do_test_on_master(\r\n self,\r\n ddp_mode: DdpMode,\r\n remote_em_rref: rpc.RRef,\r\n remote_net_rref: rpc.RRef,\r\n ):\r\n trainer_rrefs = []\r\n for rank in TRAINER_RANKS:\r\n trainer = self.trainer_name(rank)\r\n trainer_rrefs.append(\r\n rpc.remote(\r\n trainer,\r\n Trainer,\r\n args=(remote_em_rref, remote_net_rref, ddp_mode, rank),\r\n )\r\n )\r\n\r\n training_examples = get_training_examples()\r\n for _ in range(3):\r\n futures = []\r\n for idx, trainer_rref in enumerate(trainer_rrefs):\r\n futures.append(\r\n _remote_method_async(\r\n Trainer.train_batch,\r\n trainer_rref,\r\n training_examples[idx],\r\n )\r\n )\r\n\r\n for future in futures:\r\n ddp_grads, non_ddp_grads = future.wait()\r\n for grad in ddp_grads:\r\n self.assertEqual(\r\n grad,\r\n torch.zeros_like(grad),\r\n msg=\"The grad for any ddp parameter should be zeros, because \"\r\n \"the training examples' grads cancel each other.\",\r\n )\r\n for grad in non_ddp_grads:\r\n self.assertNotEqual(\r\n grad,\r\n torch.zeros_like(grad),\r\n msg=\"The grad for any non-ddp parameter shouldn't be zeros\",\r\n )\r\n\r\n # Destroy process groups\r\n for idx, trainer_rref in enumerate(trainer_rrefs):\r\n _remote_method_async(\r\n Trainer.destroy_pg,\r\n trainer_rref,\r\n ).wait()\r\n\r\n # Send shutdown signals.\r\n for rank in TRAINER_RANKS:\r\n trainer = self.trainer_name(rank)\r\n rpc.rpc_sync(trainer, set_shutdown_signal, args=())\r\n\r\n rpc.rpc_sync(self.remote_worker_name(), set_shutdown_signal, args=())\r\n\r\n def _do_test(self, ddp_mode):\r\n if self.rank == MASTER_RANK:\r\n self._master_process(ddp_mode)\r\n elif self.rank == REMOTE_WORKER_RANK:\r\n self._remote_worker_process()\r\n elif self.rank in TRAINER_RANKS:\r\n self._trainer_process(self.rank)\r\n else:\r\n raise RuntimeError(f\"Unknow process rank: {self.rank}\")\r\n\r\n @requires_gloo()\r\n @dist_init\r\n def test_backward_no_ddp(self):\r\n self._do_test(DdpMode.NONE)\r\n\r\n @requires_gloo()\r\n @dist_init\r\n def test_backward_ddp_outside(self):\r\n self._do_test(DdpMode.OUTSIDE)\r\n\r\n @requires_gloo()\r\n @dist_init\r\n def test_backward_ddp_inside(self):\r\n self._do_test(DdpMode.INSIDE)\r\n\r\n\r\[email protected](\r\n TEST_WITH_ASAN,\r\n \"Skip ASAN as torch + multiprocessing spawn have known issues\",\r\n)\r\nclass TestDdpComparison(MultiProcessTestCase, RpcAgentTestFixture):\r\n\r\n @property\r\n def world_size(self) -> int:\r\n return NUM_TRAINERS\r\n\r\n def trainer_name(self, rank):\r\n # The name has to be consistent with that in 'dist_init' decorator.\r\n return f\"worker{rank}\"\r\n\r\n def setUp(self):\r\n super(TestDdpComparison, self).setUp()\r\n\r\n self._spawn_processes()\r\n\r\n def tearDown(self):\r\n super(TestDdpComparison, self).tearDown()\r\n\r\n @requires_gloo()\r\n @dist_init\r\n def test_ddp_comparison(self):\r\n gLogger.info(f\"Running trainer rank: {self.rank}\")\r\n # Each trainer uses a different random seed. Otherwise, they are going\r\n # to have exactly the same initial model parameters, input, and\r\n # therefore grads. That means the grads will be the same before and\r\n # after DDP's all-reduce.\r\n torch.manual_seed(self.rank)\r\n dist.init_process_group(\r\n backend=\"gloo\",\r\n init_method=\"file://{}\".format(self.file_name),\r\n world_size=self.world_size,\r\n rank=self.rank)\r\n net = nn.Linear(2, 3)\r\n ddp_net = DistributedDataParallel(\r\n net\r\n )\r\n inputs = torch.rand((3, 2))\r\n\r\n # Use distributed autograd. The gradients will be in RPC context map.\r\n grads_dict = {}\r\n with dist_autograd.context() as context_id:\r\n loss = ddp_net(inputs).norm()\r\n dist_autograd.backward(context_id, [loss])\r\n grads_dict = dist_autograd.get_gradients(context_id)\r\n gLogger.info(f\"Trainer #{self.rank} got grad dict: {grads_dict}\")\r\n\r\n # Use local autograd. The gradients will be in each variable's '.grad'.\r\n loss = ddp_net(inputs).norm()\r\n loss.backward()\r\n\r\n # The gradients should be the same\r\n for param in net.parameters():\r\n self.assertTrue(\r\n param in grads_dict,\r\n msg=f\"Param {param} is not in dist_auto grad dict {grads_dict}\",\r\n )\r\n self.assertEqual(\r\n grads_dict[param],\r\n param.grad,\r\n msg=f\"The grads for param {param} are different under local \"\r\n f\"and dist autograd: {param.grad} \\n---\\n {grads_dict[param]}\",\r\n )\r\n dist.destroy_process_group()\r\n\r\n @requires_gloo()\r\n @dist_init\r\n def test_ddp_dist_autograd_sparse_grads(self):\r\n # Each trainer uses a different random seed. Otherwise, they are going\r\n # to have exactly the same initial model parameters, input, and\r\n # therefore grads. That means the grads will be the same before and\r\n # after DDP's all-reduce.\r\n torch.manual_seed(self.rank)\r\n dist.init_process_group(\r\n backend=\"gloo\",\r\n init_method=\"file://{}\".format(self.file_name),\r\n world_size=self.world_size,\r\n rank=self.rank)\r\n\r\n model = nn.EmbeddingBag(10, 3, sparse=True)\r\n ddp_model = DistributedDataParallel(model)\r\n\r\n # Different inputs for each\r\n input = torch.LongTensor(10).random_(0, 10)\r\n offsets = torch.LongTensor([0, 4])\r\n\r\n # Run local.\r\n loss = ddp_model(input, offsets).sum()\r\n loss.backward()\r\n\r\n with dist_autograd.context() as context_id:\r\n loss = ddp_model(input, offsets).sum()\r\n dist_autograd.backward(context_id, [loss])\r\n grads_dict = dist_autograd.get_gradients(context_id)\r\n self.assertEqual(1, len(grads_dict))\r\n self.assertEqual(model.weight.grad, grads_dict[model.weight])\r\n\r\n @staticmethod\r\n def get_remote_grads(rref, context_id):\r\n return dist_autograd.get_gradients(context_id)[rref.local_value().weight]\r\n\r\n @requires_gloo()\r\n @dist_init\r\n def test_ddp_dist_autograd_local_vs_remote(self):\r\n # Each trainer uses a different random seed. Otherwise, they are going\r\n # to have exactly the same initial model parameters, input, and\r\n # therefore grads. That means the grads will be the same before and\r\n # after DDP's all-reduce.\r\n torch.manual_seed(self.rank)\r\n dist.init_process_group(\r\n backend=\"gloo\",\r\n init_method=\"file://{}\".format(self.file_name),\r\n world_size=self.world_size,\r\n rank=self.rank)\r\n\r\n remote_layer1 = RemoteModule(\"worker0\", nn.Linear, args=(10, 5, False))\r\n layer1 = nn.Linear(10, 5, False)\r\n # Start with the same parameters for remote and local\r\n layer1.weight = remote_layer1.module_rref.to_here().weight\r\n\r\n # Run local case.\r\n layer2 = nn.Linear(5, 1)\r\n inputs = torch.rand((10, 10))\r\n ddp_model = DistributedDataParallel(layer2)\r\n loss = ddp_model(layer1(inputs)).sum()\r\n loss.backward()\r\n\r\n # Run remote case.\r\n with dist_autograd.context() as context_id:\r\n loss = ddp_model(remote_layer1(inputs)).sum()\r\n dist_autograd.backward(context_id, [loss])\r\n grads_dict = dist_autograd.get_gradients(context_id)\r\n dist.barrier()\r\n self.assertEqual(layer2.weight.grad, grads_dict[layer2.weight])\r\n self.assertEqual(\r\n layer1.weight.grad,\r\n rpc.rpc_sync(\r\n \"worker0\",\r\n TestDdpComparison.get_remote_grads,\r\n args=(remote_layer1.module_rref, context_id)\r\n )\r\n )\r\n\r\n @skip_if_lt_x_gpu(NUM_TRAINERS)\r\n @requires_nccl()\r\n @dist_init\r\n def test_ddp_dist_autograd_local_vs_remote_gpu(self):\r\n # Each trainer uses a different random seed. Otherwise, they are going\r\n # to have exactly the same initial model parameters, input, and\r\n # therefore grads. That means the grads will be the same before and\r\n # after DDP's all-reduce.\r\n torch.manual_seed(self.rank)\r\n dist.init_process_group(\r\n backend=\"gloo\",\r\n init_method=\"file://{}\".format(self.file_name),\r\n world_size=self.world_size,\r\n rank=self.rank)\r\n\r\n remote_layer1 = RemoteModule(\"worker0\", nn.Linear, args=(10, 7, False))\r\n layer1 = nn.Linear(10, 7, False)\r\n # Start with the same parameters for remote and local\r\n layer1.weight = remote_layer1.module_rref.to_here().weight\r\n\r\n layer2 = nn.Linear(7, 5).cuda(self.rank)\r\n ddp_layer2 = DistributedDataParallel(layer2, device_ids=[self.rank])\r\n\r\n remote_layer3 = RemoteModule(\"worker0\", nn.Linear, args=(5, 3, False))\r\n layer3 = nn.Linear(5, 3, False)\r\n # Start with the same parameters for remote and local\r\n layer3.weight = remote_layer3.module_rref.to_here().weight\r\n\r\n layer4 = nn.Linear(3, 1).cuda(self.rank)\r\n ddp_layer4 = DistributedDataParallel(layer4, device_ids=[self.rank])\r\n\r\n # Run local case.\r\n inputs = torch.rand((10, 10))\r\n loss = ddp_layer4(\r\n layer3(\r\n ddp_layer2(\r\n layer1(inputs).cuda(self.rank)\r\n ).cpu()\r\n ).cuda(self.rank)\r\n ).sum()\r\n loss.backward()\r\n\r\n # Run remote case.\r\n with dist_autograd.context() as context_id:\r\n loss = ddp_layer4(\r\n remote_layer3(\r\n ddp_layer2(\r\n remote_layer1(inputs).cuda(self.rank)\r\n ).cpu()\r\n ).cuda(self.rank)\r\n ).sum()\r\n dist_autograd.backward(context_id, [loss])\r\n grads_dict = dist_autograd.get_gradients(context_id)\r\n dist.barrier()\r\n self.assertEqual(\r\n layer1.weight.grad,\r\n rpc.rpc_sync(\r\n \"worker0\",\r\n TestDdpComparison.get_remote_grads,\r\n args=(remote_layer1.module_rref, context_id)\r\n )\r\n )\r\n self.assertEqual(layer2.weight.grad, grads_dict[layer2.weight])\r\n self.assertEqual(\r\n layer3.weight.grad,\r\n rpc.rpc_sync(\r\n \"worker0\",\r\n TestDdpComparison.get_remote_grads,\r\n args=(remote_layer3.module_rref, context_id)\r\n )\r\n )\r\n self.assertEqual(layer4.weight.grad, grads_dict[layer4.weight])\r\n", "import math\r\nfrom torch._six import inf, nan\r\nfrom numbers import Number\r\n\r\nimport torch\r\nfrom torch.distributions import constraints\r\nfrom torch.distributions.distribution import Distribution\r\nfrom torch.distributions.utils import broadcast_all\r\n\r\n\r\nclass Cauchy(Distribution):\r\n r\"\"\"\r\n Samples from a Cauchy (Lorentz) distribution. The distribution of the ratio of\r\n independent normally distributed random variables with means `0` follows a\r\n Cauchy distribution.\r\n\r\n Example::\r\n\r\n >>> m = Cauchy(torch.tensor([0.0]), torch.tensor([1.0]))\r\n >>> m.sample() # sample from a Cauchy distribution with loc=0 and scale=1\r\n tensor([ 2.3214])\r\n\r\n Args:\r\n loc (float or Tensor): mode or median of the distribution.\r\n scale (float or Tensor): half width at half maximum.\r\n \"\"\"\r\n arg_constraints = {'loc': constraints.real, 'scale': constraints.positive}\r\n support = constraints.real\r\n has_rsample = True\r\n\r\n def __init__(self, loc, scale, validate_args=None):\r\n self.loc, self.scale = broadcast_all(loc, scale)\r\n if isinstance(loc, Number) and isinstance(scale, Number):\r\n batch_shape = torch.Size()\r\n else:\r\n batch_shape = self.loc.size()\r\n super(Cauchy, self).__init__(batch_shape, validate_args=validate_args)\r\n\r\n def expand(self, batch_shape, _instance=None):\r\n new = self._get_checked_instance(Cauchy, _instance)\r\n batch_shape = torch.Size(batch_shape)\r\n new.loc = self.loc.expand(batch_shape)\r\n new.scale = self.scale.expand(batch_shape)\r\n super(Cauchy, new).__init__(batch_shape, validate_args=False)\r\n new._validate_args = self._validate_args\r\n return new\r\n\r\n @property\r\n def mean(self):\r\n return torch.full(self._extended_shape(), nan, dtype=self.loc.dtype, device=self.loc.device)\r\n\r\n @property\r\n def variance(self):\r\n return torch.full(self._extended_shape(), inf, dtype=self.loc.dtype, device=self.loc.device)\r\n\r\n def rsample(self, sample_shape=torch.Size()):\r\n shape = self._extended_shape(sample_shape)\r\n eps = self.loc.new(shape).cauchy_()\r\n return self.loc + eps * self.scale\r\n\r\n def log_prob(self, value):\r\n if self._validate_args:\r\n self._validate_sample(value)\r\n return -math.log(math.pi) - self.scale.log() - (1 + ((value - self.loc) / self.scale)**2).log()\r\n\r\n def cdf(self, value):\r\n if self._validate_args:\r\n self._validate_sample(value)\r\n return torch.atan((value - self.loc) / self.scale) / math.pi + 0.5\r\n\r\n def icdf(self, value):\r\n if self._validate_args:\r\n self._validate_sample(value)\r\n return torch.tan(math.pi * (value - 0.5)) * self.scale + self.loc\r\n\r\n def entropy(self):\r\n return math.log(4 * math.pi) + self.scale.log()\r\n", "import contextlib\r\nimport warnings\r\n\r\nfrom torch._C import default_generator\r\n\r\n\r\ndef set_rng_state(new_state):\r\n r\"\"\"Sets the random number generator state.\r\n\r\n Args:\r\n new_state (torch.ByteTensor): The desired state\r\n \"\"\"\r\n default_generator.set_state(new_state)\r\n\r\n\r\ndef get_rng_state():\r\n r\"\"\"Returns the random number generator state as a `torch.ByteTensor`.\"\"\"\r\n return default_generator.get_state()\r\n\r\n\r\ndef manual_seed(seed):\r\n r\"\"\"Sets the seed for generating random numbers. Returns a\r\n `torch.Generator` object.\r\n\r\n Args:\r\n seed (int): The desired seed.\r\n \"\"\"\r\n seed = int(seed)\r\n import torch.cuda\r\n\r\n if not torch.cuda._is_in_bad_fork():\r\n torch.cuda.manual_seed_all(seed)\r\n\r\n return default_generator.manual_seed(seed)\r\n\r\n\r\ndef seed():\r\n r\"\"\"Sets the seed for generating random numbers to a non-deterministic\r\n random number. Returns a 64 bit number used to seed the RNG.\r\n \"\"\"\r\n seed = default_generator.seed()\r\n import torch.cuda\r\n\r\n if not torch.cuda._is_in_bad_fork():\r\n torch.cuda.manual_seed_all(seed)\r\n\r\n return seed\r\n\r\n\r\ndef initial_seed():\r\n r\"\"\"Returns the initial seed for generating random numbers as a\r\n Python `long`.\r\n \"\"\"\r\n return default_generator.initial_seed()\r\n\r\n\r\n_fork_rng_warned_already = False\r\n\r\n\r\[email protected]\r\ndef fork_rng(devices=None, enabled=True, _caller=\"fork_rng\", _devices_kw=\"devices\"):\r\n \"\"\"\r\n Forks the RNG, so that when you return, the RNG is reset\r\n to the state that it was previously in.\r\n\r\n Arguments:\r\n devices (iterable of CUDA IDs): CUDA devices for which to fork\r\n the RNG. CPU RNG state is always forked. By default, :meth:`fork_rng` operates\r\n on all devices, but will emit a warning if your machine has a lot\r\n of devices, since this function will run very slowly in that case.\r\n If you explicitly specify devices, this warning will be suppressed\r\n enabled (bool): if ``False``, the RNG is not forked. This is a convenience\r\n argument for easily disabling the context manager without having\r\n to delete it and unindent your Python code under it.\r\n \"\"\"\r\n\r\n import torch.cuda\r\n global _fork_rng_warned_already\r\n\r\n # Internal arguments:\r\n # _caller: the function which called fork_rng, which the user used\r\n # _devices_kw: the devices keyword of _caller\r\n\r\n if not enabled:\r\n yield\r\n return\r\n\r\n if devices is None:\r\n num_devices = torch.cuda.device_count()\r\n if num_devices > 1 and not _fork_rng_warned_already:\r\n warnings.warn(\r\n (\"CUDA reports that you have {num_devices} available devices, and you \"\r\n \"have used {caller} without explicitly specifying which devices are being used. \"\r\n \"For safety, we initialize *every* CUDA device by default, which \"\r\n \"can be quite slow if you have a lot of GPUs. If you know that you are only \"\r\n \"making use of a few CUDA devices, set the environment variable CUDA_VISIBLE_DEVICES \"\r\n \"or the '{devices_kw}' keyword argument of {caller} with the set of devices \"\r\n \"you are actually using. For example, if you are using CPU only, \"\r\n \"set CUDA_VISIBLE_DEVICES= or devices=[]; if you are using \"\r\n \"GPU 0 only, set CUDA_VISIBLE_DEVICES=0 or devices=[0]. To initialize \"\r\n \"all devices and suppress this warning, set the '{devices_kw}' keyword argument \"\r\n \"to `range(torch.cuda.device_count())`.\"\r\n ).format(num_devices=num_devices, caller=_caller, devices_kw=_devices_kw))\r\n _fork_rng_warned_already = True\r\n devices = list(range(num_devices))\r\n else:\r\n # Protect against user passing us a generator; we need to traverse this\r\n # multiple times but a generator will be exhausted upon first traversal\r\n devices = list(devices)\r\n\r\n cpu_rng_state = torch.get_rng_state()\r\n gpu_rng_states = []\r\n for device in devices:\r\n gpu_rng_states.append(torch.cuda.get_rng_state(device))\r\n\r\n try:\r\n yield\r\n finally:\r\n torch.set_rng_state(cpu_rng_state)\r\n for device, gpu_rng_state in zip(devices, gpu_rng_states):\r\n torch.cuda.set_rng_state(gpu_rng_state, device)\r\n", "r\"\"\"\r\nWeight Normalization from https://arxiv.org/abs/1602.07868\r\n\"\"\"\r\nfrom torch.nn.parameter import Parameter\r\nfrom torch import _weight_norm, norm_except_dim\r\n\r\n\r\nclass WeightNorm(object):\r\n def __init__(self, name, dim):\r\n if dim is None:\r\n dim = -1\r\n self.name = name\r\n self.dim = dim\r\n\r\n def compute_weight(self, module):\r\n g = getattr(module, self.name + '_g')\r\n v = getattr(module, self.name + '_v')\r\n return _weight_norm(v, g, self.dim)\r\n\r\n @staticmethod\r\n def apply(module, name, dim):\r\n for k, hook in module._forward_pre_hooks.items():\r\n if isinstance(hook, WeightNorm) and hook.name == name:\r\n raise RuntimeError(\"Cannot register two weight_norm hooks on \"\r\n \"the same parameter {}\".format(name))\r\n\r\n if dim is None:\r\n dim = -1\r\n\r\n fn = WeightNorm(name, dim)\r\n\r\n weight = getattr(module, name)\r\n\r\n # remove w from parameter list\r\n del module._parameters[name]\r\n\r\n # add g and v as new parameters and express w as g/||v|| * v\r\n module.register_parameter(name + '_g', Parameter(norm_except_dim(weight, 2, dim).data))\r\n module.register_parameter(name + '_v', Parameter(weight.data))\r\n setattr(module, name, fn.compute_weight(module))\r\n\r\n # recompute weight before every forward()\r\n module.register_forward_pre_hook(fn)\r\n\r\n return fn\r\n\r\n def remove(self, module):\r\n weight = self.compute_weight(module)\r\n delattr(module, self.name)\r\n del module._parameters[self.name + '_g']\r\n del module._parameters[self.name + '_v']\r\n setattr(module, self.name, Parameter(weight.data))\r\n\r\n def __call__(self, module, inputs):\r\n setattr(module, self.name, self.compute_weight(module))\r\n\r\n\r\ndef weight_norm(module, name='weight', dim=0):\r\n r\"\"\"Applies weight normalization to a parameter in the given module.\r\n\r\n .. math::\r\n \\mathbf{w} = g \\dfrac{\\mathbf{v}}{\\|\\mathbf{v}\\|}\r\n\r\n Weight normalization is a reparameterization that decouples the magnitude\r\n of a weight tensor from its direction. This replaces the parameter specified\r\n by :attr:`name` (e.g. ``'weight'``) with two parameters: one specifying the magnitude\r\n (e.g. ``'weight_g'``) and one specifying the direction (e.g. ``'weight_v'``).\r\n Weight normalization is implemented via a hook that recomputes the weight\r\n tensor from the magnitude and direction before every :meth:`~Module.forward`\r\n call.\r\n\r\n By default, with ``dim=0``, the norm is computed independently per output\r\n channel/plane. To compute a norm over the entire weight tensor, use\r\n ``dim=None``.\r\n\r\n See https://arxiv.org/abs/1602.07868\r\n\r\n Args:\r\n module (Module): containing module\r\n name (str, optional): name of weight parameter\r\n dim (int, optional): dimension over which to compute the norm\r\n\r\n Returns:\r\n The original module with the weight norm hook\r\n\r\n Example::\r\n\r\n >>> m = weight_norm(nn.Linear(20, 40), name='weight')\r\n >>> m\r\n Linear(in_features=20, out_features=40, bias=True)\r\n >>> m.weight_g.size()\r\n torch.Size([40, 1])\r\n >>> m.weight_v.size()\r\n torch.Size([40, 20])\r\n\r\n \"\"\"\r\n WeightNorm.apply(module, name, dim)\r\n return module\r\n\r\n\r\ndef remove_weight_norm(module, name='weight'):\r\n r\"\"\"Removes the weight normalization reparameterization from a module.\r\n\r\n Args:\r\n module (Module): containing module\r\n name (str, optional): name of weight parameter\r\n\r\n Example:\r\n >>> m = weight_norm(nn.Linear(20, 40))\r\n >>> remove_weight_norm(m)\r\n \"\"\"\r\n for k, hook in module._forward_pre_hooks.items():\r\n if isinstance(hook, WeightNorm) and hook.name == name:\r\n hook.remove(module)\r\n del module._forward_pre_hooks[k]\r\n return module\r\n\r\n raise ValueError(\"weight_norm of '{}' not found in {}\"\r\n .format(name, module))\r\n", "import functools\r\nimport itertools\r\nimport logging\r\nimport math\r\nfrom numbers import Number\r\n\r\nimport numpy as np\r\nfrom numpy import ma\r\n\r\nimport matplotlib.category # Register category unit converter as side-effect.\r\nimport matplotlib.cbook as cbook\r\nimport matplotlib.collections as mcoll\r\nimport matplotlib.colors as mcolors\r\nimport matplotlib.contour as mcontour\r\nimport matplotlib.dates # Register date unit converter as side-effect.\r\nimport matplotlib.docstring as docstring\r\nimport matplotlib.image as mimage\r\nimport matplotlib.legend as mlegend\r\nimport matplotlib.lines as mlines\r\nimport matplotlib.markers as mmarkers\r\nimport matplotlib.mlab as mlab\r\nimport matplotlib.patches as mpatches\r\nimport matplotlib.path as mpath\r\nimport matplotlib.quiver as mquiver\r\nimport matplotlib.stackplot as mstack\r\nimport matplotlib.streamplot as mstream\r\nimport matplotlib.table as mtable\r\nimport matplotlib.text as mtext\r\nimport matplotlib.ticker as mticker\r\nimport matplotlib.transforms as mtransforms\r\nimport matplotlib.tri as mtri\r\nfrom matplotlib import _preprocess_data, rcParams\r\nfrom matplotlib.axes._base import _AxesBase, _process_plot_format\r\nfrom matplotlib.axes._secondary_axes import SecondaryAxis\r\nfrom matplotlib.container import BarContainer, ErrorbarContainer, StemContainer\r\n\r\n_log = logging.getLogger(__name__)\r\n\r\n\r\ndef _make_inset_locator(bounds, trans, parent):\r\n \"\"\"\r\n Helper function to locate inset axes, used in\r\n `.Axes.inset_axes`.\r\n\r\n A locator gets used in `Axes.set_aspect` to override the default\r\n locations... It is a function that takes an axes object and\r\n a renderer and tells `set_aspect` where it is to be placed.\r\n\r\n Here *rect* is a rectangle [l, b, w, h] that specifies the\r\n location for the axes in the transform given by *trans* on the\r\n *parent*.\r\n \"\"\"\r\n _bounds = mtransforms.Bbox.from_bounds(*bounds)\r\n _trans = trans\r\n _parent = parent\r\n\r\n def inset_locator(ax, renderer):\r\n bbox = _bounds\r\n bb = mtransforms.TransformedBbox(bbox, _trans)\r\n tr = _parent.figure.transFigure.inverted()\r\n bb = mtransforms.TransformedBbox(bb, tr)\r\n return bb\r\n\r\n return inset_locator\r\n\r\n\r\n# The axes module contains all the wrappers to plotting functions.\r\n# All the other methods should go in the _AxesBase class.\r\n\r\n\r\nclass Axes(_AxesBase):\r\n \"\"\"\r\n The `Axes` contains most of the figure elements: `~.axis.Axis`,\r\n `~.axis.Tick`, `~.lines.Line2D`, `~.text.Text`, `~.patches.Polygon`, etc.,\r\n and sets the coordinate system.\r\n\r\n The `Axes` instance supports callbacks through a callbacks attribute which\r\n is a `~.cbook.CallbackRegistry` instance. The events you can connect to\r\n are 'xlim_changed' and 'ylim_changed' and the callback will be called with\r\n func(*ax*) where *ax* is the `Axes` instance.\r\n\r\n Attributes\r\n ----------\r\n dataLim : `.Bbox`\r\n The bounding box enclosing all data displayed in the Axes.\r\n viewLim : `.Bbox`\r\n The view limits in data coordinates.\r\n\r\n \"\"\"\r\n ### Labelling, legend and texts\r\n\r\n def get_title(self, loc=\"center\"):\r\n \"\"\"\r\n Get an axes title.\r\n\r\n Get one of the three available axes titles. The available titles\r\n are positioned above the axes in the center, flush with the left\r\n edge, and flush with the right edge.\r\n\r\n Parameters\r\n ----------\r\n loc : {'center', 'left', 'right'}, str, default: 'center'\r\n Which title to return.\r\n\r\n Returns\r\n -------\r\n str\r\n The title text string.\r\n\r\n \"\"\"\r\n titles = {'left': self._left_title,\r\n 'center': self.title,\r\n 'right': self._right_title}\r\n title = cbook._check_getitem(titles, loc=loc.lower())\r\n return title.get_text()\r\n\r\n def set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None,\r\n **kwargs):\r\n \"\"\"\r\n Set a title for the axes.\r\n\r\n Set one of the three available axes titles. The available titles\r\n are positioned above the axes in the center, flush with the left\r\n edge, and flush with the right edge.\r\n\r\n Parameters\r\n ----------\r\n label : str\r\n Text to use for the title\r\n\r\n fontdict : dict\r\n A dictionary controlling the appearance of the title text,\r\n the default *fontdict* is::\r\n\r\n {'fontsize': rcParams['axes.titlesize'],\r\n 'fontweight': rcParams['axes.titleweight'],\r\n 'color': rcParams['axes.titlecolor'],\r\n 'verticalalignment': 'baseline',\r\n 'horizontalalignment': loc}\r\n\r\n loc : {'center', 'left', 'right'}, default: :rc:`axes.titlelocation`\r\n Which title to set.\r\n\r\n y : float, default: :rc:`axes.titley`\r\n Vertical axes loation for the title (1.0 is the top). If\r\n None (the default), y is determined automatically to avoid\r\n decorators on the axes.\r\n\r\n pad : float, default: :rc:`axes.titlepad`\r\n The offset of the title from the top of the axes, in points.\r\n\r\n Returns\r\n -------\r\n `.Text`\r\n The matplotlib text instance representing the title\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs : `.Text` properties\r\n Other keyword arguments are text properties, see `.Text` for a list\r\n of valid text properties.\r\n \"\"\"\r\n if loc is None:\r\n loc = rcParams['axes.titlelocation']\r\n\r\n if y is None:\r\n y = rcParams['axes.titley']\r\n if y is None:\r\n y = 1.0\r\n else:\r\n self._autotitlepos = False\r\n kwargs['y'] = y\r\n\r\n titles = {'left': self._left_title,\r\n 'center': self.title,\r\n 'right': self._right_title}\r\n title = cbook._check_getitem(titles, loc=loc.lower())\r\n default = {\r\n 'fontsize': rcParams['axes.titlesize'],\r\n 'fontweight': rcParams['axes.titleweight'],\r\n 'verticalalignment': 'baseline',\r\n 'horizontalalignment': loc.lower()}\r\n titlecolor = rcParams['axes.titlecolor']\r\n if not cbook._str_lower_equal(titlecolor, 'auto'):\r\n default[\"color\"] = titlecolor\r\n if pad is None:\r\n pad = rcParams['axes.titlepad']\r\n self._set_title_offset_trans(float(pad))\r\n title.set_text(label)\r\n title.update(default)\r\n if fontdict is not None:\r\n title.update(fontdict)\r\n title.update(kwargs)\r\n return title\r\n\r\n def get_xlabel(self):\r\n \"\"\"\r\n Get the xlabel text string.\r\n \"\"\"\r\n label = self.xaxis.get_label()\r\n return label.get_text()\r\n\r\n def set_xlabel(self, xlabel, fontdict=None, labelpad=None, *,\r\n loc=None, **kwargs):\r\n \"\"\"\r\n Set the label for the x-axis.\r\n\r\n Parameters\r\n ----------\r\n xlabel : str\r\n The label text.\r\n\r\n labelpad : float, default: None\r\n Spacing in points from the axes bounding box including ticks\r\n and tick labels.\r\n\r\n loc : {'left', 'center', 'right'}, default: :rc:`xaxis.labellocation`\r\n The label position. This is a high-level alternative for passing\r\n parameters *x* and *horizontalalignment*.\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs : `.Text` properties\r\n `.Text` properties control the appearance of the label.\r\n\r\n See Also\r\n --------\r\n text : Documents the properties supported by `.Text`.\r\n \"\"\"\r\n if labelpad is not None:\r\n self.xaxis.labelpad = labelpad\r\n protected_kw = ['x', 'horizontalalignment', 'ha']\r\n if {*kwargs} & {*protected_kw}:\r\n if loc is not None:\r\n raise TypeError(f\"Specifying 'loc' is disallowed when any of \"\r\n f\"its corresponding low level keyword \"\r\n f\"arguments ({protected_kw}) are also \"\r\n f\"supplied\")\r\n loc = 'center'\r\n else:\r\n loc = loc if loc is not None else rcParams['xaxis.labellocation']\r\n cbook._check_in_list(('left', 'center', 'right'), loc=loc)\r\n if loc == 'left':\r\n kwargs.update(x=0, horizontalalignment='left')\r\n elif loc == 'right':\r\n kwargs.update(x=1, horizontalalignment='right')\r\n return self.xaxis.set_label_text(xlabel, fontdict, **kwargs)\r\n\r\n def get_ylabel(self):\r\n \"\"\"\r\n Get the ylabel text string.\r\n \"\"\"\r\n label = self.yaxis.get_label()\r\n return label.get_text()\r\n\r\n def set_ylabel(self, ylabel, fontdict=None, labelpad=None, *,\r\n loc=None, **kwargs):\r\n \"\"\"\r\n Set the label for the y-axis.\r\n\r\n Parameters\r\n ----------\r\n ylabel : str\r\n The label text.\r\n\r\n labelpad : float, default: None\r\n Spacing in points from the axes bounding box including ticks\r\n and tick labels.\r\n\r\n loc : {'bottom', 'center', 'top'}, default: :rc:`yaxis.labellocation`\r\n The label position. This is a high-level alternative for passing\r\n parameters *y* and *horizontalalignment*.\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs : `.Text` properties\r\n `.Text` properties control the appearance of the label.\r\n\r\n See Also\r\n --------\r\n text : Documents the properties supported by `.Text`.\r\n \"\"\"\r\n if labelpad is not None:\r\n self.yaxis.labelpad = labelpad\r\n protected_kw = ['y', 'horizontalalignment', 'ha']\r\n if {*kwargs} & {*protected_kw}:\r\n if loc is not None:\r\n raise TypeError(f\"Specifying 'loc' is disallowed when any of \"\r\n f\"its corresponding low level keyword \"\r\n f\"arguments ({protected_kw}) are also \"\r\n f\"supplied\")\r\n loc = 'center'\r\n else:\r\n loc = loc if loc is not None else rcParams['yaxis.labellocation']\r\n cbook._check_in_list(('bottom', 'center', 'top'), loc=loc)\r\n if loc == 'bottom':\r\n kwargs.update(y=0, horizontalalignment='left')\r\n elif loc == 'top':\r\n kwargs.update(y=1, horizontalalignment='right')\r\n return self.yaxis.set_label_text(ylabel, fontdict, **kwargs)\r\n\r\n def get_legend_handles_labels(self, legend_handler_map=None):\r\n \"\"\"\r\n Return handles and labels for legend\r\n\r\n ``ax.legend()`` is equivalent to ::\r\n\r\n h, l = ax.get_legend_handles_labels()\r\n ax.legend(h, l)\r\n \"\"\"\r\n # pass through to legend.\r\n handles, labels = mlegend._get_legend_handles_labels(\r\n [self], legend_handler_map)\r\n return handles, labels\r\n\r\n @docstring.dedent_interpd\r\n def legend(self, *args, **kwargs):\r\n \"\"\"\r\n Place a legend on the axes.\r\n\r\n Call signatures::\r\n\r\n legend()\r\n legend(labels)\r\n legend(handles, labels)\r\n\r\n The call signatures correspond to three different ways how to use\r\n this method.\r\n\r\n **1. Automatic detection of elements to be shown in the legend**\r\n\r\n The elements to be added to the legend are automatically determined,\r\n when you do not pass in any extra arguments.\r\n\r\n In this case, the labels are taken from the artist. You can specify\r\n them either at artist creation or by calling the\r\n :meth:`~.Artist.set_label` method on the artist::\r\n\r\n line, = ax.plot([1, 2, 3], label='Inline label')\r\n ax.legend()\r\n\r\n or::\r\n\r\n line, = ax.plot([1, 2, 3])\r\n line.set_label('Label via method')\r\n ax.legend()\r\n\r\n Specific lines can be excluded from the automatic legend element\r\n selection by defining a label starting with an underscore.\r\n This is default for all artists, so calling `.Axes.legend` without\r\n any arguments and without setting the labels manually will result in\r\n no legend being drawn.\r\n\r\n\r\n **2. Labeling existing plot elements**\r\n\r\n To make a legend for lines which already exist on the axes\r\n (via plot for instance), simply call this function with an iterable\r\n of strings, one for each legend item. For example::\r\n\r\n ax.plot([1, 2, 3])\r\n ax.legend(['A simple line'])\r\n\r\n Note: This way of using is discouraged, because the relation between\r\n plot elements and labels is only implicit by their order and can\r\n easily be mixed up.\r\n\r\n\r\n **3. Explicitly defining the elements in the legend**\r\n\r\n For full control of which artists have a legend entry, it is possible\r\n to pass an iterable of legend artists followed by an iterable of\r\n legend labels respectively::\r\n\r\n legend((line1, line2, line3), ('label1', 'label2', 'label3'))\r\n\r\n Parameters\r\n ----------\r\n handles : sequence of `.Artist`, optional\r\n A list of Artists (lines, patches) to be added to the legend.\r\n Use this together with *labels*, if you need full control on what\r\n is shown in the legend and the automatic mechanism described above\r\n is not sufficient.\r\n\r\n The length of handles and labels should be the same in this\r\n case. If they are not, they are truncated to the smaller length.\r\n\r\n labels : list of str, optional\r\n A list of labels to show next to the artists.\r\n Use this together with *handles*, if you need full control on what\r\n is shown in the legend and the automatic mechanism described above\r\n is not sufficient.\r\n\r\n Returns\r\n -------\r\n `~matplotlib.legend.Legend`\r\n\r\n Other Parameters\r\n ----------------\r\n %(_legend_kw_doc)s\r\n\r\n Notes\r\n -----\r\n Some artists are not supported by this function. See\r\n :doc:`/tutorials/intermediate/legend_guide` for details.\r\n\r\n Examples\r\n --------\r\n .. plot:: gallery/text_labels_and_annotations/legend.py\r\n \"\"\"\r\n handles, labels, extra_args, kwargs = mlegend._parse_legend_args(\r\n [self],\r\n *args,\r\n **kwargs)\r\n if len(extra_args):\r\n raise TypeError('legend only accepts two non-keyword arguments')\r\n self.legend_ = mlegend.Legend(self, handles, labels, **kwargs)\r\n self.legend_._remove_method = self._remove_legend\r\n return self.legend_\r\n\r\n def _remove_legend(self, legend):\r\n self.legend_ = None\r\n\r\n def inset_axes(self, bounds, *, transform=None, zorder=5, **kwargs):\r\n \"\"\"\r\n Add a child inset axes to this existing axes.\r\n\r\n Warnings\r\n --------\r\n This method is experimental as of 3.0, and the API may change.\r\n\r\n Parameters\r\n ----------\r\n bounds : [x0, y0, width, height]\r\n Lower-left corner of inset axes, and its width and height.\r\n\r\n transform : `.Transform`\r\n Defaults to `ax.transAxes`, i.e. the units of *rect* are in\r\n axes-relative coordinates.\r\n\r\n zorder : number\r\n Defaults to 5 (same as `.Axes.legend`). Adjust higher or lower\r\n to change whether it is above or below data plotted on the\r\n parent axes.\r\n\r\n **kwargs\r\n Other keyword arguments are passed on to the child `.Axes`.\r\n\r\n Returns\r\n -------\r\n ax\r\n The created `~.axes.Axes` instance.\r\n\r\n Examples\r\n --------\r\n This example makes two inset axes, the first is in axes-relative\r\n coordinates, and the second in data-coordinates::\r\n\r\n fig, ax = plt.subplots()\r\n ax.plot(range(10))\r\n axin1 = ax.inset_axes([0.8, 0.1, 0.15, 0.15])\r\n axin2 = ax.inset_axes(\r\n [5, 7, 2.3, 2.3], transform=ax.transData)\r\n\r\n \"\"\"\r\n if transform is None:\r\n transform = self.transAxes\r\n kwargs.setdefault('label', 'inset_axes')\r\n\r\n # This puts the rectangle into figure-relative coordinates.\r\n inset_locator = _make_inset_locator(bounds, transform, self)\r\n bb = inset_locator(None, None)\r\n\r\n inset_ax = Axes(self.figure, bb.bounds, zorder=zorder, **kwargs)\r\n # this locator lets the axes move if in data coordinates.\r\n # it gets called in `ax.apply_aspect() (of all places)\r\n inset_ax.set_axes_locator(inset_locator)\r\n\r\n self.add_child_axes(inset_ax)\r\n\r\n return inset_ax\r\n\r\n def indicate_inset(self, bounds, inset_ax=None, *, transform=None,\r\n facecolor='none', edgecolor='0.5', alpha=0.5,\r\n zorder=4.99, **kwargs):\r\n \"\"\"\r\n Add an inset indicator to the axes. This is a rectangle on the plot\r\n at the position indicated by *bounds* that optionally has lines that\r\n connect the rectangle to an inset axes (`.Axes.inset_axes`).\r\n\r\n Warnings\r\n --------\r\n This method is experimental as of 3.0, and the API may change.\r\n\r\n Parameters\r\n ----------\r\n bounds : [x0, y0, width, height]\r\n Lower-left corner of rectangle to be marked, and its width\r\n and height.\r\n\r\n inset_ax : `.Axes`\r\n An optional inset axes to draw connecting lines to. Two lines are\r\n drawn connecting the indicator box to the inset axes on corners\r\n chosen so as to not overlap with the indicator box.\r\n\r\n transform : `.Transform`\r\n Transform for the rectangle coordinates. Defaults to\r\n `ax.transAxes`, i.e. the units of *rect* are in axes-relative\r\n coordinates.\r\n\r\n facecolor : color, default: 'none'\r\n Facecolor of the rectangle.\r\n\r\n edgecolor : color, default: '0.5'\r\n Color of the rectangle and color of the connecting lines.\r\n\r\n alpha : float, default: 0.5\r\n Transparency of the rectangle and connector lines.\r\n\r\n zorder : float, default: 4.99\r\n Drawing order of the rectangle and connector lines. The default,\r\n 4.99, is just below the default level of inset axes.\r\n\r\n **kwargs\r\n Other keyword arguments are passed on to the `.Rectangle` patch:\r\n\r\n %(Rectangle)s\r\n\r\n Returns\r\n -------\r\n rectangle_patch : `.patches.Rectangle`\r\n The indicator frame.\r\n\r\n connector_lines : 4-tuple of `.patches.ConnectionPatch`\r\n The four connector lines connecting to (lower_left, upper_left,\r\n lower_right upper_right) corners of *inset_ax*. Two lines are\r\n set with visibility to *False*, but the user can set the\r\n visibility to True if the automatic choice is not deemed correct.\r\n\r\n \"\"\"\r\n # to make the axes connectors work, we need to apply the aspect to\r\n # the parent axes.\r\n self.apply_aspect()\r\n\r\n if transform is None:\r\n transform = self.transData\r\n kwargs.setdefault('label', 'indicate_inset')\r\n\r\n x, y, width, height = bounds\r\n rectangle_patch = mpatches.Rectangle(\r\n (x, y), width, height,\r\n facecolor=facecolor, edgecolor=edgecolor, alpha=alpha,\r\n zorder=zorder, transform=transform, **kwargs)\r\n self.add_patch(rectangle_patch)\r\n\r\n connects = []\r\n\r\n if inset_ax is not None:\r\n # connect the inset_axes to the rectangle\r\n for xy_inset_ax in [(0, 0), (0, 1), (1, 0), (1, 1)]:\r\n # inset_ax positions are in axes coordinates\r\n # The 0, 1 values define the four edges if the inset_ax\r\n # lower_left, upper_left, lower_right upper_right.\r\n ex, ey = xy_inset_ax\r\n if self.xaxis.get_inverted():\r\n ex = 1 - ex\r\n if self.yaxis.get_inverted():\r\n ey = 1 - ey\r\n xy_data = x + ex * width, y + ey * height\r\n p = mpatches.ConnectionPatch(\r\n xyA=xy_inset_ax, coordsA=inset_ax.transAxes,\r\n xyB=xy_data, coordsB=self.transData,\r\n arrowstyle=\"-\", zorder=zorder,\r\n edgecolor=edgecolor, alpha=alpha)\r\n connects.append(p)\r\n self.add_patch(p)\r\n\r\n # decide which two of the lines to keep visible....\r\n pos = inset_ax.get_position()\r\n bboxins = pos.transformed(self.figure.transFigure)\r\n rectbbox = mtransforms.Bbox.from_bounds(\r\n *bounds\r\n ).transformed(transform)\r\n x0 = rectbbox.x0 < bboxins.x0\r\n x1 = rectbbox.x1 < bboxins.x1\r\n y0 = rectbbox.y0 < bboxins.y0\r\n y1 = rectbbox.y1 < bboxins.y1\r\n connects[0].set_visible(x0 ^ y0)\r\n connects[1].set_visible(x0 == y1)\r\n connects[2].set_visible(x1 == y0)\r\n connects[3].set_visible(x1 ^ y1)\r\n\r\n return rectangle_patch, tuple(connects) if connects else None\r\n\r\n def indicate_inset_zoom(self, inset_ax, **kwargs):\r\n \"\"\"\r\n Add an inset indicator rectangle to the axes based on the axis\r\n limits for an *inset_ax* and draw connectors between *inset_ax*\r\n and the rectangle.\r\n\r\n Warnings\r\n --------\r\n This method is experimental as of 3.0, and the API may change.\r\n\r\n Parameters\r\n ----------\r\n inset_ax : `.Axes`\r\n Inset axes to draw connecting lines to. Two lines are\r\n drawn connecting the indicator box to the inset axes on corners\r\n chosen so as to not overlap with the indicator box.\r\n\r\n **kwargs\r\n Other keyword arguments are passed on to `.Axes.indicate_inset`\r\n\r\n Returns\r\n -------\r\n rectangle_patch : `.patches.Rectangle`\r\n Rectangle artist.\r\n\r\n connector_lines : 4-tuple of `.patches.ConnectionPatch`\r\n Each of four connector lines coming from the rectangle drawn on\r\n this axis, in the order lower left, upper left, lower right,\r\n upper right.\r\n Two are set with visibility to *False*, but the user can\r\n set the visibility to *True* if the automatic choice is not deemed\r\n correct.\r\n \"\"\"\r\n\r\n xlim = inset_ax.get_xlim()\r\n ylim = inset_ax.get_ylim()\r\n rect = (xlim[0], ylim[0], xlim[1] - xlim[0], ylim[1] - ylim[0])\r\n return self.indicate_inset(rect, inset_ax, **kwargs)\r\n\r\n @docstring.dedent_interpd\r\n def secondary_xaxis(self, location, *, functions=None, **kwargs):\r\n \"\"\"\r\n Add a second x-axis to this axes.\r\n\r\n For example if we want to have a second scale for the data plotted on\r\n the xaxis.\r\n\r\n %(_secax_docstring)s\r\n\r\n Examples\r\n --------\r\n The main axis shows frequency, and the secondary axis shows period.\r\n\r\n .. plot::\r\n\r\n fig, ax = plt.subplots()\r\n ax.loglog(range(1, 360, 5), range(1, 360, 5))\r\n ax.set_xlabel('frequency [Hz]')\r\n\r\n def invert(x):\r\n return 1 / x\r\n\r\n secax = ax.secondary_xaxis('top', functions=(invert, invert))\r\n secax.set_xlabel('Period [s]')\r\n plt.show()\r\n \"\"\"\r\n if location in ['top', 'bottom'] or isinstance(location, Number):\r\n secondary_ax = SecondaryAxis(self, 'x', location, functions,\r\n **kwargs)\r\n self.add_child_axes(secondary_ax)\r\n return secondary_ax\r\n else:\r\n raise ValueError('secondary_xaxis location must be either '\r\n 'a float or \"top\"/\"bottom\"')\r\n\r\n @docstring.dedent_interpd\r\n def secondary_yaxis(self, location, *, functions=None, **kwargs):\r\n \"\"\"\r\n Add a second y-axis to this axes.\r\n\r\n For example if we want to have a second scale for the data plotted on\r\n the yaxis.\r\n\r\n %(_secax_docstring)s\r\n\r\n Examples\r\n --------\r\n Add a secondary axes that converts from radians to degrees\r\n\r\n .. plot::\r\n\r\n fig, ax = plt.subplots()\r\n ax.plot(range(1, 360, 5), range(1, 360, 5))\r\n ax.set_ylabel('degrees')\r\n secax = ax.secondary_yaxis('right', functions=(np.deg2rad,\r\n np.rad2deg))\r\n secax.set_ylabel('radians')\r\n \"\"\"\r\n if location in ['left', 'right'] or isinstance(location, Number):\r\n secondary_ax = SecondaryAxis(self, 'y', location,\r\n functions, **kwargs)\r\n self.add_child_axes(secondary_ax)\r\n return secondary_ax\r\n else:\r\n raise ValueError('secondary_yaxis location must be either '\r\n 'a float or \"left\"/\"right\"')\r\n\r\n @docstring.dedent_interpd\r\n def text(self, x, y, s, fontdict=None, **kwargs):\r\n \"\"\"\r\n Add text to the axes.\r\n\r\n Add the text *s* to the axes at location *x*, *y* in data coordinates.\r\n\r\n Parameters\r\n ----------\r\n x, y : float\r\n The position to place the text. By default, this is in data\r\n coordinates. The coordinate system can be changed using the\r\n *transform* parameter.\r\n\r\n s : str\r\n The text.\r\n\r\n fontdict : dict, default: None\r\n A dictionary to override the default text properties. If fontdict\r\n is None, the defaults are determined by `.rcParams`.\r\n\r\n Returns\r\n -------\r\n `.Text`\r\n The created `.Text` instance.\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs : `~matplotlib.text.Text` properties.\r\n Other miscellaneous text parameters.\r\n\r\n %(Text)s\r\n\r\n Examples\r\n --------\r\n Individual keyword arguments can be used to override any given\r\n parameter::\r\n\r\n >>> text(x, y, s, fontsize=12)\r\n\r\n The default transform specifies that text is in data coords,\r\n alternatively, you can specify text in axis coords ((0, 0) is\r\n lower-left and (1, 1) is upper-right). The example below places\r\n text in the center of the axes::\r\n\r\n >>> text(0.5, 0.5, 'matplotlib', horizontalalignment='center',\r\n ... verticalalignment='center', transform=ax.transAxes)\r\n\r\n You can put a rectangular box around the text instance (e.g., to\r\n set a background color) by using the keyword *bbox*. *bbox* is\r\n a dictionary of `~matplotlib.patches.Rectangle`\r\n properties. For example::\r\n\r\n >>> text(x, y, s, bbox=dict(facecolor='red', alpha=0.5))\r\n \"\"\"\r\n effective_kwargs = {\r\n 'verticalalignment': 'baseline',\r\n 'horizontalalignment': 'left',\r\n 'transform': self.transData,\r\n 'clip_on': False,\r\n **(fontdict if fontdict is not None else {}),\r\n **kwargs,\r\n }\r\n t = mtext.Text(x, y, text=s, **effective_kwargs)\r\n t.set_clip_path(self.patch)\r\n self._add_text(t)\r\n return t\r\n\r\n @cbook._rename_parameter(\"3.3\", \"s\", \"text\")\r\n @docstring.dedent_interpd\r\n def annotate(self, text, xy, *args, **kwargs):\r\n a = mtext.Annotation(text, xy, *args, **kwargs)\r\n a.set_transform(mtransforms.IdentityTransform())\r\n if 'clip_on' in kwargs:\r\n a.set_clip_path(self.patch)\r\n self._add_text(a)\r\n return a\r\n annotate.__doc__ = mtext.Annotation.__init__.__doc__\r\n #### Lines and spans\r\n\r\n @docstring.dedent_interpd\r\n def axhline(self, y=0, xmin=0, xmax=1, **kwargs):\r\n \"\"\"\r\n Add a horizontal line across the axis.\r\n\r\n Parameters\r\n ----------\r\n y : float, default: 0\r\n y position in data coordinates of the horizontal line.\r\n\r\n xmin : float, default: 0\r\n Should be between 0 and 1, 0 being the far left of the plot, 1 the\r\n far right of the plot.\r\n\r\n xmax : float, default: 1\r\n Should be between 0 and 1, 0 being the far left of the plot, 1 the\r\n far right of the plot.\r\n\r\n Returns\r\n -------\r\n `~matplotlib.lines.Line2D`\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs\r\n Valid keyword arguments are `.Line2D` properties, with the\r\n exception of 'transform':\r\n\r\n %(_Line2D_docstr)s\r\n\r\n See Also\r\n --------\r\n hlines : Add horizontal lines in data coordinates.\r\n axhspan : Add a horizontal span (rectangle) across the axis.\r\n axline : Add a line with an arbitrary slope.\r\n\r\n Examples\r\n --------\r\n * draw a thick red hline at 'y' = 0 that spans the xrange::\r\n\r\n >>> axhline(linewidth=4, color='r')\r\n\r\n * draw a default hline at 'y' = 1 that spans the xrange::\r\n\r\n >>> axhline(y=1)\r\n\r\n * draw a default hline at 'y' = .5 that spans the middle half of\r\n the xrange::\r\n\r\n >>> axhline(y=.5, xmin=0.25, xmax=0.75)\r\n \"\"\"\r\n if \"transform\" in kwargs:\r\n raise ValueError(\r\n \"'transform' is not allowed as a kwarg;\"\r\n + \"axhline generates its own transform.\")\r\n ymin, ymax = self.get_ybound()\r\n\r\n # We need to strip away the units for comparison with\r\n # non-unitized bounds\r\n self._process_unit_info(ydata=y, kwargs=kwargs)\r\n yy = self.convert_yunits(y)\r\n scaley = (yy < ymin) or (yy > ymax)\r\n\r\n trans = self.get_yaxis_transform(which='grid')\r\n l = mlines.Line2D([xmin, xmax], [y, y], transform=trans, **kwargs)\r\n self.add_line(l)\r\n self._request_autoscale_view(scalex=False, scaley=scaley)\r\n return l\r\n\r\n @docstring.dedent_interpd\r\n def axvline(self, x=0, ymin=0, ymax=1, **kwargs):\r\n \"\"\"\r\n Add a vertical line across the axes.\r\n\r\n Parameters\r\n ----------\r\n x : float, default: 0\r\n x position in data coordinates of the vertical line.\r\n\r\n ymin : float, default: 0\r\n Should be between 0 and 1, 0 being the bottom of the plot, 1 the\r\n top of the plot.\r\n\r\n ymax : float, default: 1\r\n Should be between 0 and 1, 0 being the bottom of the plot, 1 the\r\n top of the plot.\r\n\r\n Returns\r\n -------\r\n `~matplotlib.lines.Line2D`\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs\r\n Valid keyword arguments are `.Line2D` properties, with the\r\n exception of 'transform':\r\n\r\n %(_Line2D_docstr)s\r\n\r\n See Also\r\n --------\r\n vlines : Add vertical lines in data coordinates.\r\n axvspan : Add a vertical span (rectangle) across the axis.\r\n axline : Add a line with an arbitrary slope.\r\n\r\n Examples\r\n --------\r\n * draw a thick red vline at *x* = 0 that spans the yrange::\r\n\r\n >>> axvline(linewidth=4, color='r')\r\n\r\n * draw a default vline at *x* = 1 that spans the yrange::\r\n\r\n >>> axvline(x=1)\r\n\r\n * draw a default vline at *x* = .5 that spans the middle half of\r\n the yrange::\r\n\r\n >>> axvline(x=.5, ymin=0.25, ymax=0.75)\r\n \"\"\"\r\n\r\n if \"transform\" in kwargs:\r\n raise ValueError(\r\n \"'transform' is not allowed as a kwarg;\"\r\n + \"axvline generates its own transform.\")\r\n xmin, xmax = self.get_xbound()\r\n\r\n # We need to strip away the units for comparison with\r\n # non-unitized bounds\r\n self._process_unit_info(xdata=x, kwargs=kwargs)\r\n xx = self.convert_xunits(x)\r\n scalex = (xx < xmin) or (xx > xmax)\r\n\r\n trans = self.get_xaxis_transform(which='grid')\r\n l = mlines.Line2D([x, x], [ymin, ymax], transform=trans, **kwargs)\r\n self.add_line(l)\r\n self._request_autoscale_view(scalex=scalex, scaley=False)\r\n return l\r\n\r\n @docstring.dedent_interpd\r\n def axline(self, xy1, xy2=None, *, slope=None, **kwargs):\r\n \"\"\"\r\n Add an infinitely long straight line.\r\n\r\n The line can be defined either by two points *xy1* and *xy2*, or\r\n by one point *xy1* and a *slope*.\r\n\r\n This draws a straight line \"on the screen\", regardless of the x and y\r\n scales, and is thus also suitable for drawing exponential decays in\r\n semilog plots, power laws in loglog plots, etc. However, *slope*\r\n should only be used with linear scales; It has no clear meaning for\r\n all other scales, and thus the behavior is undefined. Please specify\r\n the line using the points *xy1*, *xy2* for non-linear scales.\r\n\r\n Parameters\r\n ----------\r\n xy1, xy2 : (float, float)\r\n Points for the line to pass through.\r\n Either *xy2* or *slope* has to be given.\r\n slope : float, optional\r\n The slope of the line. Either *xy2* or *slope* has to be given.\r\n\r\n Returns\r\n -------\r\n `.Line2D`\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs\r\n Valid kwargs are `.Line2D` properties, with the exception of\r\n 'transform':\r\n\r\n %(_Line2D_docstr)s\r\n\r\n See Also\r\n --------\r\n axhline : for horizontal lines\r\n axvline : for vertical lines\r\n\r\n Examples\r\n --------\r\n Draw a thick red line passing through (0, 0) and (1, 1)::\r\n\r\n >>> axline((0, 0), (1, 1), linewidth=4, color='r')\r\n \"\"\"\r\n def _to_points(xy1, xy2, slope):\r\n \"\"\"\r\n Check for a valid combination of input parameters and convert\r\n to two points, if necessary.\r\n \"\"\"\r\n if (xy2 is None and slope is None or\r\n xy2 is not None and slope is not None):\r\n raise TypeError(\r\n \"Exactly one of 'xy2' and 'slope' must be given\")\r\n if xy2 is None:\r\n x1, y1 = xy1\r\n xy2 = (x1, y1 + 1) if np.isinf(slope) else (x1 + 1, y1 + slope)\r\n return xy1, xy2\r\n\r\n if \"transform\" in kwargs:\r\n raise TypeError(\"'transform' is not allowed as a kwarg; \"\r\n \"axline generates its own transform\")\r\n if slope is not None and (self.get_xscale() != 'linear' or\r\n self.get_yscale() != 'linear'):\r\n raise TypeError(\"'slope' cannot be used with non-linear scales\")\r\n\r\n datalim = [xy1] if xy2 is None else [xy1, xy2]\r\n (x1, y1), (x2, y2) = _to_points(xy1, xy2, slope)\r\n line = mlines._AxLine([x1, x2], [y1, y2], **kwargs)\r\n # Like add_line, but correctly handling data limits.\r\n self._set_artist_props(line)\r\n if line.get_clip_path() is None:\r\n line.set_clip_path(self.patch)\r\n if not line.get_label():\r\n line.set_label(f\"_line{len(self.lines)}\")\r\n self.lines.append(line)\r\n line._remove_method = self.lines.remove\r\n self.update_datalim(datalim)\r\n\r\n self._request_autoscale_view()\r\n return line\r\n\r\n @docstring.dedent_interpd\r\n def axhspan(self, ymin, ymax, xmin=0, xmax=1, **kwargs):\r\n \"\"\"\r\n Add a horizontal span (rectangle) across the axis.\r\n\r\n The rectangle spans from *ymin* to *ymax* vertically, and, by default,\r\n the whole x-axis horizontally. The x-span can be set using *xmin*\r\n (default: 0) and *xmax* (default: 1) which are in axis units; e.g.\r\n ``xmin = 0.5`` always refers to the middle of the x-axis regardless of\r\n the limits set by `~.Axes.set_xlim`.\r\n\r\n Parameters\r\n ----------\r\n ymin : float\r\n Lower y-coordinate of the span, in data units.\r\n ymax : float\r\n Upper y-coordinate of the span, in data units.\r\n xmin : float, default: 0\r\n Lower x-coordinate of the span, in x-axis (0-1) units.\r\n xmax : float, default: 1\r\n Upper x-coordinate of the span, in x-axis (0-1) units.\r\n\r\n Returns\r\n -------\r\n `~matplotlib.patches.Polygon`\r\n Horizontal span (rectangle) from (xmin, ymin) to (xmax, ymax).\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs : `~matplotlib.patches.Polygon` properties\r\n\r\n %(Polygon)s\r\n\r\n See Also\r\n --------\r\n axvspan : Add a vertical span across the axes.\r\n \"\"\"\r\n trans = self.get_yaxis_transform(which='grid')\r\n\r\n # process the unit information\r\n self._process_unit_info([xmin, xmax], [ymin, ymax], kwargs=kwargs)\r\n\r\n # first we need to strip away the units\r\n xmin, xmax = self.convert_xunits([xmin, xmax])\r\n ymin, ymax = self.convert_yunits([ymin, ymax])\r\n\r\n verts = (xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)\r\n p = mpatches.Polygon(verts, **kwargs)\r\n p.set_transform(trans)\r\n self.add_patch(p)\r\n self._request_autoscale_view(scalex=False)\r\n return p\r\n\r\n def axvspan(self, xmin, xmax, ymin=0, ymax=1, **kwargs):\r\n \"\"\"\r\n Add a vertical span (rectangle) across the axes.\r\n\r\n The rectangle spans from *xmin* to *xmax* horizontally, and, by\r\n default, the whole y-axis vertically. The y-span can be set using\r\n *ymin* (default: 0) and *ymax* (default: 1) which are in axis units;\r\n e.g. ``ymin = 0.5`` always refers to the middle of the y-axis\r\n regardless of the limits set by `~.Axes.set_ylim`.\r\n\r\n Parameters\r\n ----------\r\n xmin : float\r\n Lower x-coordinate of the span, in data units.\r\n xmax : float\r\n Upper x-coordinate of the span, in data units.\r\n ymin : float, default: 0\r\n Lower y-coordinate of the span, in y-axis units (0-1).\r\n ymax : float, default: 1\r\n Upper y-coordinate of the span, in y-axis units (0-1).\r\n\r\n Returns\r\n -------\r\n `~matplotlib.patches.Polygon`\r\n Vertical span (rectangle) from (xmin, ymin) to (xmax, ymax).\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs : `~matplotlib.patches.Polygon` properties\r\n\r\n %(Polygon)s\r\n\r\n See Also\r\n --------\r\n axhspan : Add a horizontal span across the axes.\r\n\r\n Examples\r\n --------\r\n Draw a vertical, green, translucent rectangle from x = 1.25 to\r\n x = 1.55 that spans the yrange of the axes.\r\n\r\n >>> axvspan(1.25, 1.55, facecolor='g', alpha=0.5)\r\n\r\n \"\"\"\r\n trans = self.get_xaxis_transform(which='grid')\r\n\r\n # process the unit information\r\n self._process_unit_info([xmin, xmax], [ymin, ymax], kwargs=kwargs)\r\n\r\n # first we need to strip away the units\r\n xmin, xmax = self.convert_xunits([xmin, xmax])\r\n ymin, ymax = self.convert_yunits([ymin, ymax])\r\n\r\n verts = [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)]\r\n p = mpatches.Polygon(verts, **kwargs)\r\n p.set_transform(trans)\r\n self.add_patch(p)\r\n self._request_autoscale_view(scaley=False)\r\n return p\r\n\r\n @_preprocess_data(replace_names=[\"y\", \"xmin\", \"xmax\", \"colors\"],\r\n label_namer=\"y\")\r\n def hlines(self, y, xmin, xmax, colors=None, linestyles='solid',\r\n label='', **kwargs):\r\n \"\"\"\r\n Plot horizontal lines at each *y* from *xmin* to *xmax*.\r\n\r\n Parameters\r\n ----------\r\n y : float or array-like\r\n y-indexes where to plot the lines.\r\n\r\n xmin, xmax : float or array-like\r\n Respective beginning and end of each line. If scalars are\r\n provided, all lines will have same length.\r\n\r\n colors : list of colors, default: :rc:`lines.color`\r\n\r\n linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, optional\r\n\r\n label : str, default: ''\r\n\r\n Returns\r\n -------\r\n `~matplotlib.collections.LineCollection`\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs : `~matplotlib.collections.LineCollection` properties.\r\n\r\n See Also\r\n --------\r\n vlines : vertical lines\r\n axhline: horizontal line across the axes\r\n \"\"\"\r\n\r\n # We do the conversion first since not all unitized data is uniform\r\n # process the unit information\r\n self._process_unit_info([xmin, xmax], y, kwargs=kwargs)\r\n y = self.convert_yunits(y)\r\n xmin = self.convert_xunits(xmin)\r\n xmax = self.convert_xunits(xmax)\r\n\r\n if not np.iterable(y):\r\n y = [y]\r\n if not np.iterable(xmin):\r\n xmin = [xmin]\r\n if not np.iterable(xmax):\r\n xmax = [xmax]\r\n\r\n # Create and combine masked_arrays from input\r\n y, xmin, xmax = cbook._combine_masks(y, xmin, xmax)\r\n y = np.ravel(y)\r\n xmin = np.ravel(xmin)\r\n xmax = np.ravel(xmax)\r\n\r\n masked_verts = np.ma.empty((len(y), 2, 2))\r\n masked_verts[:, 0, 0] = xmin\r\n masked_verts[:, 0, 1] = y\r\n masked_verts[:, 1, 0] = xmax\r\n masked_verts[:, 1, 1] = y\r\n\r\n lines = mcoll.LineCollection(masked_verts, colors=colors,\r\n linestyles=linestyles, label=label)\r\n self.add_collection(lines, autolim=False)\r\n lines.update(kwargs)\r\n\r\n if len(y) > 0:\r\n minx = min(xmin.min(), xmax.min())\r\n maxx = max(xmin.max(), xmax.max())\r\n miny = y.min()\r\n maxy = y.max()\r\n\r\n corners = (minx, miny), (maxx, maxy)\r\n\r\n self.update_datalim(corners)\r\n self._request_autoscale_view()\r\n\r\n return lines\r\n\r\n @_preprocess_data(replace_names=[\"x\", \"ymin\", \"ymax\", \"colors\"],\r\n label_namer=\"x\")\r\n def vlines(self, x, ymin, ymax, colors=None, linestyles='solid',\r\n label='', **kwargs):\r\n \"\"\"\r\n Plot vertical lines.\r\n\r\n Plot vertical lines at each *x* from *ymin* to *ymax*.\r\n\r\n Parameters\r\n ----------\r\n x : float or array-like\r\n x-indexes where to plot the lines.\r\n\r\n ymin, ymax : float or array-like\r\n Respective beginning and end of each line. If scalars are\r\n provided, all lines will have same length.\r\n\r\n colors : list of colors, default: :rc:`lines.color`\r\n\r\n linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, optional\r\n\r\n label : str, default: ''\r\n\r\n Returns\r\n -------\r\n `~matplotlib.collections.LineCollection`\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs : `~matplotlib.collections.LineCollection` properties.\r\n\r\n See Also\r\n --------\r\n hlines : horizontal lines\r\n axvline: vertical line across the axes\r\n \"\"\"\r\n\r\n self._process_unit_info(xdata=x, ydata=[ymin, ymax], kwargs=kwargs)\r\n\r\n # We do the conversion first since not all unitized data is uniform\r\n x = self.convert_xunits(x)\r\n ymin = self.convert_yunits(ymin)\r\n ymax = self.convert_yunits(ymax)\r\n\r\n if not np.iterable(x):\r\n x = [x]\r\n if not np.iterable(ymin):\r\n ymin = [ymin]\r\n if not np.iterable(ymax):\r\n ymax = [ymax]\r\n\r\n # Create and combine masked_arrays from input\r\n x, ymin, ymax = cbook._combine_masks(x, ymin, ymax)\r\n x = np.ravel(x)\r\n ymin = np.ravel(ymin)\r\n ymax = np.ravel(ymax)\r\n\r\n masked_verts = np.ma.empty((len(x), 2, 2))\r\n masked_verts[:, 0, 0] = x\r\n masked_verts[:, 0, 1] = ymin\r\n masked_verts[:, 1, 0] = x\r\n masked_verts[:, 1, 1] = ymax\r\n\r\n lines = mcoll.LineCollection(masked_verts, colors=colors,\r\n linestyles=linestyles, label=label)\r\n self.add_collection(lines, autolim=False)\r\n lines.update(kwargs)\r\n\r\n if len(x) > 0:\r\n minx = x.min()\r\n maxx = x.max()\r\n miny = min(ymin.min(), ymax.min())\r\n maxy = max(ymin.max(), ymax.max())\r\n\r\n corners = (minx, miny), (maxx, maxy)\r\n self.update_datalim(corners)\r\n self._request_autoscale_view()\r\n\r\n return lines\r\n\r\n @_preprocess_data(replace_names=[\"positions\", \"lineoffsets\",\r\n \"linelengths\", \"linewidths\",\r\n \"colors\", \"linestyles\"])\r\n @docstring.dedent_interpd\r\n def eventplot(self, positions, orientation='horizontal', lineoffsets=1,\r\n linelengths=1, linewidths=None, colors=None,\r\n linestyles='solid', **kwargs):\r\n \"\"\"\r\n Plot identical parallel lines at the given positions.\r\n\r\n This type of plot is commonly used in neuroscience for representing\r\n neural events, where it is usually called a spike raster, dot raster,\r\n or raster plot.\r\n\r\n However, it is useful in any situation where you wish to show the\r\n timing or position of multiple sets of discrete events, such as the\r\n arrival times of people to a business on each day of the month or the\r\n date of hurricanes each year of the last century.\r\n\r\n Parameters\r\n ----------\r\n positions : array-like or list of array-like\r\n A 1D array-like defines the positions of one sequence of events.\r\n\r\n Multiple groups of events may be passed as a list of array-likes.\r\n Each group can be styled independently by passing lists of values\r\n to *lineoffsets*, *linelengths*, *linewidths*, *colors* and\r\n *linestyles*.\r\n\r\n Note that *positions* can be a 2D array, but in practice different\r\n event groups usually have different counts so that one will use a\r\n list of different-length arrays rather than a 2D array.\r\n\r\n orientation : {'horizontal', 'vertical'}, default: 'horizontal'\r\n The direction of the event sequence:\r\n\r\n - 'horizontal': the events are arranged horizontally.\r\n The indicator lines are vertical.\r\n - 'vertical': the events are arranged vertically.\r\n The indicator lines are horizontal.\r\n\r\n lineoffsets : float or array-like, default: 1\r\n The offset of the center of the lines from the origin, in the\r\n direction orthogonal to *orientation*.\r\n\r\n If *positions* is 2D, this can be a sequence with length matching\r\n the length of *positions*.\r\n\r\n linelengths : float or array-like, default: 1\r\n The total height of the lines (i.e. the lines stretches from\r\n ``lineoffset - linelength/2`` to ``lineoffset + linelength/2``).\r\n\r\n If *positions* is 2D, this can be a sequence with length matching\r\n the length of *positions*.\r\n\r\n linewidths : float or array-like, default: :rc:`lines.linewidth`\r\n The line width(s) of the event lines, in points.\r\n\r\n If *positions* is 2D, this can be a sequence with length matching\r\n the length of *positions*.\r\n\r\n colors : color or list of colors, default: :rc:`lines.color`\r\n The color(s) of the event lines.\r\n\r\n If *positions* is 2D, this can be a sequence with length matching\r\n the length of *positions*.\r\n\r\n linestyles : str or tuple or list of such values, default: 'solid'\r\n Default is 'solid'. Valid strings are ['solid', 'dashed',\r\n 'dashdot', 'dotted', '-', '--', '-.', ':']. Dash tuples\r\n should be of the form::\r\n\r\n (offset, onoffseq),\r\n\r\n where *onoffseq* is an even length tuple of on and off ink\r\n in points.\r\n\r\n If *positions* is 2D, this can be a sequence with length matching\r\n the length of *positions*.\r\n\r\n **kwargs\r\n Other keyword arguments are line collection properties. See\r\n `.LineCollection` for a list of the valid properties.\r\n\r\n Returns\r\n -------\r\n list of `.EventCollection`\r\n The `.EventCollection` that were added.\r\n\r\n Notes\r\n -----\r\n For *linelengths*, *linewidths*, *colors*, and *linestyles*, if only\r\n a single value is given, that value is applied to all lines. If an\r\n array-like is given, it must have the same length as *positions*, and\r\n each value will be applied to the corresponding row of the array.\r\n\r\n Examples\r\n --------\r\n .. plot:: gallery/lines_bars_and_markers/eventplot_demo.py\r\n \"\"\"\r\n self._process_unit_info(xdata=positions,\r\n ydata=[lineoffsets, linelengths],\r\n kwargs=kwargs)\r\n\r\n # We do the conversion first since not all unitized data is uniform\r\n positions = self.convert_xunits(positions)\r\n lineoffsets = self.convert_yunits(lineoffsets)\r\n linelengths = self.convert_yunits(linelengths)\r\n\r\n if not np.iterable(positions):\r\n positions = [positions]\r\n elif any(np.iterable(position) for position in positions):\r\n positions = [np.asanyarray(position) for position in positions]\r\n else:\r\n positions = [np.asanyarray(positions)]\r\n\r\n if len(positions) == 0:\r\n return []\r\n\r\n # prevent 'singular' keys from **kwargs dict from overriding the effect\r\n # of 'plural' keyword arguments (e.g. 'color' overriding 'colors')\r\n colors = cbook._local_over_kwdict(colors, kwargs, 'color')\r\n linewidths = cbook._local_over_kwdict(linewidths, kwargs, 'linewidth')\r\n linestyles = cbook._local_over_kwdict(linestyles, kwargs, 'linestyle')\r\n\r\n if not np.iterable(lineoffsets):\r\n lineoffsets = [lineoffsets]\r\n if not np.iterable(linelengths):\r\n linelengths = [linelengths]\r\n if not np.iterable(linewidths):\r\n linewidths = [linewidths]\r\n if not np.iterable(colors):\r\n colors = [colors]\r\n if hasattr(linestyles, 'lower') or not np.iterable(linestyles):\r\n linestyles = [linestyles]\r\n\r\n lineoffsets = np.asarray(lineoffsets)\r\n linelengths = np.asarray(linelengths)\r\n linewidths = np.asarray(linewidths)\r\n\r\n if len(lineoffsets) == 0:\r\n lineoffsets = [None]\r\n if len(linelengths) == 0:\r\n linelengths = [None]\r\n if len(linewidths) == 0:\r\n lineoffsets = [None]\r\n if len(linewidths) == 0:\r\n lineoffsets = [None]\r\n if len(colors) == 0:\r\n colors = [None]\r\n try:\r\n # Early conversion of the colors into RGBA values to take care\r\n # of cases like colors='0.5' or colors='C1'. (Issue #8193)\r\n colors = mcolors.to_rgba_array(colors)\r\n except ValueError:\r\n # Will fail if any element of *colors* is None. But as long\r\n # as len(colors) == 1 or len(positions), the rest of the\r\n # code should process *colors* properly.\r\n pass\r\n\r\n if len(lineoffsets) == 1 and len(positions) != 1:\r\n lineoffsets = np.tile(lineoffsets, len(positions))\r\n lineoffsets[0] = 0\r\n lineoffsets = np.cumsum(lineoffsets)\r\n if len(linelengths) == 1:\r\n linelengths = np.tile(linelengths, len(positions))\r\n if len(linewidths) == 1:\r\n linewidths = np.tile(linewidths, len(positions))\r\n if len(colors) == 1:\r\n colors = list(colors)\r\n colors = colors * len(positions)\r\n if len(linestyles) == 1:\r\n linestyles = [linestyles] * len(positions)\r\n\r\n if len(lineoffsets) != len(positions):\r\n raise ValueError('lineoffsets and positions are unequal sized '\r\n 'sequences')\r\n if len(linelengths) != len(positions):\r\n raise ValueError('linelengths and positions are unequal sized '\r\n 'sequences')\r\n if len(linewidths) != len(positions):\r\n raise ValueError('linewidths and positions are unequal sized '\r\n 'sequences')\r\n if len(colors) != len(positions):\r\n raise ValueError('colors and positions are unequal sized '\r\n 'sequences')\r\n if len(linestyles) != len(positions):\r\n raise ValueError('linestyles and positions are unequal sized '\r\n 'sequences')\r\n\r\n colls = []\r\n for position, lineoffset, linelength, linewidth, color, linestyle in \\\r\n zip(positions, lineoffsets, linelengths, linewidths,\r\n colors, linestyles):\r\n coll = mcoll.EventCollection(position,\r\n orientation=orientation,\r\n lineoffset=lineoffset,\r\n linelength=linelength,\r\n linewidth=linewidth,\r\n color=color,\r\n linestyle=linestyle)\r\n self.add_collection(coll, autolim=False)\r\n coll.update(kwargs)\r\n colls.append(coll)\r\n\r\n if len(positions) > 0:\r\n # try to get min/max\r\n min_max = [(np.min(_p), np.max(_p)) for _p in positions\r\n if len(_p) > 0]\r\n # if we have any non-empty positions, try to autoscale\r\n if len(min_max) > 0:\r\n mins, maxes = zip(*min_max)\r\n minpos = np.min(mins)\r\n maxpos = np.max(maxes)\r\n\r\n minline = (lineoffsets - linelengths).min()\r\n maxline = (lineoffsets + linelengths).max()\r\n\r\n if (orientation is not None and\r\n orientation.lower() == \"vertical\"):\r\n corners = (minline, minpos), (maxline, maxpos)\r\n else: # \"horizontal\", None or \"none\" (see EventCollection)\r\n corners = (minpos, minline), (maxpos, maxline)\r\n self.update_datalim(corners)\r\n self._request_autoscale_view()\r\n\r\n return colls\r\n\r\n #### Basic plotting\r\n\r\n # Uses a custom implementation of data-kwarg handling in\r\n # _process_plot_var_args.\r\n @docstring.dedent_interpd\r\n def plot(self, *args, scalex=True, scaley=True, data=None, **kwargs):\r\n \"\"\"\r\n Plot y versus x as lines and/or markers.\r\n\r\n Call signatures::\r\n\r\n plot([x], y, [fmt], *, data=None, **kwargs)\r\n plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)\r\n\r\n The coordinates of the points or line nodes are given by *x*, *y*.\r\n\r\n The optional parameter *fmt* is a convenient way for defining basic\r\n formatting like color, marker and linestyle. It's a shortcut string\r\n notation described in the *Notes* section below.\r\n\r\n >>> plot(x, y) # plot x and y using default line style and color\r\n >>> plot(x, y, 'bo') # plot x and y using blue circle markers\r\n >>> plot(y) # plot y using x as index array 0..N-1\r\n >>> plot(y, 'r+') # ditto, but with red plusses\r\n\r\n You can use `.Line2D` properties as keyword arguments for more\r\n control on the appearance. Line properties and *fmt* can be mixed.\r\n The following two calls yield identical results:\r\n\r\n >>> plot(x, y, 'go--', linewidth=2, markersize=12)\r\n >>> plot(x, y, color='green', marker='o', linestyle='dashed',\r\n ... linewidth=2, markersize=12)\r\n\r\n When conflicting with *fmt*, keyword arguments take precedence.\r\n\r\n\r\n **Plotting labelled data**\r\n\r\n There's a convenient way for plotting objects with labelled data (i.e.\r\n data that can be accessed by index ``obj['y']``). Instead of giving\r\n the data in *x* and *y*, you can provide the object in the *data*\r\n parameter and just give the labels for *x* and *y*::\r\n\r\n >>> plot('xlabel', 'ylabel', data=obj)\r\n\r\n All indexable objects are supported. This could e.g. be a `dict`, a\r\n `pandas.DataFrame` or a structured numpy array.\r\n\r\n\r\n **Plotting multiple sets of data**\r\n\r\n There are various ways to plot multiple sets of data.\r\n\r\n - The most straight forward way is just to call `plot` multiple times.\r\n Example:\r\n\r\n >>> plot(x1, y1, 'bo')\r\n >>> plot(x2, y2, 'go')\r\n\r\n - Alternatively, if your data is already a 2d array, you can pass it\r\n directly to *x*, *y*. A separate data set will be drawn for every\r\n column.\r\n\r\n Example: an array ``a`` where the first column represents the *x*\r\n values and the other columns are the *y* columns::\r\n\r\n >>> plot(a[0], a[1:])\r\n\r\n - The third way is to specify multiple sets of *[x]*, *y*, *[fmt]*\r\n groups::\r\n\r\n >>> plot(x1, y1, 'g^', x2, y2, 'g-')\r\n\r\n In this case, any additional keyword argument applies to all\r\n datasets. Also this syntax cannot be combined with the *data*\r\n parameter.\r\n\r\n By default, each line is assigned a different style specified by a\r\n 'style cycle'. The *fmt* and line property parameters are only\r\n necessary if you want explicit deviations from these defaults.\r\n Alternatively, you can also change the style cycle using\r\n :rc:`axes.prop_cycle`.\r\n\r\n\r\n Parameters\r\n ----------\r\n x, y : array-like or scalar\r\n The horizontal / vertical coordinates of the data points.\r\n *x* values are optional and default to ``range(len(y))``.\r\n\r\n Commonly, these parameters are 1D arrays.\r\n\r\n They can also be scalars, or two-dimensional (in that case, the\r\n columns represent separate data sets).\r\n\r\n These arguments cannot be passed as keywords.\r\n\r\n fmt : str, optional\r\n A format string, e.g. 'ro' for red circles. See the *Notes*\r\n section for a full description of the format strings.\r\n\r\n Format strings are just an abbreviation for quickly setting\r\n basic line properties. All of these and more can also be\r\n controlled by keyword arguments.\r\n\r\n This argument cannot be passed as keyword.\r\n\r\n data : indexable object, optional\r\n An object with labelled data. If given, provide the label names to\r\n plot in *x* and *y*.\r\n\r\n .. note::\r\n Technically there's a slight ambiguity in calls where the\r\n second label is a valid *fmt*. ``plot('n', 'o', data=obj)``\r\n could be ``plt(x, y)`` or ``plt(y, fmt)``. In such cases,\r\n the former interpretation is chosen, but a warning is issued.\r\n You may suppress the warning by adding an empty format string\r\n ``plot('n', 'o', '', data=obj)``.\r\n\r\n Returns\r\n -------\r\n list of `.Line2D`\r\n A list of lines representing the plotted data.\r\n\r\n Other Parameters\r\n ----------------\r\n scalex, scaley : bool, default: True\r\n These parameters determine if the view limits are adapted to the\r\n data limits. The values are passed on to `autoscale_view`.\r\n\r\n **kwargs : `.Line2D` properties, optional\r\n *kwargs* are used to specify properties like a line label (for\r\n auto legends), linewidth, antialiasing, marker face color.\r\n Example::\r\n\r\n >>> plot([1, 2, 3], [1, 2, 3], 'go-', label='line 1', linewidth=2)\r\n >>> plot([1, 2, 3], [1, 4, 9], 'rs', label='line 2')\r\n\r\n If you make multiple lines with one plot call, the kwargs\r\n apply to all those lines.\r\n\r\n Here is a list of available `.Line2D` properties:\r\n\r\n %(_Line2D_docstr)s\r\n\r\n See Also\r\n --------\r\n scatter : XY scatter plot with markers of varying size and/or color (\r\n sometimes also called bubble chart).\r\n\r\n Notes\r\n -----\r\n **Format Strings**\r\n\r\n A format string consists of a part for color, marker and line::\r\n\r\n fmt = '[marker][line][color]'\r\n\r\n Each of them is optional. If not provided, the value from the style\r\n cycle is used. Exception: If ``line`` is given, but no ``marker``,\r\n the data will be a line without markers.\r\n\r\n Other combinations such as ``[color][marker][line]`` are also\r\n supported, but note that their parsing may be ambiguous.\r\n\r\n **Markers**\r\n\r\n ============= ===============================\r\n character description\r\n ============= ===============================\r\n ``'.'`` point marker\r\n ``','`` pixel marker\r\n ``'o'`` circle marker\r\n ``'v'`` triangle_down marker\r\n ``'^'`` triangle_up marker\r\n ``'<'`` triangle_left marker\r\n ``'>'`` triangle_right marker\r\n ``'1'`` tri_down marker\r\n ``'2'`` tri_up marker\r\n ``'3'`` tri_left marker\r\n ``'4'`` tri_right marker\r\n ``'s'`` square marker\r\n ``'p'`` pentagon marker\r\n ``'*'`` star marker\r\n ``'h'`` hexagon1 marker\r\n ``'H'`` hexagon2 marker\r\n ``'+'`` plus marker\r\n ``'x'`` x marker\r\n ``'D'`` diamond marker\r\n ``'d'`` thin_diamond marker\r\n ``'|'`` vline marker\r\n ``'_'`` hline marker\r\n ============= ===============================\r\n\r\n **Line Styles**\r\n\r\n ============= ===============================\r\n character description\r\n ============= ===============================\r\n ``'-'`` solid line style\r\n ``'--'`` dashed line style\r\n ``'-.'`` dash-dot line style\r\n ``':'`` dotted line style\r\n ============= ===============================\r\n\r\n Example format strings::\r\n\r\n 'b' # blue markers with default shape\r\n 'or' # red circles\r\n '-g' # green solid line\r\n '--' # dashed line with default color\r\n '^k:' # black triangle_up markers connected by a dotted line\r\n\r\n **Colors**\r\n\r\n The supported color abbreviations are the single letter codes\r\n\r\n ============= ===============================\r\n character color\r\n ============= ===============================\r\n ``'b'`` blue\r\n ``'g'`` green\r\n ``'r'`` red\r\n ``'c'`` cyan\r\n ``'m'`` magenta\r\n ``'y'`` yellow\r\n ``'k'`` black\r\n ``'w'`` white\r\n ============= ===============================\r\n\r\n and the ``'CN'`` colors that index into the default property cycle.\r\n\r\n If the color is the only part of the format string, you can\r\n additionally use any `matplotlib.colors` spec, e.g. full names\r\n (``'green'``) or hex strings (``'#008000'``).\r\n \"\"\"\r\n kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)\r\n lines = [*self._get_lines(*args, data=data, **kwargs)]\r\n for line in lines:\r\n self.add_line(line)\r\n self._request_autoscale_view(scalex=scalex, scaley=scaley)\r\n return lines\r\n\r\n @_preprocess_data(replace_names=[\"x\", \"y\"], label_namer=\"y\")\r\n @docstring.dedent_interpd\r\n def plot_date(self, x, y, fmt='o', tz=None, xdate=True, ydate=False,\r\n **kwargs):\r\n \"\"\"\r\n Plot data that contains dates.\r\n\r\n Similar to `.plot`, this plots *y* vs. *x* as lines or markers.\r\n However, the axis labels are formatted as dates depending on *xdate*\r\n and *ydate*.\r\n\r\n Parameters\r\n ----------\r\n x, y : array-like\r\n The coordinates of the data points. If *xdate* or *ydate* is\r\n *True*, the respective values *x* or *y* are interpreted as\r\n :ref:`Matplotlib dates <date-format>`.\r\n\r\n fmt : str, optional\r\n The plot format string. For details, see the corresponding\r\n parameter in `.plot`.\r\n\r\n tz : timezone string or `datetime.tzinfo`, default: :rc:`timezone`\r\n The time zone to use in labeling dates.\r\n\r\n xdate : bool, default: True\r\n If *True*, the *x*-axis will be interpreted as Matplotlib dates.\r\n\r\n ydate : bool, default: False\r\n If *True*, the *y*-axis will be interpreted as Matplotlib dates.\r\n\r\n Returns\r\n -------\r\n lines\r\n A list of `.Line2D` objects representing the plotted data.\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs\r\n Keyword arguments control the `.Line2D` properties:\r\n\r\n %(_Line2D_docstr)s\r\n\r\n See Also\r\n --------\r\n matplotlib.dates : Helper functions on dates.\r\n matplotlib.dates.date2num : Convert dates to num.\r\n matplotlib.dates.num2date : Convert num to dates.\r\n matplotlib.dates.drange : Create an equally spaced sequence of dates.\r\n\r\n Notes\r\n -----\r\n If you are using custom date tickers and formatters, it may be\r\n necessary to set the formatters/locators after the call to\r\n `.plot_date`. `.plot_date` will set the default tick locator to\r\n `.AutoDateLocator` (if the tick locator is not already set to a\r\n `.DateLocator` instance) and the default tick formatter to\r\n `.AutoDateFormatter` (if the tick formatter is not already set to a\r\n `.DateFormatter` instance).\r\n \"\"\"\r\n if xdate:\r\n self.xaxis_date(tz)\r\n if ydate:\r\n self.yaxis_date(tz)\r\n return self.plot(x, y, fmt, **kwargs)\r\n\r\n # @_preprocess_data() # let 'plot' do the unpacking..\r\n @docstring.dedent_interpd\r\n def loglog(self, *args, **kwargs):\r\n \"\"\"\r\n Make a plot with log scaling on both the x and y axis.\r\n\r\n Call signatures::\r\n\r\n loglog([x], y, [fmt], data=None, **kwargs)\r\n loglog([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)\r\n\r\n This is just a thin wrapper around `.plot` which additionally changes\r\n both the x-axis and the y-axis to log scaling. All of the concepts and\r\n parameters of plot can be used here as well.\r\n\r\n The additional parameters *base*, *subs* and *nonpositive* control the\r\n x/y-axis properties. They are just forwarded to `.Axes.set_xscale` and\r\n `.Axes.set_yscale`. To use different properties on the x-axis and the\r\n y-axis, use e.g.\r\n ``ax.set_xscale(\"log\", base=10); ax.set_yscale(\"log\", base=2)``.\r\n\r\n Parameters\r\n ----------\r\n base : float, default: 10\r\n Base of the logarithm.\r\n\r\n subs : sequence, optional\r\n The location of the minor ticks. If *None*, reasonable locations\r\n are automatically chosen depending on the number of decades in the\r\n plot. See `.Axes.set_xscale`/`.Axes.set_yscale` for details.\r\n\r\n nonpositive : {'mask', 'clip'}, default: 'mask'\r\n Non-positive values can be masked as invalid, or clipped to a very\r\n small positive number.\r\n\r\n Returns\r\n -------\r\n lines\r\n A list of `.Line2D` objects representing the plotted data.\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs\r\n All parameters supported by `.plot`.\r\n \"\"\"\r\n dx = {k: v for k, v in kwargs.items()\r\n if k in ['base', 'subs', 'nonpositive',\r\n 'basex', 'subsx', 'nonposx']}\r\n self.set_xscale('log', **dx)\r\n dy = {k: v for k, v in kwargs.items()\r\n if k in ['base', 'subs', 'nonpositive',\r\n 'basey', 'subsy', 'nonposy']}\r\n self.set_yscale('log', **dy)\r\n return self.plot(\r\n *args, **{k: v for k, v in kwargs.items() if k not in {*dx, *dy}})\r\n\r\n # @_preprocess_data() # let 'plot' do the unpacking..\r\n @docstring.dedent_interpd\r\n def semilogx(self, *args, **kwargs):\r\n \"\"\"\r\n Make a plot with log scaling on the x axis.\r\n\r\n Call signatures::\r\n\r\n semilogx([x], y, [fmt], data=None, **kwargs)\r\n semilogx([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)\r\n\r\n This is just a thin wrapper around `.plot` which additionally changes\r\n the x-axis to log scaling. All of the concepts and parameters of plot\r\n can be used here as well.\r\n\r\n The additional parameters *base*, *subs*, and *nonpositive* control the\r\n x-axis properties. They are just forwarded to `.Axes.set_xscale`.\r\n\r\n Parameters\r\n ----------\r\n base : float, default: 10\r\n Base of the x logarithm.\r\n\r\n subs : array-like, optional\r\n The location of the minor xticks. If *None*, reasonable locations\r\n are automatically chosen depending on the number of decades in the\r\n plot. See `.Axes.set_xscale` for details.\r\n\r\n nonpositive : {'mask', 'clip'}, default: 'mask'\r\n Non-positive values in x can be masked as invalid, or clipped to a\r\n very small positive number.\r\n\r\n Returns\r\n -------\r\n lines\r\n A list of `.Line2D` objects representing the plotted data.\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs\r\n All parameters supported by `.plot`.\r\n \"\"\"\r\n d = {k: v for k, v in kwargs.items()\r\n if k in ['base', 'subs', 'nonpositive',\r\n 'basex', 'subsx', 'nonposx']}\r\n self.set_xscale('log', **d)\r\n return self.plot(\r\n *args, **{k: v for k, v in kwargs.items() if k not in d})\r\n\r\n # @_preprocess_data() # let 'plot' do the unpacking..\r\n @docstring.dedent_interpd\r\n def semilogy(self, *args, **kwargs):\r\n \"\"\"\r\n Make a plot with log scaling on the y axis.\r\n\r\n Call signatures::\r\n\r\n semilogy([x], y, [fmt], data=None, **kwargs)\r\n semilogy([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)\r\n\r\n This is just a thin wrapper around `.plot` which additionally changes\r\n the y-axis to log scaling. All of the concepts and parameters of plot\r\n can be used here as well.\r\n\r\n The additional parameters *base*, *subs*, and *nonpositive* control the\r\n y-axis properties. They are just forwarded to `.Axes.set_yscale`.\r\n\r\n Parameters\r\n ----------\r\n base : float, default: 10\r\n Base of the y logarithm.\r\n\r\n subs : array-like, optional\r\n The location of the minor yticks. If *None*, reasonable locations\r\n are automatically chosen depending on the number of decades in the\r\n plot. See `.Axes.set_yscale` for details.\r\n\r\n nonpositive : {'mask', 'clip'}, default: 'mask'\r\n Non-positive values in y can be masked as invalid, or clipped to a\r\n very small positive number.\r\n\r\n Returns\r\n -------\r\n lines\r\n A list of `.Line2D` objects representing the plotted data.\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs\r\n All parameters supported by `.plot`.\r\n \"\"\"\r\n d = {k: v for k, v in kwargs.items()\r\n if k in ['base', 'subs', 'nonpositive',\r\n 'basey', 'subsy', 'nonposy']}\r\n self.set_yscale('log', **d)\r\n return self.plot(\r\n *args, **{k: v for k, v in kwargs.items() if k not in d})\r\n\r\n @_preprocess_data(replace_names=[\"x\"], label_namer=\"x\")\r\n def acorr(self, x, **kwargs):\r\n \"\"\"\r\n Plot the autocorrelation of *x*.\r\n\r\n Parameters\r\n ----------\r\n x : array-like\r\n\r\n detrend : callable, default: `.mlab.detrend_none` (no detrending)\r\n A detrending function applied to *x*. It must have the\r\n signature ::\r\n\r\n detrend(x: np.ndarray) -> np.ndarray\r\n\r\n normed : bool, default: True\r\n If ``True``, input vectors are normalised to unit length.\r\n\r\n usevlines : bool, default: True\r\n Determines the plot style.\r\n\r\n If ``True``, vertical lines are plotted from 0 to the acorr value\r\n using `.Axes.vlines`. Additionally, a horizontal line is plotted\r\n at y=0 using `.Axes.axhline`.\r\n\r\n If ``False``, markers are plotted at the acorr values using\r\n `.Axes.plot`.\r\n\r\n maxlags : int, default: 10\r\n Number of lags to show. If ``None``, will return all\r\n ``2 * len(x) - 1`` lags.\r\n\r\n Returns\r\n -------\r\n lags : array (length ``2*maxlags+1``)\r\n The lag vector.\r\n c : array (length ``2*maxlags+1``)\r\n The auto correlation vector.\r\n line : `.LineCollection` or `.Line2D`\r\n `.Artist` added to the axes of the correlation:\r\n\r\n - `.LineCollection` if *usevlines* is True.\r\n - `.Line2D` if *usevlines* is False.\r\n b : `.Line2D` or None\r\n Horizontal line at 0 if *usevlines* is True\r\n None *usevlines* is False.\r\n\r\n Other Parameters\r\n ----------------\r\n linestyle : `.Line2D` property, optional\r\n The linestyle for plotting the data points.\r\n Only used if *usevlines* is ``False``.\r\n\r\n marker : str, default: 'o'\r\n The marker for plotting the data points.\r\n Only used if *usevlines* is ``False``.\r\n\r\n **kwargs\r\n Additional parameters are passed to `.Axes.vlines` and\r\n `.Axes.axhline` if *usevlines* is ``True``; otherwise they are\r\n passed to `.Axes.plot`.\r\n\r\n Notes\r\n -----\r\n The cross correlation is performed with `numpy.correlate` with\r\n ``mode = \"full\"``.\r\n \"\"\"\r\n return self.xcorr(x, x, **kwargs)\r\n\r\n @_preprocess_data(replace_names=[\"x\", \"y\"], label_namer=\"y\")\r\n def xcorr(self, x, y, normed=True, detrend=mlab.detrend_none,\r\n usevlines=True, maxlags=10, **kwargs):\r\n r\"\"\"\r\n Plot the cross correlation between *x* and *y*.\r\n\r\n The correlation with lag k is defined as\r\n :math:`\\sum_n x[n+k] \\cdot y^*[n]`, where :math:`y^*` is the complex\r\n conjugate of :math:`y`.\r\n\r\n Parameters\r\n ----------\r\n x, y : array-like of length n\r\n\r\n detrend : callable, default: `.mlab.detrend_none` (no detrending)\r\n A detrending function applied to *x* and *y*. It must have the\r\n signature ::\r\n\r\n detrend(x: np.ndarray) -> np.ndarray\r\n\r\n normed : bool, default: True\r\n If ``True``, input vectors are normalised to unit length.\r\n\r\n usevlines : bool, default: True\r\n Determines the plot style.\r\n\r\n If ``True``, vertical lines are plotted from 0 to the xcorr value\r\n using `.Axes.vlines`. Additionally, a horizontal line is plotted\r\n at y=0 using `.Axes.axhline`.\r\n\r\n If ``False``, markers are plotted at the xcorr values using\r\n `.Axes.plot`.\r\n\r\n maxlags : int, default: 10\r\n Number of lags to show. If None, will return all ``2 * len(x) - 1``\r\n lags.\r\n\r\n Returns\r\n -------\r\n lags : array (length ``2*maxlags+1``)\r\n The lag vector.\r\n c : array (length ``2*maxlags+1``)\r\n The auto correlation vector.\r\n line : `.LineCollection` or `.Line2D`\r\n `.Artist` added to the axes of the correlation:\r\n\r\n - `.LineCollection` if *usevlines* is True.\r\n - `.Line2D` if *usevlines* is False.\r\n b : `.Line2D` or None\r\n Horizontal line at 0 if *usevlines* is True\r\n None *usevlines* is False.\r\n\r\n Other Parameters\r\n ----------------\r\n linestyle : `.Line2D` property, optional\r\n The linestyle for plotting the data points.\r\n Only used if *usevlines* is ``False``.\r\n\r\n marker : str, default: 'o'\r\n The marker for plotting the data points.\r\n Only used if *usevlines* is ``False``.\r\n\r\n **kwargs\r\n Additional parameters are passed to `.Axes.vlines` and\r\n `.Axes.axhline` if *usevlines* is ``True``; otherwise they are\r\n passed to `.Axes.plot`.\r\n\r\n Notes\r\n -----\r\n The cross correlation is performed with `numpy.correlate` with\r\n ``mode = \"full\"``.\r\n \"\"\"\r\n Nx = len(x)\r\n if Nx != len(y):\r\n raise ValueError('x and y must be equal length')\r\n\r\n x = detrend(np.asarray(x))\r\n y = detrend(np.asarray(y))\r\n\r\n correls = np.correlate(x, y, mode=\"full\")\r\n\r\n if normed:\r\n correls /= np.sqrt(np.dot(x, x) * np.dot(y, y))\r\n\r\n if maxlags is None:\r\n maxlags = Nx - 1\r\n\r\n if maxlags >= Nx or maxlags < 1:\r\n raise ValueError('maxlags must be None or strictly '\r\n 'positive < %d' % Nx)\r\n\r\n lags = np.arange(-maxlags, maxlags + 1)\r\n correls = correls[Nx - 1 - maxlags:Nx + maxlags]\r\n\r\n if usevlines:\r\n a = self.vlines(lags, [0], correls, **kwargs)\r\n # Make label empty so only vertical lines get a legend entry\r\n kwargs.pop('label', '')\r\n b = self.axhline(**kwargs)\r\n else:\r\n kwargs.setdefault('marker', 'o')\r\n kwargs.setdefault('linestyle', 'None')\r\n a, = self.plot(lags, correls, **kwargs)\r\n b = None\r\n return lags, correls, a, b\r\n\r\n #### Specialized plotting\r\n\r\n # @_preprocess_data() # let 'plot' do the unpacking..\r\n def step(self, x, y, *args, where='pre', data=None, **kwargs):\r\n \"\"\"\r\n Make a step plot.\r\n\r\n Call signatures::\r\n\r\n step(x, y, [fmt], *, data=None, where='pre', **kwargs)\r\n step(x, y, [fmt], x2, y2, [fmt2], ..., *, where='pre', **kwargs)\r\n\r\n This is just a thin wrapper around `.plot` which changes some\r\n formatting options. Most of the concepts and parameters of plot can be\r\n used here as well.\r\n\r\n Parameters\r\n ----------\r\n x : array-like\r\n 1-D sequence of x positions. It is assumed, but not checked, that\r\n it is uniformly increasing.\r\n\r\n y : array-like\r\n 1-D sequence of y levels.\r\n\r\n fmt : str, optional\r\n A format string, e.g. 'g' for a green line. See `.plot` for a more\r\n detailed description.\r\n\r\n Note: While full format strings are accepted, it is recommended to\r\n only specify the color. Line styles are currently ignored (use\r\n the keyword argument *linestyle* instead). Markers are accepted\r\n and plotted on the given positions, however, this is a rarely\r\n needed feature for step plots.\r\n\r\n data : indexable object, optional\r\n An object with labelled data. If given, provide the label names to\r\n plot in *x* and *y*.\r\n\r\n where : {'pre', 'post', 'mid'}, default: 'pre'\r\n Define where the steps should be placed:\r\n\r\n - 'pre': The y value is continued constantly to the left from\r\n every *x* position, i.e. the interval ``(x[i-1], x[i]]`` has the\r\n value ``y[i]``.\r\n - 'post': The y value is continued constantly to the right from\r\n every *x* position, i.e. the interval ``[x[i], x[i+1])`` has the\r\n value ``y[i]``.\r\n - 'mid': Steps occur half-way between the *x* positions.\r\n\r\n Returns\r\n -------\r\n lines\r\n A list of `.Line2D` objects representing the plotted data.\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs\r\n Additional parameters are the same as those for `.plot`.\r\n\r\n Notes\r\n -----\r\n .. [notes section required to get data note injection right]\r\n \"\"\"\r\n cbook._check_in_list(('pre', 'post', 'mid'), where=where)\r\n kwargs['drawstyle'] = 'steps-' + where\r\n return self.plot(x, y, *args, data=data, **kwargs)\r\n\r\n @staticmethod\r\n def _convert_dx(dx, x0, xconv, convert):\r\n \"\"\"\r\n Small helper to do logic of width conversion flexibly.\r\n\r\n *dx* and *x0* have units, but *xconv* has already been converted\r\n to unitless (and is an ndarray). This allows the *dx* to have units\r\n that are different from *x0*, but are still accepted by the\r\n ``__add__`` operator of *x0*.\r\n \"\"\"\r\n\r\n # x should be an array...\r\n assert type(xconv) is np.ndarray\r\n\r\n if xconv.size == 0:\r\n # xconv has already been converted, but maybe empty...\r\n return convert(dx)\r\n\r\n try:\r\n # attempt to add the width to x0; this works for\r\n # datetime+timedelta, for instance\r\n\r\n # only use the first element of x and x0. This saves\r\n # having to be sure addition works across the whole\r\n # vector. This is particularly an issue if\r\n # x0 and dx are lists so x0 + dx just concatenates the lists.\r\n # We can't just cast x0 and dx to numpy arrays because that\r\n # removes the units from unit packages like `pint` that\r\n # wrap numpy arrays.\r\n try:\r\n x0 = cbook.safe_first_element(x0)\r\n except (TypeError, IndexError, KeyError):\r\n x0 = x0\r\n\r\n try:\r\n x = cbook.safe_first_element(xconv)\r\n except (TypeError, IndexError, KeyError):\r\n x = xconv\r\n\r\n delist = False\r\n if not np.iterable(dx):\r\n dx = [dx]\r\n delist = True\r\n dx = [convert(x0 + ddx) - x for ddx in dx]\r\n if delist:\r\n dx = dx[0]\r\n except (ValueError, TypeError, AttributeError):\r\n # if the above fails (for any reason) just fallback to what\r\n # we do by default and convert dx by itself.\r\n dx = convert(dx)\r\n return dx\r\n\r\n @_preprocess_data()\r\n @docstring.dedent_interpd\r\n def bar(self, x, height, width=0.8, bottom=None, *, align=\"center\",\r\n **kwargs):\r\n r\"\"\"\r\n Make a bar plot.\r\n\r\n The bars are positioned at *x* with the given *align*\\ment. Their\r\n dimensions are given by *height* and *width*. The vertical baseline\r\n is *bottom* (default 0).\r\n\r\n Many parameters can take either a single value applying to all bars\r\n or a sequence of values, one for each bar.\r\n\r\n Parameters\r\n ----------\r\n x : float or array-like\r\n The x coordinates of the bars. See also *align* for the\r\n alignment of the bars to the coordinates.\r\n\r\n height : float or array-like\r\n The height(s) of the bars.\r\n\r\n width : float or array-like, default: 0.8\r\n The width(s) of the bars.\r\n\r\n bottom : float or array-like, default: 0\r\n The y coordinate(s) of the bars bases.\r\n\r\n align : {'center', 'edge'}, default: 'center'\r\n Alignment of the bars to the *x* coordinates:\r\n\r\n - 'center': Center the base on the *x* positions.\r\n - 'edge': Align the left edges of the bars with the *x* positions.\r\n\r\n To align the bars on the right edge pass a negative *width* and\r\n ``align='edge'``.\r\n\r\n Returns\r\n -------\r\n `.BarContainer`\r\n Container with all the bars and optionally errorbars.\r\n\r\n Other Parameters\r\n ----------------\r\n color : color or list of color, optional\r\n The colors of the bar faces.\r\n\r\n edgecolor : color or list of color, optional\r\n The colors of the bar edges.\r\n\r\n linewidth : float or array-like, optional\r\n Width of the bar edge(s). If 0, don't draw edges.\r\n\r\n tick_label : str or list of str, optional\r\n The tick labels of the bars.\r\n Default: None (Use default numeric labels.)\r\n\r\n xerr, yerr : float or array-like of shape(N,) or shape(2, N), optional\r\n If not *None*, add horizontal / vertical errorbars to the bar tips.\r\n The values are +/- sizes relative to the data:\r\n\r\n - scalar: symmetric +/- values for all bars\r\n - shape(N,): symmetric +/- values for each bar\r\n - shape(2, N): Separate - and + values for each bar. First row\r\n contains the lower errors, the second row contains the upper\r\n errors.\r\n - *None*: No errorbar. (Default)\r\n\r\n See :doc:`/gallery/statistics/errorbar_features`\r\n for an example on the usage of ``xerr`` and ``yerr``.\r\n\r\n ecolor : color or list of color, default: 'black'\r\n The line color of the errorbars.\r\n\r\n capsize : float, default: :rc:`errorbar.capsize`\r\n The length of the error bar caps in points.\r\n\r\n error_kw : dict, optional\r\n Dictionary of kwargs to be passed to the `~.Axes.errorbar`\r\n method. Values of *ecolor* or *capsize* defined here take\r\n precedence over the independent kwargs.\r\n\r\n log : bool, default: False\r\n If *True*, set the y-axis to be log scale.\r\n\r\n **kwargs : `.Rectangle` properties\r\n\r\n %(Rectangle)s\r\n\r\n See Also\r\n --------\r\n barh: Plot a horizontal bar plot.\r\n\r\n Notes\r\n -----\r\n Stacked bars can be achieved by passing individual *bottom* values per\r\n bar. See :doc:`/gallery/lines_bars_and_markers/bar_stacked`.\r\n \"\"\"\r\n kwargs = cbook.normalize_kwargs(kwargs, mpatches.Patch)\r\n color = kwargs.pop('color', None)\r\n if color is None:\r\n color = self._get_patches_for_fill.get_next_color()\r\n edgecolor = kwargs.pop('edgecolor', None)\r\n linewidth = kwargs.pop('linewidth', None)\r\n\r\n # Because xerr and yerr will be passed to errorbar, most dimension\r\n # checking and processing will be left to the errorbar method.\r\n xerr = kwargs.pop('xerr', None)\r\n yerr = kwargs.pop('yerr', None)\r\n error_kw = kwargs.pop('error_kw', {})\r\n ezorder = error_kw.pop('zorder', None)\r\n if ezorder is None:\r\n ezorder = kwargs.get('zorder', None)\r\n if ezorder is not None:\r\n # If using the bar zorder, increment slightly to make sure\r\n # errorbars are drawn on top of bars\r\n ezorder += 0.01\r\n error_kw.setdefault('zorder', ezorder)\r\n ecolor = kwargs.pop('ecolor', 'k')\r\n capsize = kwargs.pop('capsize', rcParams[\"errorbar.capsize\"])\r\n error_kw.setdefault('ecolor', ecolor)\r\n error_kw.setdefault('capsize', capsize)\r\n\r\n # The keyword argument *orientation* is used by barh() to defer all\r\n # logic and drawing to bar(). It is considered internal and is\r\n # intentionally not mentioned in the docstring.\r\n orientation = kwargs.pop('orientation', 'vertical')\r\n cbook._check_in_list(['vertical', 'horizontal'],\r\n orientation=orientation)\r\n log = kwargs.pop('log', False)\r\n label = kwargs.pop('label', '')\r\n tick_labels = kwargs.pop('tick_label', None)\r\n\r\n y = bottom # Matches barh call signature.\r\n if orientation == 'vertical':\r\n if y is None:\r\n y = 0\r\n elif orientation == 'horizontal':\r\n if x is None:\r\n x = 0\r\n\r\n if orientation == 'vertical':\r\n self._process_unit_info(xdata=x, ydata=height, kwargs=kwargs)\r\n if log:\r\n self.set_yscale('log', nonpositive='clip')\r\n elif orientation == 'horizontal':\r\n self._process_unit_info(xdata=width, ydata=y, kwargs=kwargs)\r\n if log:\r\n self.set_xscale('log', nonpositive='clip')\r\n\r\n # lets do some conversions now since some types cannot be\r\n # subtracted uniformly\r\n if self.xaxis is not None:\r\n x0 = x\r\n x = np.asarray(self.convert_xunits(x))\r\n width = self._convert_dx(width, x0, x, self.convert_xunits)\r\n if xerr is not None:\r\n xerr = self._convert_dx(xerr, x0, x, self.convert_xunits)\r\n if self.yaxis is not None:\r\n y0 = y\r\n y = np.asarray(self.convert_yunits(y))\r\n height = self._convert_dx(height, y0, y, self.convert_yunits)\r\n if yerr is not None:\r\n yerr = self._convert_dx(yerr, y0, y, self.convert_yunits)\r\n\r\n x, height, width, y, linewidth = np.broadcast_arrays(\r\n # Make args iterable too.\r\n np.atleast_1d(x), height, width, y, linewidth)\r\n\r\n # Now that units have been converted, set the tick locations.\r\n if orientation == 'vertical':\r\n tick_label_axis = self.xaxis\r\n tick_label_position = x\r\n elif orientation == 'horizontal':\r\n tick_label_axis = self.yaxis\r\n tick_label_position = y\r\n\r\n linewidth = itertools.cycle(np.atleast_1d(linewidth))\r\n color = itertools.chain(itertools.cycle(mcolors.to_rgba_array(color)),\r\n # Fallback if color == \"none\".\r\n itertools.repeat('none'))\r\n if edgecolor is None:\r\n edgecolor = itertools.repeat(None)\r\n else:\r\n edgecolor = itertools.chain(\r\n itertools.cycle(mcolors.to_rgba_array(edgecolor)),\r\n # Fallback if edgecolor == \"none\".\r\n itertools.repeat('none'))\r\n\r\n # We will now resolve the alignment and really have\r\n # left, bottom, width, height vectors\r\n cbook._check_in_list(['center', 'edge'], align=align)\r\n if align == 'center':\r\n if orientation == 'vertical':\r\n try:\r\n left = x - width / 2\r\n except TypeError as e:\r\n raise TypeError(f'the dtypes of parameters x ({x.dtype}) '\r\n f'and width ({width.dtype}) '\r\n f'are incompatible') from e\r\n bottom = y\r\n elif orientation == 'horizontal':\r\n try:\r\n bottom = y - height / 2\r\n except TypeError as e:\r\n raise TypeError(f'the dtypes of parameters y ({y.dtype}) '\r\n f'and height ({height.dtype}) '\r\n f'are incompatible') from e\r\n left = x\r\n elif align == 'edge':\r\n left = x\r\n bottom = y\r\n\r\n patches = []\r\n args = zip(left, bottom, width, height, color, edgecolor, linewidth)\r\n for l, b, w, h, c, e, lw in args:\r\n r = mpatches.Rectangle(\r\n xy=(l, b), width=w, height=h,\r\n facecolor=c,\r\n edgecolor=e,\r\n linewidth=lw,\r\n label='_nolegend_',\r\n )\r\n r.update(kwargs)\r\n r.get_path()._interpolation_steps = 100\r\n if orientation == 'vertical':\r\n r.sticky_edges.y.append(b)\r\n elif orientation == 'horizontal':\r\n r.sticky_edges.x.append(l)\r\n self.add_patch(r)\r\n patches.append(r)\r\n\r\n if xerr is not None or yerr is not None:\r\n if orientation == 'vertical':\r\n # using list comps rather than arrays to preserve unit info\r\n ex = [l + 0.5 * w for l, w in zip(left, width)]\r\n ey = [b + h for b, h in zip(bottom, height)]\r\n\r\n elif orientation == 'horizontal':\r\n # using list comps rather than arrays to preserve unit info\r\n ex = [l + w for l, w in zip(left, width)]\r\n ey = [b + 0.5 * h for b, h in zip(bottom, height)]\r\n\r\n error_kw.setdefault(\"label\", '_nolegend_')\r\n\r\n errorbar = self.errorbar(ex, ey,\r\n yerr=yerr, xerr=xerr,\r\n fmt='none', **error_kw)\r\n else:\r\n errorbar = None\r\n\r\n self._request_autoscale_view()\r\n\r\n bar_container = BarContainer(patches, errorbar, label=label)\r\n self.add_container(bar_container)\r\n\r\n if tick_labels is not None:\r\n tick_labels = np.broadcast_to(tick_labels, len(patches))\r\n tick_label_axis.set_ticks(tick_label_position)\r\n tick_label_axis.set_ticklabels(tick_labels)\r\n\r\n return bar_container\r\n\r\n @docstring.dedent_interpd\r\n def barh(self, y, width, height=0.8, left=None, *, align=\"center\",\r\n **kwargs):\r\n r\"\"\"\r\n Make a horizontal bar plot.\r\n\r\n The bars are positioned at *y* with the given *align*\\ment. Their\r\n dimensions are given by *width* and *height*. The horizontal baseline\r\n is *left* (default 0).\r\n\r\n Many parameters can take either a single value applying to all bars\r\n or a sequence of values, one for each bar.\r\n\r\n Parameters\r\n ----------\r\n y : float or array-like\r\n The y coordinates of the bars. See also *align* for the\r\n alignment of the bars to the coordinates.\r\n\r\n width : float or array-like\r\n The width(s) of the bars.\r\n\r\n height : float or array-like, default: 0.8\r\n The heights of the bars.\r\n\r\n left : float or array-like, default: 0\r\n The x coordinates of the left sides of the bars.\r\n\r\n align : {'center', 'edge'}, default: 'center'\r\n Alignment of the base to the *y* coordinates*:\r\n\r\n - 'center': Center the bars on the *y* positions.\r\n - 'edge': Align the bottom edges of the bars with the *y*\r\n positions.\r\n\r\n To align the bars on the top edge pass a negative *height* and\r\n ``align='edge'``.\r\n\r\n Returns\r\n -------\r\n `.BarContainer`\r\n Container with all the bars and optionally errorbars.\r\n\r\n Other Parameters\r\n ----------------\r\n color : color or list of color, optional\r\n The colors of the bar faces.\r\n\r\n edgecolor : color or list of color, optional\r\n The colors of the bar edges.\r\n\r\n linewidth : float or array-like, optional\r\n Width of the bar edge(s). If 0, don't draw edges.\r\n\r\n tick_label : str or list of str, optional\r\n The tick labels of the bars.\r\n Default: None (Use default numeric labels.)\r\n\r\n xerr, yerr : float or array-like of shape(N,) or shape(2, N), optional\r\n If not ``None``, add horizontal / vertical errorbars to the\r\n bar tips. The values are +/- sizes relative to the data:\r\n\r\n - scalar: symmetric +/- values for all bars\r\n - shape(N,): symmetric +/- values for each bar\r\n - shape(2, N): Separate - and + values for each bar. First row\r\n contains the lower errors, the second row contains the upper\r\n errors.\r\n - *None*: No errorbar. (default)\r\n\r\n See :doc:`/gallery/statistics/errorbar_features`\r\n for an example on the usage of ``xerr`` and ``yerr``.\r\n\r\n ecolor : color or list of color, default: 'black'\r\n The line color of the errorbars.\r\n\r\n capsize : float, default: :rc:`errorbar.capsize`\r\n The length of the error bar caps in points.\r\n\r\n error_kw : dict, optional\r\n Dictionary of kwargs to be passed to the `~.Axes.errorbar`\r\n method. Values of *ecolor* or *capsize* defined here take\r\n precedence over the independent kwargs.\r\n\r\n log : bool, default: False\r\n If ``True``, set the x-axis to be log scale.\r\n\r\n **kwargs : `.Rectangle` properties\r\n\r\n %(Rectangle)s\r\n\r\n See Also\r\n --------\r\n bar: Plot a vertical bar plot.\r\n\r\n Notes\r\n -----\r\n Stacked bars can be achieved by passing individual *left* values per\r\n bar. See\r\n :doc:`/gallery/lines_bars_and_markers/horizontal_barchart_distribution`\r\n .\r\n \"\"\"\r\n kwargs.setdefault('orientation', 'horizontal')\r\n patches = self.bar(x=left, height=height, width=width, bottom=y,\r\n align=align, **kwargs)\r\n return patches\r\n\r\n @_preprocess_data()\r\n @docstring.dedent_interpd\r\n def broken_barh(self, xranges, yrange, **kwargs):\r\n \"\"\"\r\n Plot a horizontal sequence of rectangles.\r\n\r\n A rectangle is drawn for each element of *xranges*. All rectangles\r\n have the same vertical position and size defined by *yrange*.\r\n\r\n This is a convenience function for instantiating a\r\n `.BrokenBarHCollection`, adding it to the axes and autoscaling the\r\n view.\r\n\r\n Parameters\r\n ----------\r\n xranges : sequence of tuples (*xmin*, *xwidth*)\r\n The x-positions and extends of the rectangles. For each tuple\r\n (*xmin*, *xwidth*) a rectangle is drawn from *xmin* to *xmin* +\r\n *xwidth*.\r\n yrange : (*ymin*, *yheight*)\r\n The y-position and extend for all the rectangles.\r\n\r\n Returns\r\n -------\r\n `~.collections.BrokenBarHCollection`\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs : `.BrokenBarHCollection` properties\r\n\r\n Each *kwarg* can be either a single argument applying to all\r\n rectangles, e.g.::\r\n\r\n facecolors='black'\r\n\r\n or a sequence of arguments over which is cycled, e.g.::\r\n\r\n facecolors=('black', 'blue')\r\n\r\n would create interleaving black and blue rectangles.\r\n\r\n Supported keywords:\r\n\r\n %(BrokenBarHCollection)s\r\n \"\"\"\r\n # process the unit information\r\n if len(xranges):\r\n xdata = cbook.safe_first_element(xranges)\r\n else:\r\n xdata = None\r\n if len(yrange):\r\n ydata = cbook.safe_first_element(yrange)\r\n else:\r\n ydata = None\r\n self._process_unit_info(xdata=xdata,\r\n ydata=ydata,\r\n kwargs=kwargs)\r\n xranges_conv = []\r\n for xr in xranges:\r\n if len(xr) != 2:\r\n raise ValueError('each range in xrange must be a sequence '\r\n 'with two elements (i.e. an Nx2 array)')\r\n # convert the absolute values, not the x and dx...\r\n x_conv = np.asarray(self.convert_xunits(xr[0]))\r\n x1 = self._convert_dx(xr[1], xr[0], x_conv, self.convert_xunits)\r\n xranges_conv.append((x_conv, x1))\r\n\r\n yrange_conv = self.convert_yunits(yrange)\r\n\r\n col = mcoll.BrokenBarHCollection(xranges_conv, yrange_conv, **kwargs)\r\n self.add_collection(col, autolim=True)\r\n self._request_autoscale_view()\r\n\r\n return col\r\n\r\n @_preprocess_data()\r\n def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0,\r\n label=None, use_line_collection=True):\r\n \"\"\"\r\n Create a stem plot.\r\n\r\n A stem plot plots vertical lines at each *x* location from the baseline\r\n to *y*, and places a marker there.\r\n\r\n Call signature::\r\n\r\n stem([x,] y, linefmt=None, markerfmt=None, basefmt=None)\r\n\r\n The x-positions are optional. The formats may be provided either as\r\n positional or as keyword-arguments.\r\n\r\n Parameters\r\n ----------\r\n x : array-like, optional\r\n The x-positions of the stems. Default: (0, 1, ..., len(y) - 1).\r\n\r\n y : array-like\r\n The y-values of the stem heads.\r\n\r\n linefmt : str, optional\r\n A string defining the properties of the vertical lines. Usually,\r\n this will be a color or a color and a linestyle:\r\n\r\n ========= =============\r\n Character Line Style\r\n ========= =============\r\n ``'-'`` solid line\r\n ``'--'`` dashed line\r\n ``'-.'`` dash-dot line\r\n ``':'`` dotted line\r\n ========= =============\r\n\r\n Default: 'C0-', i.e. solid line with the first color of the color\r\n cycle.\r\n\r\n Note: While it is technically possible to specify valid formats\r\n other than color or color and linestyle (e.g. 'rx' or '-.'), this\r\n is beyond the intention of the method and will most likely not\r\n result in a reasonable plot.\r\n\r\n markerfmt : str, optional\r\n A string defining the properties of the markers at the stem heads.\r\n Default: 'C0o', i.e. filled circles with the first color of the\r\n color cycle.\r\n\r\n basefmt : str, default: 'C3-' ('C2-' in classic mode)\r\n A format string defining the properties of the baseline.\r\n\r\n bottom : float, default: 0\r\n The y-position of the baseline.\r\n\r\n label : str, default: None\r\n The label to use for the stems in legends.\r\n\r\n use_line_collection : bool, default: True\r\n If ``True``, store and plot the stem lines as a\r\n `~.collections.LineCollection` instead of individual lines, which\r\n significantly increases performance. If ``False``, defaults to the\r\n old behavior of using a list of `.Line2D` objects. This parameter\r\n may be deprecated in the future.\r\n\r\n Returns\r\n -------\r\n `.StemContainer`\r\n The container may be treated like a tuple\r\n (*markerline*, *stemlines*, *baseline*)\r\n\r\n Notes\r\n -----\r\n .. seealso::\r\n The MATLAB function\r\n `stem <https://www.mathworks.com/help/matlab/ref/stem.html>`_\r\n which inspired this method.\r\n \"\"\"\r\n if not 1 <= len(args) <= 5:\r\n raise TypeError('stem expected between 1 and 5 positional '\r\n 'arguments, got {}'.format(args))\r\n\r\n if len(args) == 1:\r\n y, = args\r\n x = np.arange(len(y))\r\n args = ()\r\n else:\r\n x, y, *args = args\r\n\r\n self._process_unit_info(xdata=x, ydata=y)\r\n x = self.convert_xunits(x)\r\n y = self.convert_yunits(y)\r\n\r\n # defaults for formats\r\n if linefmt is None:\r\n try:\r\n # fallback to positional argument\r\n linefmt = args[0]\r\n except IndexError:\r\n linecolor = 'C0'\r\n linemarker = 'None'\r\n linestyle = '-'\r\n else:\r\n linestyle, linemarker, linecolor = \\\r\n _process_plot_format(linefmt)\r\n else:\r\n linestyle, linemarker, linecolor = _process_plot_format(linefmt)\r\n\r\n if markerfmt is None:\r\n try:\r\n # fallback to positional argument\r\n markerfmt = args[1]\r\n except IndexError:\r\n markercolor = 'C0'\r\n markermarker = 'o'\r\n markerstyle = 'None'\r\n else:\r\n markerstyle, markermarker, markercolor = \\\r\n _process_plot_format(markerfmt)\r\n else:\r\n markerstyle, markermarker, markercolor = \\\r\n _process_plot_format(markerfmt)\r\n\r\n if basefmt is None:\r\n try:\r\n # fallback to positional argument\r\n basefmt = args[2]\r\n except IndexError:\r\n if rcParams['_internal.classic_mode']:\r\n basecolor = 'C2'\r\n else:\r\n basecolor = 'C3'\r\n basemarker = 'None'\r\n basestyle = '-'\r\n else:\r\n basestyle, basemarker, basecolor = \\\r\n _process_plot_format(basefmt)\r\n else:\r\n basestyle, basemarker, basecolor = _process_plot_format(basefmt)\r\n\r\n # New behaviour in 3.1 is to use a LineCollection for the stemlines\r\n if use_line_collection:\r\n stemlines = [((xi, bottom), (xi, yi)) for xi, yi in zip(x, y)]\r\n if linestyle is None:\r\n linestyle = rcParams['lines.linestyle']\r\n stemlines = mcoll.LineCollection(stemlines, linestyles=linestyle,\r\n colors=linecolor,\r\n label='_nolegend_')\r\n self.add_collection(stemlines)\r\n # Old behaviour is to plot each of the lines individually\r\n else:\r\n stemlines = []\r\n for xi, yi in zip(x, y):\r\n l, = self.plot([xi, xi], [bottom, yi],\r\n color=linecolor, linestyle=linestyle,\r\n marker=linemarker, label=\"_nolegend_\")\r\n stemlines.append(l)\r\n\r\n markerline, = self.plot(x, y, color=markercolor, linestyle=markerstyle,\r\n marker=markermarker, label=\"_nolegend_\")\r\n\r\n baseline, = self.plot([np.min(x), np.max(x)], [bottom, bottom],\r\n color=basecolor, linestyle=basestyle,\r\n marker=basemarker, label=\"_nolegend_\")\r\n\r\n stem_container = StemContainer((markerline, stemlines, baseline),\r\n label=label)\r\n self.add_container(stem_container)\r\n return stem_container\r\n\r\n @_preprocess_data(replace_names=[\"x\", \"explode\", \"labels\", \"colors\"])\r\n def pie(self, x, explode=None, labels=None, colors=None,\r\n autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1,\r\n startangle=0, radius=1, counterclock=True,\r\n wedgeprops=None, textprops=None, center=(0, 0),\r\n frame=False, rotatelabels=False, *, normalize=None):\r\n \"\"\"\r\n Plot a pie chart.\r\n\r\n Make a pie chart of array *x*. The fractional area of each wedge is\r\n given by ``x/sum(x)``. If ``sum(x) < 1``, then the values of *x* give\r\n the fractional area directly and the array will not be normalized. The\r\n resulting pie will have an empty wedge of size ``1 - sum(x)``.\r\n\r\n The wedges are plotted counterclockwise, by default starting from the\r\n x-axis.\r\n\r\n Parameters\r\n ----------\r\n x : 1D array-like\r\n The wedge sizes.\r\n\r\n explode : array-like, default: None\r\n If not *None*, is a ``len(x)`` array which specifies the fraction\r\n of the radius with which to offset each wedge.\r\n\r\n labels : list, default: None\r\n A sequence of strings providing the labels for each wedge\r\n\r\n colors : array-like, default: None\r\n A sequence of colors through which the pie chart will cycle. If\r\n *None*, will use the colors in the currently active cycle.\r\n\r\n autopct : None or str or callable, default: None\r\n If not *None*, is a string or function used to label the wedges\r\n with their numeric value. The label will be placed inside the\r\n wedge. If it is a format string, the label will be ``fmt % pct``.\r\n If it is a function, it will be called.\r\n\r\n pctdistance : float, default: 0.6\r\n The ratio between the center of each pie slice and the start of\r\n the text generated by *autopct*. Ignored if *autopct* is *None*.\r\n\r\n shadow : bool, default: False\r\n Draw a shadow beneath the pie.\r\n\r\n normalize: None or bool, default: None\r\n When *True*, always make a full pie by normalizing x so that\r\n ``sum(x) == 1``. *False* makes a partial pie if ``sum(x) <= 1``\r\n and raises a `ValueError` for ``sum(x) > 1``.\r\n\r\n When *None*, defaults to *True* if ``sum(x) >= 1`` and *False* if\r\n ``sum(x) < 1``.\r\n\r\n Please note that the previous default value of *None* is now\r\n deprecated, and the default will change to *True* in the next\r\n release. Please pass ``normalize=False`` explicitly if you want to\r\n draw a partial pie.\r\n\r\n labeldistance : float or None, default: 1.1\r\n The radial distance at which the pie labels are drawn.\r\n If set to ``None``, label are not drawn, but are stored for use in\r\n ``legend()``\r\n\r\n startangle : float, default: 0 degrees\r\n The angle by which the start of the pie is rotated,\r\n counterclockwise from the x-axis.\r\n\r\n radius : float, default: 1\r\n The radius of the pie.\r\n\r\n counterclock : bool, default: True\r\n Specify fractions direction, clockwise or counterclockwise.\r\n\r\n wedgeprops : dict, default: None\r\n Dict of arguments passed to the wedge objects making the pie.\r\n For example, you can pass in ``wedgeprops = {'linewidth': 3}``\r\n to set the width of the wedge border lines equal to 3.\r\n For more details, look at the doc/arguments of the wedge object.\r\n By default ``clip_on=False``.\r\n\r\n textprops : dict, default: None\r\n Dict of arguments to pass to the text objects.\r\n\r\n center : (float, float), default: (0, 0)\r\n The coordinates of the center of the chart.\r\n\r\n frame : bool, default: False\r\n Plot axes frame with the chart if true.\r\n\r\n rotatelabels : bool, default: False\r\n Rotate each label to the angle of the corresponding slice if true.\r\n\r\n Returns\r\n -------\r\n patches : list\r\n A sequence of `matplotlib.patches.Wedge` instances\r\n\r\n texts : list\r\n A list of the label `.Text` instances.\r\n\r\n autotexts : list\r\n A list of `.Text` instances for the numeric labels. This will only\r\n be returned if the parameter *autopct* is not *None*.\r\n\r\n Notes\r\n -----\r\n The pie chart will probably look best if the figure and axes are\r\n square, or the Axes aspect is equal.\r\n This method sets the aspect ratio of the axis to \"equal\".\r\n The axes aspect ratio can be controlled with `.Axes.set_aspect`.\r\n \"\"\"\r\n self.set_aspect('equal')\r\n # The use of float32 is \"historical\", but can't be changed without\r\n # regenerating the test baselines.\r\n x = np.asarray(x, np.float32)\r\n if x.ndim > 1:\r\n raise ValueError(\"x must be 1D\")\r\n\r\n if np.any(x < 0):\r\n raise ValueError(\"Wedge sizes 'x' must be non negative values\")\r\n\r\n sx = x.sum()\r\n\r\n if normalize is None:\r\n if sx < 1:\r\n cbook.warn_deprecated(\r\n \"3.3\", message=\"normalize=None does not normalize \"\r\n \"if the sum is less than 1 but this behavior \"\r\n \"is deprecated since %(since)s until %(removal)s. \"\r\n \"After the deprecation \"\r\n \"period the default value will be normalize=True. \"\r\n \"To prevent normalization pass normalize=False \")\r\n else:\r\n normalize = True\r\n if normalize:\r\n x = x / sx\r\n elif sx > 1:\r\n raise ValueError('Cannot plot an unnormalized pie with sum(x) > 1')\r\n if labels is None:\r\n labels = [''] * len(x)\r\n if explode is None:\r\n explode = [0] * len(x)\r\n if len(x) != len(labels):\r\n raise ValueError(\"'label' must be of length 'x'\")\r\n if len(x) != len(explode):\r\n raise ValueError(\"'explode' must be of length 'x'\")\r\n if colors is None:\r\n get_next_color = self._get_patches_for_fill.get_next_color\r\n else:\r\n color_cycle = itertools.cycle(colors)\r\n\r\n def get_next_color():\r\n return next(color_cycle)\r\n\r\n if radius is None:\r\n cbook.warn_deprecated(\r\n \"3.3\", message=\"Support for passing a radius of None to mean \"\r\n \"1 is deprecated since %(since)s and will be removed \"\r\n \"%(removal)s.\")\r\n radius = 1\r\n\r\n # Starting theta1 is the start fraction of the circle\r\n if startangle is None:\r\n cbook.warn_deprecated(\r\n \"3.3\", message=\"Support for passing a startangle of None to \"\r\n \"mean 0 is deprecated since %(since)s and will be removed \"\r\n \"%(removal)s.\")\r\n startangle = 0\r\n theta1 = startangle / 360\r\n\r\n if wedgeprops is None:\r\n wedgeprops = {}\r\n if textprops is None:\r\n textprops = {}\r\n\r\n texts = []\r\n slices = []\r\n autotexts = []\r\n\r\n for frac, label, expl in zip(x, labels, explode):\r\n x, y = center\r\n theta2 = (theta1 + frac) if counterclock else (theta1 - frac)\r\n thetam = 2 * np.pi * 0.5 * (theta1 + theta2)\r\n x += expl * math.cos(thetam)\r\n y += expl * math.sin(thetam)\r\n\r\n w = mpatches.Wedge((x, y), radius, 360. * min(theta1, theta2),\r\n 360. * max(theta1, theta2),\r\n facecolor=get_next_color(),\r\n clip_on=False,\r\n label=label)\r\n w.set(**wedgeprops)\r\n slices.append(w)\r\n self.add_patch(w)\r\n\r\n if shadow:\r\n # Make sure to add a shadow after the call to add_patch so the\r\n # figure and transform props will be set.\r\n shad = mpatches.Shadow(w, -0.02, -0.02, label='_nolegend_')\r\n self.add_patch(shad)\r\n\r\n if labeldistance is not None:\r\n xt = x + labeldistance * radius * math.cos(thetam)\r\n yt = y + labeldistance * radius * math.sin(thetam)\r\n label_alignment_h = 'left' if xt > 0 else 'right'\r\n label_alignment_v = 'center'\r\n label_rotation = 'horizontal'\r\n if rotatelabels:\r\n label_alignment_v = 'bottom' if yt > 0 else 'top'\r\n label_rotation = (np.rad2deg(thetam)\r\n + (0 if xt > 0 else 180))\r\n t = self.text(xt, yt, label,\r\n clip_on=False,\r\n horizontalalignment=label_alignment_h,\r\n verticalalignment=label_alignment_v,\r\n rotation=label_rotation,\r\n size=rcParams['xtick.labelsize'])\r\n t.set(**textprops)\r\n texts.append(t)\r\n\r\n if autopct is not None:\r\n xt = x + pctdistance * radius * math.cos(thetam)\r\n yt = y + pctdistance * radius * math.sin(thetam)\r\n if isinstance(autopct, str):\r\n s = autopct % (100. * frac)\r\n elif callable(autopct):\r\n s = autopct(100. * frac)\r\n else:\r\n raise TypeError(\r\n 'autopct must be callable or a format string')\r\n t = self.text(xt, yt, s,\r\n clip_on=False,\r\n horizontalalignment='center',\r\n verticalalignment='center')\r\n t.set(**textprops)\r\n autotexts.append(t)\r\n\r\n theta1 = theta2\r\n\r\n if not frame:\r\n self.set(frame_on=False, xticks=[], yticks=[],\r\n xlim=(-1.25 + center[0], 1.25 + center[0]),\r\n ylim=(-1.25 + center[1], 1.25 + center[1]))\r\n\r\n if autopct is None:\r\n return slices, texts\r\n else:\r\n return slices, texts, autotexts\r\n\r\n @_preprocess_data(replace_names=[\"x\", \"y\", \"xerr\", \"yerr\"],\r\n label_namer=\"y\")\r\n @docstring.dedent_interpd\r\n def errorbar(self, x, y, yerr=None, xerr=None,\r\n fmt='', ecolor=None, elinewidth=None, capsize=None,\r\n barsabove=False, lolims=False, uplims=False,\r\n xlolims=False, xuplims=False, errorevery=1, capthick=None,\r\n **kwargs):\r\n \"\"\"\r\n Plot y versus x as lines and/or markers with attached errorbars.\r\n\r\n *x*, *y* define the data locations, *xerr*, *yerr* define the errorbar\r\n sizes. By default, this draws the data markers/lines as well the\r\n errorbars. Use fmt='none' to draw errorbars without any data markers.\r\n\r\n Parameters\r\n ----------\r\n x, y : float or array-like\r\n The data positions.\r\n\r\n xerr, yerr : float or array-like, shape(N,) or shape(2, N), optional\r\n The errorbar sizes:\r\n\r\n - scalar: Symmetric +/- values for all data points.\r\n - shape(N,): Symmetric +/-values for each data point.\r\n - shape(2, N): Separate - and + values for each bar. First row\r\n contains the lower errors, the second row contains the upper\r\n errors.\r\n - *None*: No errorbar.\r\n\r\n Note that all error arrays should have *positive* values.\r\n\r\n See :doc:`/gallery/statistics/errorbar_features`\r\n for an example on the usage of ``xerr`` and ``yerr``.\r\n\r\n fmt : str, default: ''\r\n The format for the data points / data lines. See `.plot` for\r\n details.\r\n\r\n Use 'none' (case insensitive) to plot errorbars without any data\r\n markers.\r\n\r\n ecolor : color, default: None\r\n The color of the errorbar lines. If None, use the color of the\r\n line connecting the markers.\r\n\r\n elinewidth : float, default: None\r\n The linewidth of the errorbar lines. If None, the linewidth of\r\n the current style is used.\r\n\r\n capsize : float, default: :rc:`errorbar.capsize`\r\n The length of the error bar caps in points.\r\n\r\n capthick : float, default: None\r\n An alias to the keyword argument *markeredgewidth* (a.k.a. *mew*).\r\n This setting is a more sensible name for the property that\r\n controls the thickness of the error bar cap in points. For\r\n backwards compatibility, if *mew* or *markeredgewidth* are given,\r\n then they will over-ride *capthick*. This may change in future\r\n releases.\r\n\r\n barsabove : bool, default: False\r\n If True, will plot the errorbars above the plot\r\n symbols. Default is below.\r\n\r\n lolims, uplims, xlolims, xuplims : bool, default: False\r\n These arguments can be used to indicate that a value gives only\r\n upper/lower limits. In that case a caret symbol is used to\r\n indicate this. *lims*-arguments may be scalars, or array-likes of\r\n the same length as *xerr* and *yerr*. To use limits with inverted\r\n axes, `~.Axes.set_xlim` or `~.Axes.set_ylim` must be called before\r\n :meth:`errorbar`. Note the tricky parameter names: setting e.g.\r\n *lolims* to True means that the y-value is a *lower* limit of the\r\n True value, so, only an *upward*-pointing arrow will be drawn!\r\n\r\n errorevery : int or (int, int), default: 1\r\n draws error bars on a subset of the data. *errorevery* =N draws\r\n error bars on the points (x[::N], y[::N]).\r\n *errorevery* =(start, N) draws error bars on the points\r\n (x[start::N], y[start::N]). e.g. errorevery=(6, 3)\r\n adds error bars to the data at (x[6], x[9], x[12], x[15], ...).\r\n Used to avoid overlapping error bars when two series share x-axis\r\n values.\r\n\r\n Returns\r\n -------\r\n `.ErrorbarContainer`\r\n The container contains:\r\n\r\n - plotline: `.Line2D` instance of x, y plot markers and/or line.\r\n - caplines: A tuple of `.Line2D` instances of the error bar caps.\r\n - barlinecols: A tuple of `.LineCollection` with the horizontal and\r\n vertical error ranges.\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs\r\n All other keyword arguments are passed on to the `~.Axes.plot` call\r\n drawing the markers. For example, this code makes big red squares\r\n with thick green edges::\r\n\r\n x, y, yerr = rand(3, 10)\r\n errorbar(x, y, yerr, marker='s', mfc='red',\r\n mec='green', ms=20, mew=4)\r\n\r\n where *mfc*, *mec*, *ms* and *mew* are aliases for the longer\r\n property names, *markerfacecolor*, *markeredgecolor*, *markersize*\r\n and *markeredgewidth*.\r\n\r\n Valid kwargs for the marker properties are `.Line2D` properties:\r\n\r\n %(_Line2D_docstr)s\r\n \"\"\"\r\n kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)\r\n # anything that comes in as 'None', drop so the default thing\r\n # happens down stream\r\n kwargs = {k: v for k, v in kwargs.items() if v is not None}\r\n kwargs.setdefault('zorder', 2)\r\n\r\n try:\r\n offset, errorevery = errorevery\r\n except TypeError:\r\n offset = 0\r\n\r\n if errorevery < 1 or int(errorevery) != errorevery:\r\n raise ValueError(\r\n 'errorevery must be positive integer or tuple of integers')\r\n if int(offset) != offset:\r\n raise ValueError(\"errorevery's starting index must be an integer\")\r\n\r\n self._process_unit_info(xdata=x, ydata=y, kwargs=kwargs)\r\n\r\n plot_line = (fmt.lower() != 'none')\r\n label = kwargs.pop(\"label\", None)\r\n\r\n if fmt == '':\r\n fmt_style_kwargs = {}\r\n else:\r\n fmt_style_kwargs = {k: v for k, v in\r\n zip(('linestyle', 'marker', 'color'),\r\n _process_plot_format(fmt))\r\n if v is not None}\r\n if fmt == 'none':\r\n # Remove alpha=0 color that _process_plot_format returns\r\n fmt_style_kwargs.pop('color')\r\n\r\n if ('color' in kwargs or 'color' in fmt_style_kwargs):\r\n base_style = {}\r\n if 'color' in kwargs:\r\n base_style['color'] = kwargs.pop('color')\r\n else:\r\n base_style = next(self._get_lines.prop_cycler)\r\n\r\n base_style['label'] = '_nolegend_'\r\n base_style.update(fmt_style_kwargs)\r\n if 'color' not in base_style:\r\n base_style['color'] = 'C0'\r\n if ecolor is None:\r\n ecolor = base_style['color']\r\n # make sure all the args are iterable; use lists not arrays to\r\n # preserve units\r\n if not np.iterable(x):\r\n x = [x]\r\n\r\n if not np.iterable(y):\r\n y = [y]\r\n\r\n if len(x) != len(y):\r\n raise ValueError(\"'x' and 'y' must have the same size\")\r\n\r\n if xerr is not None:\r\n if not np.iterable(xerr):\r\n xerr = [xerr] * len(x)\r\n\r\n if yerr is not None:\r\n if not np.iterable(yerr):\r\n yerr = [yerr] * len(y)\r\n\r\n # make the style dict for the 'normal' plot line\r\n plot_line_style = {\r\n **base_style,\r\n **kwargs,\r\n 'zorder': (kwargs['zorder'] - .1 if barsabove else\r\n kwargs['zorder'] + .1),\r\n }\r\n\r\n # make the style dict for the line collections (the bars)\r\n eb_lines_style = dict(base_style)\r\n eb_lines_style.pop('marker', None)\r\n eb_lines_style.pop('linestyle', None)\r\n eb_lines_style['color'] = ecolor\r\n\r\n if elinewidth:\r\n eb_lines_style['linewidth'] = elinewidth\r\n elif 'linewidth' in kwargs:\r\n eb_lines_style['linewidth'] = kwargs['linewidth']\r\n\r\n for key in ('transform', 'alpha', 'zorder', 'rasterized'):\r\n if key in kwargs:\r\n eb_lines_style[key] = kwargs[key]\r\n\r\n # set up cap style dictionary\r\n eb_cap_style = dict(base_style)\r\n # eject any marker information from format string\r\n eb_cap_style.pop('marker', None)\r\n eb_lines_style.pop('markerfacecolor', None)\r\n eb_lines_style.pop('markeredgewidth', None)\r\n eb_lines_style.pop('markeredgecolor', None)\r\n eb_cap_style.pop('ls', None)\r\n eb_cap_style['linestyle'] = 'none'\r\n if capsize is None:\r\n capsize = rcParams[\"errorbar.capsize\"]\r\n if capsize > 0:\r\n eb_cap_style['markersize'] = 2. * capsize\r\n if capthick is not None:\r\n eb_cap_style['markeredgewidth'] = capthick\r\n\r\n # For backwards-compat, allow explicit setting of\r\n # 'markeredgewidth' to over-ride capthick.\r\n for key in ('markeredgewidth', 'transform', 'alpha',\r\n 'zorder', 'rasterized'):\r\n if key in kwargs:\r\n eb_cap_style[key] = kwargs[key]\r\n eb_cap_style['color'] = ecolor\r\n\r\n data_line = None\r\n if plot_line:\r\n data_line = mlines.Line2D(x, y, **plot_line_style)\r\n self.add_line(data_line)\r\n\r\n barcols = []\r\n caplines = []\r\n\r\n # arrays fine here, they are booleans and hence not units\r\n lolims = np.broadcast_to(lolims, len(x)).astype(bool)\r\n uplims = np.broadcast_to(uplims, len(x)).astype(bool)\r\n xlolims = np.broadcast_to(xlolims, len(x)).astype(bool)\r\n xuplims = np.broadcast_to(xuplims, len(x)).astype(bool)\r\n\r\n everymask = np.zeros(len(x), bool)\r\n everymask[offset::errorevery] = True\r\n\r\n def apply_mask(arrays, mask):\r\n # Return, for each array in *arrays*, the elements for which *mask*\r\n # is True, without using fancy indexing.\r\n return [[*itertools.compress(array, mask)] for array in arrays]\r\n\r\n def extract_err(name, err, data, lolims, uplims):\r\n \"\"\"\r\n Private function to compute error bars.\r\n\r\n Parameters\r\n ----------\r\n name : {'x', 'y'}\r\n Name used in the error message.\r\n err : array-like\r\n xerr or yerr from errorbar().\r\n data : array-like\r\n x or y from errorbar().\r\n lolims : array-like\r\n Error is only applied on **upper** side when this is True. See\r\n the note in the main docstring about this parameter's name.\r\n uplims : array-like\r\n Error is only applied on **lower** side when this is True. See\r\n the note in the main docstring about this parameter's name.\r\n \"\"\"\r\n try: # Asymmetric error: pair of 1D iterables.\r\n a, b = err\r\n iter(a)\r\n iter(b)\r\n except (TypeError, ValueError):\r\n a = b = err # Symmetric error: 1D iterable.\r\n if np.ndim(a) > 1 or np.ndim(b) > 1:\r\n raise ValueError(\r\n f\"{name}err must be a scalar or a 1D or (2, n) array-like\")\r\n # Using list comprehensions rather than arrays to preserve units.\r\n for e in [a, b]:\r\n if len(data) != len(e):\r\n raise ValueError(\r\n f\"The lengths of the data ({len(data)}) and the \"\r\n f\"error {len(e)} do not match\")\r\n low = [v if lo else v - e for v, e, lo in zip(data, a, lolims)]\r\n high = [v if up else v + e for v, e, up in zip(data, b, uplims)]\r\n return low, high\r\n\r\n if xerr is not None:\r\n left, right = extract_err('x', xerr, x, xlolims, xuplims)\r\n barcols.append(self.hlines(\r\n *apply_mask([y, left, right], everymask), **eb_lines_style))\r\n # select points without upper/lower limits in x and\r\n # draw normal errorbars for these points\r\n noxlims = ~(xlolims | xuplims)\r\n if noxlims.any() and capsize > 0:\r\n yo, lo, ro = apply_mask([y, left, right], noxlims & everymask)\r\n caplines.extend([\r\n mlines.Line2D(lo, yo, marker='|', **eb_cap_style),\r\n mlines.Line2D(ro, yo, marker='|', **eb_cap_style)])\r\n if xlolims.any():\r\n xo, yo, lo, ro = apply_mask([x, y, left, right],\r\n xlolims & everymask)\r\n if self.xaxis_inverted():\r\n marker = mlines.CARETLEFTBASE\r\n else:\r\n marker = mlines.CARETRIGHTBASE\r\n caplines.append(mlines.Line2D(\r\n ro, yo, ls='None', marker=marker, **eb_cap_style))\r\n if capsize > 0:\r\n caplines.append(mlines.Line2D(\r\n xo, yo, marker='|', **eb_cap_style))\r\n if xuplims.any():\r\n xo, yo, lo, ro = apply_mask([x, y, left, right],\r\n xuplims & everymask)\r\n if self.xaxis_inverted():\r\n marker = mlines.CARETRIGHTBASE\r\n else:\r\n marker = mlines.CARETLEFTBASE\r\n caplines.append(mlines.Line2D(\r\n lo, yo, ls='None', marker=marker, **eb_cap_style))\r\n if capsize > 0:\r\n caplines.append(mlines.Line2D(\r\n xo, yo, marker='|', **eb_cap_style))\r\n\r\n if yerr is not None:\r\n lower, upper = extract_err('y', yerr, y, lolims, uplims)\r\n barcols.append(self.vlines(\r\n *apply_mask([x, lower, upper], everymask), **eb_lines_style))\r\n # select points without upper/lower limits in y and\r\n # draw normal errorbars for these points\r\n noylims = ~(lolims | uplims)\r\n if noylims.any() and capsize > 0:\r\n xo, lo, uo = apply_mask([x, lower, upper], noylims & everymask)\r\n caplines.extend([\r\n mlines.Line2D(xo, lo, marker='_', **eb_cap_style),\r\n mlines.Line2D(xo, uo, marker='_', **eb_cap_style)])\r\n if lolims.any():\r\n xo, yo, lo, uo = apply_mask([x, y, lower, upper],\r\n lolims & everymask)\r\n if self.yaxis_inverted():\r\n marker = mlines.CARETDOWNBASE\r\n else:\r\n marker = mlines.CARETUPBASE\r\n caplines.append(mlines.Line2D(\r\n xo, uo, ls='None', marker=marker, **eb_cap_style))\r\n if capsize > 0:\r\n caplines.append(mlines.Line2D(\r\n xo, yo, marker='_', **eb_cap_style))\r\n if uplims.any():\r\n xo, yo, lo, uo = apply_mask([x, y, lower, upper],\r\n uplims & everymask)\r\n if self.yaxis_inverted():\r\n marker = mlines.CARETUPBASE\r\n else:\r\n marker = mlines.CARETDOWNBASE\r\n caplines.append(mlines.Line2D(\r\n xo, lo, ls='None', marker=marker, **eb_cap_style))\r\n if capsize > 0:\r\n caplines.append(mlines.Line2D(\r\n xo, yo, marker='_', **eb_cap_style))\r\n\r\n for l in caplines:\r\n self.add_line(l)\r\n\r\n self._request_autoscale_view()\r\n errorbar_container = ErrorbarContainer(\r\n (data_line, tuple(caplines), tuple(barcols)),\r\n has_xerr=(xerr is not None), has_yerr=(yerr is not None),\r\n label=label)\r\n self.containers.append(errorbar_container)\r\n\r\n return errorbar_container # (l0, caplines, barcols)\r\n\r\n @_preprocess_data()\r\n def boxplot(self, x, notch=None, sym=None, vert=None, whis=None,\r\n positions=None, widths=None, patch_artist=None,\r\n bootstrap=None, usermedians=None, conf_intervals=None,\r\n meanline=None, showmeans=None, showcaps=None,\r\n showbox=None, showfliers=None, boxprops=None,\r\n labels=None, flierprops=None, medianprops=None,\r\n meanprops=None, capprops=None, whiskerprops=None,\r\n manage_ticks=True, autorange=False, zorder=None):\r\n \"\"\"\r\n Make a box and whisker plot.\r\n\r\n Make a box and whisker plot for each column of *x* or each\r\n vector in sequence *x*. The box extends from the lower to\r\n upper quartile values of the data, with a line at the median.\r\n The whiskers extend from the box to show the range of the\r\n data. Flier points are those past the end of the whiskers.\r\n\r\n Parameters\r\n ----------\r\n x : Array or a sequence of vectors.\r\n The input data.\r\n\r\n notch : bool, default: False\r\n Whether to draw a noteched box plot (`True`), or a rectangular box\r\n plot (`False`). The notches represent the confidence interval (CI)\r\n around the median. The documentation for *bootstrap* describes how\r\n the locations of the notches are computed.\r\n\r\n .. note::\r\n\r\n In cases where the values of the CI are less than the\r\n lower quartile or greater than the upper quartile, the\r\n notches will extend beyond the box, giving it a\r\n distinctive \"flipped\" appearance. This is expected\r\n behavior and consistent with other statistical\r\n visualization packages.\r\n\r\n sym : str, optional\r\n The default symbol for flier points. An empty string ('') hides\r\n the fliers. If `None`, then the fliers default to 'b+'. More\r\n control is provided by the *flierprops* parameter.\r\n\r\n vert : bool, default: True\r\n If `True`, draws vertical boxes.\r\n If `False`, draw horizontal boxes.\r\n\r\n whis : float or (float, float), default: 1.5\r\n The position of the whiskers.\r\n\r\n If a float, the lower whisker is at the lowest datum above\r\n ``Q1 - whis*(Q3-Q1)``, and the upper whisker at the highest datum\r\n below ``Q3 + whis*(Q3-Q1)``, where Q1 and Q3 are the first and\r\n third quartiles. The default value of ``whis = 1.5`` corresponds\r\n to Tukey's original definition of boxplots.\r\n\r\n If a pair of floats, they indicate the percentiles at which to\r\n draw the whiskers (e.g., (5, 95)). In particular, setting this to\r\n (0, 100) results in whiskers covering the whole range of the data.\r\n \"range\" is a deprecated synonym for (0, 100).\r\n\r\n In the edge case where ``Q1 == Q3``, *whis* is automatically set\r\n to (0, 100) (cover the whole range of the data) if *autorange* is\r\n True.\r\n\r\n Beyond the whiskers, data are considered outliers and are plotted\r\n as individual points.\r\n\r\n bootstrap : int, optional\r\n Specifies whether to bootstrap the confidence intervals\r\n around the median for notched boxplots. If *bootstrap* is\r\n None, no bootstrapping is performed, and notches are\r\n calculated using a Gaussian-based asymptotic approximation\r\n (see McGill, R., Tukey, J.W., and Larsen, W.A., 1978, and\r\n Kendall and Stuart, 1967). Otherwise, bootstrap specifies\r\n the number of times to bootstrap the median to determine its\r\n 95% confidence intervals. Values between 1000 and 10000 are\r\n recommended.\r\n\r\n usermedians : array-like, optional\r\n A 1D array-like of length ``len(x)``. Each entry that is not\r\n `None` forces the value of the median for the corresponding\r\n dataset. For entries that are `None`, the medians are computed\r\n by Matplotlib as normal.\r\n\r\n conf_intervals : array-like, optional\r\n A 2D array-like of shape ``(len(x), 2)``. Each entry that is not\r\n None forces the location of the corresponding notch (which is\r\n only drawn if *notch* is `True`). For entries that are `None`,\r\n the notches are computed by the method specified by the other\r\n parameters (e.g., *bootstrap*).\r\n\r\n positions : array-like, optional\r\n Sets the positions of the boxes. The ticks and limits are\r\n automatically set to match the positions. Defaults to\r\n ``range(1, N+1)`` where N is the number of boxes to be drawn.\r\n\r\n widths : float or array-like\r\n Sets the width of each box either with a scalar or a\r\n sequence. The default is 0.5, or ``0.15*(distance between\r\n extreme positions)``, if that is smaller.\r\n\r\n patch_artist : bool, default: False\r\n If `False` produces boxes with the Line2D artist. Otherwise,\r\n boxes and drawn with Patch artists.\r\n\r\n labels : sequence, optional\r\n Labels for each dataset (one per dataset).\r\n\r\n manage_ticks : bool, default: True\r\n If True, the tick locations and labels will be adjusted to match\r\n the boxplot positions.\r\n\r\n autorange : bool, default: False\r\n When `True` and the data are distributed such that the 25th and\r\n 75th percentiles are equal, *whis* is set to (0, 100) such\r\n that the whisker ends are at the minimum and maximum of the data.\r\n\r\n meanline : bool, default: False\r\n If `True` (and *showmeans* is `True`), will try to render the\r\n mean as a line spanning the full width of the box according to\r\n *meanprops* (see below). Not recommended if *shownotches* is also\r\n True. Otherwise, means will be shown as points.\r\n\r\n zorder : float, default: ``Line2D.zorder = 2``\r\n Sets the zorder of the boxplot.\r\n\r\n Returns\r\n -------\r\n dict\r\n A dictionary mapping each component of the boxplot to a list\r\n of the `.Line2D` instances created. That dictionary has the\r\n following keys (assuming vertical boxplots):\r\n\r\n - ``boxes``: the main body of the boxplot showing the\r\n quartiles and the median's confidence intervals if\r\n enabled.\r\n\r\n - ``medians``: horizontal lines at the median of each box.\r\n\r\n - ``whiskers``: the vertical lines extending to the most\r\n extreme, non-outlier data points.\r\n\r\n - ``caps``: the horizontal lines at the ends of the\r\n whiskers.\r\n\r\n - ``fliers``: points representing data that extend beyond\r\n the whiskers (fliers).\r\n\r\n - ``means``: points or lines representing the means.\r\n\r\n Other Parameters\r\n ----------------\r\n showcaps : bool, default: True\r\n Show the caps on the ends of whiskers.\r\n showbox : bool, default: True\r\n Show the central box.\r\n showfliers : bool, default: True\r\n Show the outliers beyond the caps.\r\n showmeans : bool, default: False\r\n Show the arithmetic means.\r\n capprops : dict, default: None\r\n The style of the caps.\r\n boxprops : dict, default: None\r\n The style of the box.\r\n whiskerprops : dict, default: None\r\n The style of the whiskers.\r\n flierprops : dict, default: None\r\n The style of the fliers.\r\n medianprops : dict, default: None\r\n The style of the median.\r\n meanprops : dict, default: None\r\n The style of the mean.\r\n\r\n \"\"\"\r\n\r\n # Missing arguments default to rcParams.\r\n if whis is None:\r\n whis = rcParams['boxplot.whiskers']\r\n if bootstrap is None:\r\n bootstrap = rcParams['boxplot.bootstrap']\r\n\r\n bxpstats = cbook.boxplot_stats(x, whis=whis, bootstrap=bootstrap,\r\n labels=labels, autorange=autorange)\r\n if notch is None:\r\n notch = rcParams['boxplot.notch']\r\n if vert is None:\r\n vert = rcParams['boxplot.vertical']\r\n if patch_artist is None:\r\n patch_artist = rcParams['boxplot.patchartist']\r\n if meanline is None:\r\n meanline = rcParams['boxplot.meanline']\r\n if showmeans is None:\r\n showmeans = rcParams['boxplot.showmeans']\r\n if showcaps is None:\r\n showcaps = rcParams['boxplot.showcaps']\r\n if showbox is None:\r\n showbox = rcParams['boxplot.showbox']\r\n if showfliers is None:\r\n showfliers = rcParams['boxplot.showfliers']\r\n\r\n if boxprops is None:\r\n boxprops = {}\r\n if whiskerprops is None:\r\n whiskerprops = {}\r\n if capprops is None:\r\n capprops = {}\r\n if medianprops is None:\r\n medianprops = {}\r\n if meanprops is None:\r\n meanprops = {}\r\n if flierprops is None:\r\n flierprops = {}\r\n\r\n if patch_artist:\r\n boxprops['linestyle'] = 'solid' # Not consistent with bxp.\r\n if 'color' in boxprops:\r\n boxprops['edgecolor'] = boxprops.pop('color')\r\n\r\n # if non-default sym value, put it into the flier dictionary\r\n # the logic for providing the default symbol ('b+') now lives\r\n # in bxp in the initial value of final_flierprops\r\n # handle all of the *sym* related logic here so we only have to pass\r\n # on the flierprops dict.\r\n if sym is not None:\r\n # no-flier case, which should really be done with\r\n # 'showfliers=False' but none-the-less deal with it to keep back\r\n # compatibility\r\n if sym == '':\r\n # blow away existing dict and make one for invisible markers\r\n flierprops = dict(linestyle='none', marker='', color='none')\r\n # turn the fliers off just to be safe\r\n showfliers = False\r\n # now process the symbol string\r\n else:\r\n # process the symbol string\r\n # discarded linestyle\r\n _, marker, color = _process_plot_format(sym)\r\n # if we have a marker, use it\r\n if marker is not None:\r\n flierprops['marker'] = marker\r\n # if we have a color, use it\r\n if color is not None:\r\n # assume that if color is passed in the user want\r\n # filled symbol, if the users want more control use\r\n # flierprops\r\n flierprops['color'] = color\r\n flierprops['markerfacecolor'] = color\r\n flierprops['markeredgecolor'] = color\r\n\r\n # replace medians if necessary:\r\n if usermedians is not None:\r\n if (len(np.ravel(usermedians)) != len(bxpstats) or\r\n np.shape(usermedians)[0] != len(bxpstats)):\r\n raise ValueError(\r\n \"'usermedians' and 'x' have different lengths\")\r\n else:\r\n # reassign medians as necessary\r\n for stats, med in zip(bxpstats, usermedians):\r\n if med is not None:\r\n stats['med'] = med\r\n\r\n if conf_intervals is not None:\r\n if len(conf_intervals) != len(bxpstats):\r\n raise ValueError(\r\n \"'conf_intervals' and 'x' have different lengths\")\r\n else:\r\n for stats, ci in zip(bxpstats, conf_intervals):\r\n if ci is not None:\r\n if len(ci) != 2:\r\n raise ValueError('each confidence interval must '\r\n 'have two values')\r\n else:\r\n if ci[0] is not None:\r\n stats['cilo'] = ci[0]\r\n if ci[1] is not None:\r\n stats['cihi'] = ci[1]\r\n\r\n artists = self.bxp(bxpstats, positions=positions, widths=widths,\r\n vert=vert, patch_artist=patch_artist,\r\n shownotches=notch, showmeans=showmeans,\r\n showcaps=showcaps, showbox=showbox,\r\n boxprops=boxprops, flierprops=flierprops,\r\n medianprops=medianprops, meanprops=meanprops,\r\n meanline=meanline, showfliers=showfliers,\r\n capprops=capprops, whiskerprops=whiskerprops,\r\n manage_ticks=manage_ticks, zorder=zorder)\r\n return artists\r\n\r\n def bxp(self, bxpstats, positions=None, widths=None, vert=True,\r\n patch_artist=False, shownotches=False, showmeans=False,\r\n showcaps=True, showbox=True, showfliers=True,\r\n boxprops=None, whiskerprops=None, flierprops=None,\r\n medianprops=None, capprops=None, meanprops=None,\r\n meanline=False, manage_ticks=True, zorder=None):\r\n \"\"\"\r\n Drawing function for box and whisker plots.\r\n\r\n Make a box and whisker plot for each column of *x* or each\r\n vector in sequence *x*. The box extends from the lower to\r\n upper quartile values of the data, with a line at the median.\r\n The whiskers extend from the box to show the range of the\r\n data. Flier points are those past the end of the whiskers.\r\n\r\n Parameters\r\n ----------\r\n bxpstats : list of dicts\r\n A list of dictionaries containing stats for each boxplot.\r\n Required keys are:\r\n\r\n - ``med``: The median (scalar float).\r\n\r\n - ``q1``: The first quartile (25th percentile) (scalar\r\n float).\r\n\r\n - ``q3``: The third quartile (75th percentile) (scalar\r\n float).\r\n\r\n - ``whislo``: Lower bound of the lower whisker (scalar\r\n float).\r\n\r\n - ``whishi``: Upper bound of the upper whisker (scalar\r\n float).\r\n\r\n Optional keys are:\r\n\r\n - ``mean``: The mean (scalar float). Needed if\r\n ``showmeans=True``.\r\n\r\n - ``fliers``: Data beyond the whiskers (sequence of floats).\r\n Needed if ``showfliers=True``.\r\n\r\n - ``cilo`` & ``cihi``: Lower and upper confidence intervals\r\n about the median. Needed if ``shownotches=True``.\r\n\r\n - ``label``: Name of the dataset (string). If available,\r\n this will be used a tick label for the boxplot\r\n\r\n positions : array-like, default: [1, 2, ..., n]\r\n Sets the positions of the boxes. The ticks and limits\r\n are automatically set to match the positions.\r\n\r\n widths : array-like, default: None\r\n Either a scalar or a vector and sets the width of each\r\n box. The default is ``0.15*(distance between extreme\r\n positions)``, clipped to no less than 0.15 and no more than\r\n 0.5.\r\n\r\n vert : bool, default: True\r\n If `True` (default), makes the boxes vertical. If `False`,\r\n makes horizontal boxes.\r\n\r\n patch_artist : bool, default: False\r\n If `False` produces boxes with the `.Line2D` artist.\r\n If `True` produces boxes with the `~matplotlib.patches.Patch` artist.\r\n\r\n shownotches : bool, default: False\r\n If `False` (default), produces a rectangular box plot.\r\n If `True`, will produce a notched box plot\r\n\r\n showmeans : bool, default: False\r\n If `True`, will toggle on the rendering of the means\r\n\r\n showcaps : bool, default: True\r\n If `True`, will toggle on the rendering of the caps\r\n\r\n showbox : bool, default: True\r\n If `True`, will toggle on the rendering of the box\r\n\r\n showfliers : bool, default: True\r\n If `True`, will toggle on the rendering of the fliers\r\n\r\n boxprops : dict or None (default)\r\n If provided, will set the plotting style of the boxes\r\n\r\n whiskerprops : dict or None (default)\r\n If provided, will set the plotting style of the whiskers\r\n\r\n capprops : dict or None (default)\r\n If provided, will set the plotting style of the caps\r\n\r\n flierprops : dict or None (default)\r\n If provided will set the plotting style of the fliers\r\n\r\n medianprops : dict or None (default)\r\n If provided, will set the plotting style of the medians\r\n\r\n meanprops : dict or None (default)\r\n If provided, will set the plotting style of the means\r\n\r\n meanline : bool, default: False\r\n If `True` (and *showmeans* is `True`), will try to render the mean\r\n as a line spanning the full width of the box according to\r\n *meanprops*. Not recommended if *shownotches* is also True.\r\n Otherwise, means will be shown as points.\r\n\r\n manage_ticks : bool, default: True\r\n If True, the tick locations and labels will be adjusted to match the\r\n boxplot positions.\r\n\r\n zorder : float, default: ``Line2D.zorder = 2``\r\n The zorder of the resulting boxplot.\r\n\r\n Returns\r\n -------\r\n dict\r\n A dictionary mapping each component of the boxplot to a list\r\n of the `.Line2D` instances created. That dictionary has the\r\n following keys (assuming vertical boxplots):\r\n\r\n - ``boxes``: the main body of the boxplot showing the\r\n quartiles and the median's confidence intervals if\r\n enabled.\r\n\r\n - ``medians``: horizontal lines at the median of each box.\r\n\r\n - ``whiskers``: the vertical lines extending to the most\r\n extreme, non-outlier data points.\r\n\r\n - ``caps``: the horizontal lines at the ends of the\r\n whiskers.\r\n\r\n - ``fliers``: points representing data that extend beyond\r\n the whiskers (fliers).\r\n\r\n - ``means``: points or lines representing the means.\r\n\r\n Examples\r\n --------\r\n .. plot:: gallery/statistics/bxp.py\r\n\r\n \"\"\"\r\n # lists of artists to be output\r\n whiskers = []\r\n caps = []\r\n boxes = []\r\n medians = []\r\n means = []\r\n fliers = []\r\n\r\n # empty list of xticklabels\r\n datalabels = []\r\n\r\n # Use default zorder if none specified\r\n if zorder is None:\r\n zorder = mlines.Line2D.zorder\r\n\r\n zdelta = 0.1\r\n\r\n def line_props_with_rcdefaults(subkey, explicit, zdelta=0,\r\n use_marker=True):\r\n d = {k.split('.')[-1]: v for k, v in rcParams.items()\r\n if k.startswith(f'boxplot.{subkey}')}\r\n d['zorder'] = zorder + zdelta\r\n if not use_marker:\r\n d['marker'] = ''\r\n if explicit is not None:\r\n d.update(cbook.normalize_kwargs(explicit, mlines.Line2D))\r\n return d\r\n\r\n # box properties\r\n if patch_artist:\r\n final_boxprops = dict(\r\n linestyle=rcParams['boxplot.boxprops.linestyle'],\r\n linewidth=rcParams['boxplot.boxprops.linewidth'],\r\n edgecolor=rcParams['boxplot.boxprops.color'],\r\n facecolor=('white' if rcParams['_internal.classic_mode'] else\r\n rcParams['patch.facecolor']),\r\n zorder=zorder,\r\n )\r\n if boxprops is not None:\r\n final_boxprops.update(\r\n cbook.normalize_kwargs(boxprops, mpatches.PathPatch))\r\n else:\r\n final_boxprops = line_props_with_rcdefaults('boxprops', boxprops,\r\n use_marker=False)\r\n final_whiskerprops = line_props_with_rcdefaults(\r\n 'whiskerprops', whiskerprops, use_marker=False)\r\n final_capprops = line_props_with_rcdefaults(\r\n 'capprops', capprops, use_marker=False)\r\n final_flierprops = line_props_with_rcdefaults(\r\n 'flierprops', flierprops)\r\n final_medianprops = line_props_with_rcdefaults(\r\n 'medianprops', medianprops, zdelta, use_marker=False)\r\n final_meanprops = line_props_with_rcdefaults(\r\n 'meanprops', meanprops, zdelta)\r\n removed_prop = 'marker' if meanline else 'linestyle'\r\n # Only remove the property if it's not set explicitly as a parameter.\r\n if meanprops is None or removed_prop not in meanprops:\r\n final_meanprops[removed_prop] = ''\r\n\r\n def patch_list(xs, ys, **kwargs):\r\n path = mpath.Path(\r\n # Last vertex will have a CLOSEPOLY code and thus be ignored.\r\n np.append(np.column_stack([xs, ys]), [(0, 0)], 0),\r\n closed=True)\r\n patch = mpatches.PathPatch(path, **kwargs)\r\n self.add_artist(patch)\r\n return [patch]\r\n\r\n # vertical or horizontal plot?\r\n if vert:\r\n def doplot(*args, **kwargs):\r\n return self.plot(*args, **kwargs)\r\n\r\n def dopatch(xs, ys, **kwargs):\r\n return patch_list(xs, ys, **kwargs)\r\n\r\n else:\r\n def doplot(*args, **kwargs):\r\n shuffled = []\r\n for i in range(0, len(args), 2):\r\n shuffled.extend([args[i + 1], args[i]])\r\n return self.plot(*shuffled, **kwargs)\r\n\r\n def dopatch(xs, ys, **kwargs):\r\n xs, ys = ys, xs # flip X, Y\r\n return patch_list(xs, ys, **kwargs)\r\n\r\n # input validation\r\n N = len(bxpstats)\r\n datashape_message = (\"List of boxplot statistics and `{0}` \"\r\n \"values must have same the length\")\r\n # check position\r\n if positions is None:\r\n positions = list(range(1, N + 1))\r\n elif len(positions) != N:\r\n raise ValueError(datashape_message.format(\"positions\"))\r\n\r\n positions = np.array(positions)\r\n if len(positions) > 0 and not isinstance(positions[0], Number):\r\n raise TypeError(\"positions should be an iterable of numbers\")\r\n\r\n # width\r\n if widths is None:\r\n widths = [np.clip(0.15 * np.ptp(positions), 0.15, 0.5)] * N\r\n elif np.isscalar(widths):\r\n widths = [widths] * N\r\n elif len(widths) != N:\r\n raise ValueError(datashape_message.format(\"widths\"))\r\n\r\n for pos, width, stats in zip(positions, widths, bxpstats):\r\n # try to find a new label\r\n datalabels.append(stats.get('label', pos))\r\n\r\n # whisker coords\r\n whisker_x = np.ones(2) * pos\r\n whiskerlo_y = np.array([stats['q1'], stats['whislo']])\r\n whiskerhi_y = np.array([stats['q3'], stats['whishi']])\r\n\r\n # cap coords\r\n cap_left = pos - width * 0.25\r\n cap_right = pos + width * 0.25\r\n cap_x = np.array([cap_left, cap_right])\r\n cap_lo = np.ones(2) * stats['whislo']\r\n cap_hi = np.ones(2) * stats['whishi']\r\n\r\n # box and median coords\r\n box_left = pos - width * 0.5\r\n box_right = pos + width * 0.5\r\n med_y = [stats['med'], stats['med']]\r\n\r\n # notched boxes\r\n if shownotches:\r\n box_x = [box_left, box_right, box_right, cap_right, box_right,\r\n box_right, box_left, box_left, cap_left, box_left,\r\n box_left]\r\n box_y = [stats['q1'], stats['q1'], stats['cilo'],\r\n stats['med'], stats['cihi'], stats['q3'],\r\n stats['q3'], stats['cihi'], stats['med'],\r\n stats['cilo'], stats['q1']]\r\n med_x = cap_x\r\n\r\n # plain boxes\r\n else:\r\n box_x = [box_left, box_right, box_right, box_left, box_left]\r\n box_y = [stats['q1'], stats['q1'], stats['q3'], stats['q3'],\r\n stats['q1']]\r\n med_x = [box_left, box_right]\r\n\r\n # maybe draw the box:\r\n if showbox:\r\n if patch_artist:\r\n boxes.extend(dopatch(box_x, box_y, **final_boxprops))\r\n else:\r\n boxes.extend(doplot(box_x, box_y, **final_boxprops))\r\n\r\n # draw the whiskers\r\n whiskers.extend(doplot(\r\n whisker_x, whiskerlo_y, **final_whiskerprops\r\n ))\r\n whiskers.extend(doplot(\r\n whisker_x, whiskerhi_y, **final_whiskerprops\r\n ))\r\n\r\n # maybe draw the caps:\r\n if showcaps:\r\n caps.extend(doplot(cap_x, cap_lo, **final_capprops))\r\n caps.extend(doplot(cap_x, cap_hi, **final_capprops))\r\n\r\n # draw the medians\r\n medians.extend(doplot(med_x, med_y, **final_medianprops))\r\n\r\n # maybe draw the means\r\n if showmeans:\r\n if meanline:\r\n means.extend(doplot(\r\n [box_left, box_right], [stats['mean'], stats['mean']],\r\n **final_meanprops\r\n ))\r\n else:\r\n means.extend(doplot(\r\n [pos], [stats['mean']], **final_meanprops\r\n ))\r\n\r\n # maybe draw the fliers\r\n if showfliers:\r\n # fliers coords\r\n flier_x = np.full(len(stats['fliers']), pos, dtype=np.float64)\r\n flier_y = stats['fliers']\r\n\r\n fliers.extend(doplot(\r\n flier_x, flier_y, **final_flierprops\r\n ))\r\n\r\n if manage_ticks:\r\n axis_name = \"x\" if vert else \"y\"\r\n interval = getattr(self.dataLim, f\"interval{axis_name}\")\r\n axis = getattr(self, f\"{axis_name}axis\")\r\n positions = axis.convert_units(positions)\r\n # The 0.5 additional padding ensures reasonable-looking boxes\r\n # even when drawing a single box. We set the sticky edge to\r\n # prevent margins expansion, in order to match old behavior (back\r\n # when separate calls to boxplot() would completely reset the axis\r\n # limits regardless of what was drawn before). The sticky edges\r\n # are attached to the median lines, as they are always present.\r\n interval[:] = (min(interval[0], min(positions) - .5),\r\n max(interval[1], max(positions) + .5))\r\n for median, position in zip(medians, positions):\r\n getattr(median.sticky_edges, axis_name).extend(\r\n [position - .5, position + .5])\r\n # Modified from Axis.set_ticks and Axis.set_ticklabels.\r\n locator = axis.get_major_locator()\r\n if not isinstance(axis.get_major_locator(),\r\n mticker.FixedLocator):\r\n locator = mticker.FixedLocator([])\r\n axis.set_major_locator(locator)\r\n locator.locs = np.array([*locator.locs, *positions])\r\n formatter = axis.get_major_formatter()\r\n if not isinstance(axis.get_major_formatter(),\r\n mticker.FixedFormatter):\r\n formatter = mticker.FixedFormatter([])\r\n axis.set_major_formatter(formatter)\r\n formatter.seq = [*formatter.seq, *datalabels]\r\n\r\n self._request_autoscale_view(\r\n scalex=self._autoscaleXon, scaley=self._autoscaleYon)\r\n\r\n return dict(whiskers=whiskers, caps=caps, boxes=boxes,\r\n medians=medians, fliers=fliers, means=means)\r\n\r\n @staticmethod\r\n def _parse_scatter_color_args(c, edgecolors, kwargs, xsize,\r\n get_next_color_func):\r\n \"\"\"\r\n Helper function to process color related arguments of `.Axes.scatter`.\r\n\r\n Argument precedence for facecolors:\r\n\r\n - c (if not None)\r\n - kwargs['facecolors']\r\n - kwargs['facecolor']\r\n - kwargs['color'] (==kwcolor)\r\n - 'b' if in classic mode else the result of ``get_next_color_func()``\r\n\r\n Argument precedence for edgecolors:\r\n\r\n - edgecolors (is an explicit kw argument in scatter())\r\n - kwargs['edgecolor']\r\n - kwargs['color'] (==kwcolor)\r\n - 'face' if not in classic mode else None\r\n\r\n Parameters\r\n ----------\r\n c : color or sequence or sequence of color or None\r\n See argument description of `.Axes.scatter`.\r\n edgecolors : color or sequence of color or {'face', 'none'} or None\r\n See argument description of `.Axes.scatter`.\r\n kwargs : dict\r\n Additional kwargs. If these keys exist, we pop and process them:\r\n 'facecolors', 'facecolor', 'edgecolor', 'color'\r\n Note: The dict is modified by this function.\r\n xsize : int\r\n The size of the x and y arrays passed to `.Axes.scatter`.\r\n get_next_color_func : callable\r\n A callable that returns a color. This color is used as facecolor\r\n if no other color is provided.\r\n\r\n Note, that this is a function rather than a fixed color value to\r\n support conditional evaluation of the next color. As of the\r\n current implementation obtaining the next color from the\r\n property cycle advances the cycle. This must only happen if we\r\n actually use the color, which will only be decided within this\r\n method.\r\n\r\n Returns\r\n -------\r\n c\r\n The input *c* if it was not *None*, else a color derived from the\r\n other inputs or defaults.\r\n colors : array(N, 4) or None\r\n The facecolors as RGBA values, or *None* if a colormap is used.\r\n edgecolors\r\n The edgecolor.\r\n\r\n \"\"\"\r\n facecolors = kwargs.pop('facecolors', None)\r\n facecolors = kwargs.pop('facecolor', facecolors)\r\n edgecolors = kwargs.pop('edgecolor', edgecolors)\r\n\r\n kwcolor = kwargs.pop('color', None)\r\n\r\n if kwcolor is not None and c is not None:\r\n raise ValueError(\"Supply a 'c' argument or a 'color'\"\r\n \" kwarg but not both; they differ but\"\r\n \" their functionalities overlap.\")\r\n\r\n if kwcolor is not None:\r\n try:\r\n mcolors.to_rgba_array(kwcolor)\r\n except ValueError as err:\r\n raise ValueError(\r\n \"'color' kwarg must be an color or sequence of color \"\r\n \"specs. For a sequence of values to be color-mapped, use \"\r\n \"the 'c' argument instead.\") from err\r\n if edgecolors is None:\r\n edgecolors = kwcolor\r\n if facecolors is None:\r\n facecolors = kwcolor\r\n\r\n if edgecolors is None and not rcParams['_internal.classic_mode']:\r\n edgecolors = rcParams['scatter.edgecolors']\r\n\r\n c_was_none = c is None\r\n if c is None:\r\n c = (facecolors if facecolors is not None\r\n else \"b\" if rcParams['_internal.classic_mode']\r\n else get_next_color_func())\r\n c_is_string_or_strings = (\r\n isinstance(c, str)\r\n or (np.iterable(c) and len(c) > 0\r\n and isinstance(cbook.safe_first_element(c), str)))\r\n\r\n def invalid_shape_exception(csize, xsize):\r\n return ValueError(\r\n f\"'c' argument has {csize} elements, which is inconsistent \"\r\n f\"with 'x' and 'y' with size {xsize}.\")\r\n\r\n c_is_mapped = False # Unless proven otherwise below.\r\n valid_shape = True # Unless proven otherwise below.\r\n if not c_was_none and kwcolor is None and not c_is_string_or_strings:\r\n try: # First, does 'c' look suitable for value-mapping?\r\n c = np.asanyarray(c, dtype=float)\r\n except ValueError:\r\n pass # Failed to convert to float array; must be color specs.\r\n else:\r\n # handle the documented special case of a 2D array with 1\r\n # row which as RGB(A) to broadcast.\r\n if c.shape == (1, 4) or c.shape == (1, 3):\r\n c_is_mapped = False\r\n if c.size != xsize:\r\n valid_shape = False\r\n # If c can be either mapped values or a RGB(A) color, prefer\r\n # the former if shapes match, the latter otherwise.\r\n elif c.size == xsize:\r\n c = c.ravel()\r\n c_is_mapped = True\r\n else: # Wrong size; it must not be intended for mapping.\r\n if c.shape in ((3,), (4,)):\r\n _log.warning(\r\n \"*c* argument looks like a single numeric RGB or \"\r\n \"RGBA sequence, which should be avoided as value-\"\r\n \"mapping will have precedence in case its length \"\r\n \"matches with *x* & *y*. Please use the *color* \"\r\n \"keyword-argument or provide a 2-D array \"\r\n \"with a single row if you intend to specify \"\r\n \"the same RGB or RGBA value for all points.\")\r\n valid_shape = False\r\n if not c_is_mapped:\r\n try: # Is 'c' acceptable as PathCollection facecolors?\r\n colors = mcolors.to_rgba_array(c)\r\n except (TypeError, ValueError) as err:\r\n if \"RGBA values should be within 0-1 range\" in str(err):\r\n raise\r\n else:\r\n if not valid_shape:\r\n raise invalid_shape_exception(c.size, xsize) from err\r\n # Both the mapping *and* the RGBA conversion failed: pretty\r\n # severe failure => one may appreciate a verbose feedback.\r\n raise ValueError(\r\n f\"'c' argument must be a color, a sequence of colors, \"\r\n f\"or a sequence of numbers, not {c}\") from err\r\n else:\r\n if len(colors) not in (0, 1, xsize):\r\n # NB: remember that a single color is also acceptable.\r\n # Besides *colors* will be an empty array if c == 'none'.\r\n raise invalid_shape_exception(len(colors), xsize)\r\n else:\r\n colors = None # use cmap, norm after collection is created\r\n return c, colors, edgecolors\r\n\r\n @_preprocess_data(replace_names=[\"x\", \"y\", \"s\", \"linewidths\",\r\n \"edgecolors\", \"c\", \"facecolor\",\r\n \"facecolors\", \"color\"],\r\n label_namer=\"y\")\r\n @cbook._delete_parameter(\"3.2\", \"verts\")\r\n def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None,\r\n vmin=None, vmax=None, alpha=None, linewidths=None,\r\n verts=None, edgecolors=None, *, plotnonfinite=False,\r\n **kwargs):\r\n \"\"\"\r\n A scatter plot of *y* vs. *x* with varying marker size and/or color.\r\n\r\n Parameters\r\n ----------\r\n x, y : float or array-like, shape (n, )\r\n The data positions.\r\n\r\n s : float or array-like, shape (n, ), optional\r\n The marker size in points**2.\r\n Default is ``rcParams['lines.markersize'] ** 2``.\r\n\r\n c : array-like or list of colors or color, optional\r\n The marker colors. Possible values:\r\n\r\n - A scalar or sequence of n numbers to be mapped to colors using\r\n *cmap* and *norm*.\r\n - A 2-D array in which the rows are RGB or RGBA.\r\n - A sequence of colors of length n.\r\n - A single color format string.\r\n\r\n Note that *c* should not be a single numeric RGB or RGBA sequence\r\n because that is indistinguishable from an array of values to be\r\n colormapped. If you want to specify the same RGB or RGBA value for\r\n all points, use a 2-D array with a single row. Otherwise, value-\r\n matching will have precedence in case of a size matching with *x*\r\n and *y*.\r\n\r\n If you wish to specify a single color for all points\r\n prefer the *color* keyword argument.\r\n\r\n Defaults to `None`. In that case the marker color is determined\r\n by the value of *color*, *facecolor* or *facecolors*. In case\r\n those are not specified or `None`, the marker color is determined\r\n by the next color of the ``Axes``' current \"shape and fill\" color\r\n cycle. This cycle defaults to :rc:`axes.prop_cycle`.\r\n\r\n marker : `~.markers.MarkerStyle`, default: :rc:`scatter.marker`\r\n The marker style. *marker* can be either an instance of the class\r\n or the text shorthand for a particular marker.\r\n See :mod:`matplotlib.markers` for more information about marker\r\n styles.\r\n\r\n cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`\r\n A `.Colormap` instance or registered colormap name. *cmap* is only\r\n used if *c* is an array of floats.\r\n\r\n norm : `~matplotlib.colors.Normalize`, default: None\r\n If *c* is an array of floats, *norm* is used to scale the color\r\n data, *c*, in the range 0 to 1, in order to map into the colormap\r\n *cmap*.\r\n If *None*, use the default `.colors.Normalize`.\r\n\r\n vmin, vmax : float, default: None\r\n *vmin* and *vmax* are used in conjunction with the default norm to\r\n map the color array *c* to the colormap *cmap*. If None, the\r\n respective min and max of the color array is used.\r\n It is deprecated to use *vmin*/*vmax* when *norm* is given.\r\n\r\n alpha : float, default: None\r\n The alpha blending value, between 0 (transparent) and 1 (opaque).\r\n\r\n linewidths : float or array-like, default: :rc:`lines.linewidth`\r\n The linewidth of the marker edges. Note: The default *edgecolors*\r\n is 'face'. You may want to change this as well.\r\n\r\n edgecolors : {'face', 'none', *None*} or color or sequence of color, \\\r\ndefault: :rc:`scatter.edgecolors`\r\n The edge color of the marker. Possible values:\r\n\r\n - 'face': The edge color will always be the same as the face color.\r\n - 'none': No patch boundary will be drawn.\r\n - A color or sequence of colors.\r\n\r\n For non-filled markers, the *edgecolors* kwarg is ignored and\r\n forced to 'face' internally.\r\n\r\n plotnonfinite : bool, default: False\r\n Set to plot points with nonfinite *c*, in conjunction with\r\n `~matplotlib.colors.Colormap.set_bad`.\r\n\r\n Returns\r\n -------\r\n `~matplotlib.collections.PathCollection`\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs : `~matplotlib.collections.Collection` properties\r\n\r\n See Also\r\n --------\r\n plot : To plot scatter plots when markers are identical in size and\r\n color.\r\n\r\n Notes\r\n -----\r\n * The `.plot` function will be faster for scatterplots where markers\r\n don't vary in size or color.\r\n\r\n * Any or all of *x*, *y*, *s*, and *c* may be masked arrays, in which\r\n case all masks will be combined and only unmasked points will be\r\n plotted.\r\n\r\n * Fundamentally, scatter works with 1-D arrays; *x*, *y*, *s*, and *c*\r\n may be input as N-D arrays, but within scatter they will be\r\n flattened. The exception is *c*, which will be flattened only if its\r\n size matches the size of *x* and *y*.\r\n\r\n \"\"\"\r\n # Process **kwargs to handle aliases, conflicts with explicit kwargs:\r\n\r\n self._process_unit_info(xdata=x, ydata=y, kwargs=kwargs)\r\n x = self.convert_xunits(x)\r\n y = self.convert_yunits(y)\r\n\r\n # np.ma.ravel yields an ndarray, not a masked array,\r\n # unless its argument is a masked array.\r\n x = np.ma.ravel(x)\r\n y = np.ma.ravel(y)\r\n if x.size != y.size:\r\n raise ValueError(\"x and y must be the same size\")\r\n\r\n if s is None:\r\n s = (20 if rcParams['_internal.classic_mode'] else\r\n rcParams['lines.markersize'] ** 2.0)\r\n s = np.ma.ravel(s)\r\n if len(s) not in (1, x.size):\r\n raise ValueError(\"s must be a scalar, or the same size as x and y\")\r\n\r\n c, colors, edgecolors = \\\r\n self._parse_scatter_color_args(\r\n c, edgecolors, kwargs, x.size,\r\n get_next_color_func=self._get_patches_for_fill.get_next_color)\r\n\r\n if plotnonfinite and colors is None:\r\n c = np.ma.masked_invalid(c)\r\n x, y, s, edgecolors, linewidths = \\\r\n cbook._combine_masks(x, y, s, edgecolors, linewidths)\r\n else:\r\n x, y, s, c, colors, edgecolors, linewidths = \\\r\n cbook._combine_masks(\r\n x, y, s, c, colors, edgecolors, linewidths)\r\n\r\n scales = s # Renamed for readability below.\r\n\r\n # load default marker from rcParams\r\n if marker is None:\r\n marker = rcParams['scatter.marker']\r\n\r\n if isinstance(marker, mmarkers.MarkerStyle):\r\n marker_obj = marker\r\n else:\r\n marker_obj = mmarkers.MarkerStyle(marker)\r\n\r\n path = marker_obj.get_path().transformed(\r\n marker_obj.get_transform())\r\n if not marker_obj.is_filled():\r\n edgecolors = 'face'\r\n if linewidths is None:\r\n linewidths = rcParams['lines.linewidth']\r\n elif np.iterable(linewidths):\r\n linewidths = [\r\n lw if lw is not None else rcParams['lines.linewidth']\r\n for lw in linewidths]\r\n\r\n offsets = np.ma.column_stack([x, y])\r\n\r\n collection = mcoll.PathCollection(\r\n (path,), scales,\r\n facecolors=colors,\r\n edgecolors=edgecolors,\r\n linewidths=linewidths,\r\n offsets=offsets,\r\n transOffset=kwargs.pop('transform', self.transData),\r\n alpha=alpha\r\n )\r\n collection.set_transform(mtransforms.IdentityTransform())\r\n collection.update(kwargs)\r\n\r\n if colors is None:\r\n collection.set_array(c)\r\n collection.set_cmap(cmap)\r\n collection.set_norm(norm)\r\n collection._scale_norm(norm, vmin, vmax)\r\n\r\n # Classic mode only:\r\n # ensure there are margins to allow for the\r\n # finite size of the symbols. In v2.x, margins\r\n # are present by default, so we disable this\r\n # scatter-specific override.\r\n if rcParams['_internal.classic_mode']:\r\n if self._xmargin < 0.05 and x.size > 0:\r\n self.set_xmargin(0.05)\r\n if self._ymargin < 0.05 and x.size > 0:\r\n self.set_ymargin(0.05)\r\n\r\n self.add_collection(collection)\r\n self._request_autoscale_view()\r\n\r\n return collection\r\n\r\n @_preprocess_data(replace_names=[\"x\", \"y\"], label_namer=\"y\")\r\n @docstring.dedent_interpd\r\n def hexbin(self, x, y, C=None, gridsize=100, bins=None,\r\n xscale='linear', yscale='linear', extent=None,\r\n cmap=None, norm=None, vmin=None, vmax=None,\r\n alpha=None, linewidths=None, edgecolors='face',\r\n reduce_C_function=np.mean, mincnt=None, marginals=False,\r\n **kwargs):\r\n \"\"\"\r\n Make a 2D hexagonal binning plot of points *x*, *y*.\r\n\r\n If *C* is *None*, the value of the hexagon is determined by the number\r\n of points in the hexagon. Otherwise, *C* specifies values at the\r\n coordinate (x[i], y[i]). For each hexagon, these values are reduced\r\n using *reduce_C_function*.\r\n\r\n Parameters\r\n ----------\r\n x, y : array-like\r\n The data positions. *x* and *y* must be of the same length.\r\n\r\n C : array-like, optional\r\n If given, these values are accumulated in the bins. Otherwise,\r\n every point has a value of 1. Must be of the same length as *x*\r\n and *y*.\r\n\r\n gridsize : int or (int, int), default: 100\r\n If a single int, the number of hexagons in the *x*-direction.\r\n The number of hexagons in the *y*-direction is chosen such that\r\n the hexagons are approximately regular.\r\n\r\n Alternatively, if a tuple (*nx*, *ny*), the number of hexagons\r\n in the *x*-direction and the *y*-direction.\r\n\r\n bins : 'log' or int or sequence, default: None\r\n Discretization of the hexagon values.\r\n\r\n - If *None*, no binning is applied; the color of each hexagon\r\n directly corresponds to its count value.\r\n - If 'log', use a logarithmic scale for the color map.\r\n Internally, :math:`log_{10}(i+1)` is used to determine the\r\n hexagon color. This is equivalent to ``norm=LogNorm()``.\r\n - If an integer, divide the counts in the specified number\r\n of bins, and color the hexagons accordingly.\r\n - If a sequence of values, the values of the lower bound of\r\n the bins to be used.\r\n\r\n xscale : {'linear', 'log'}, default: 'linear'\r\n Use a linear or log10 scale on the horizontal axis.\r\n\r\n yscale : {'linear', 'log'}, default: 'linear'\r\n Use a linear or log10 scale on the vertical axis.\r\n\r\n mincnt : int > 0, default: *None*\r\n If not *None*, only display cells with more than *mincnt*\r\n number of points in the cell.\r\n\r\n marginals : bool, default: *False*\r\n If marginals is *True*, plot the marginal density as\r\n colormapped rectangles along the bottom of the x-axis and\r\n left of the y-axis.\r\n\r\n extent : float, default: *None*\r\n The limits of the bins. The default assigns the limits\r\n based on *gridsize*, *x*, *y*, *xscale* and *yscale*.\r\n\r\n If *xscale* or *yscale* is set to 'log', the limits are\r\n expected to be the exponent for a power of 10. E.g. for\r\n x-limits of 1 and 50 in 'linear' scale and y-limits\r\n of 10 and 1000 in 'log' scale, enter (1, 50, 1, 3).\r\n\r\n Order of scalars is (left, right, bottom, top).\r\n\r\n Returns\r\n -------\r\n `~matplotlib.collections.PolyCollection`\r\n A `.PolyCollection` defining the hexagonal bins.\r\n\r\n - `.PolyCollection.get_offsets` contains a Mx2 array containing\r\n the x, y positions of the M hexagon centers.\r\n - `.PolyCollection.get_array` contains the values of the M\r\n hexagons.\r\n\r\n If *marginals* is *True*, horizontal\r\n bar and vertical bar (both PolyCollections) will be attached\r\n to the return collection as attributes *hbar* and *vbar*.\r\n\r\n Other Parameters\r\n ----------------\r\n cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`\r\n The Colormap instance or registered colormap name used to map\r\n the bin values to colors.\r\n\r\n norm : `~matplotlib.colors.Normalize`, optional\r\n The Normalize instance scales the bin values to the canonical\r\n colormap range [0, 1] for mapping to colors. By default, the data\r\n range is mapped to the colorbar range using linear scaling.\r\n\r\n vmin, vmax : float, default: None\r\n The colorbar range. If *None*, suitable min/max values are\r\n automatically chosen by the `~.Normalize` instance (defaults to\r\n the respective min/max values of the bins in case of the default\r\n linear scaling).\r\n It is deprecated to use *vmin*/*vmax* when *norm* is given.\r\n\r\n alpha : float between 0 and 1, optional\r\n The alpha blending value, between 0 (transparent) and 1 (opaque).\r\n\r\n linewidths : float, default: *None*\r\n If *None*, defaults to 1.0.\r\n\r\n edgecolors : {'face', 'none', *None*} or color, default: 'face'\r\n The color of the hexagon edges. Possible values are:\r\n\r\n - 'face': Draw the edges in the same color as the fill color.\r\n - 'none': No edges are drawn. This can sometimes lead to unsightly\r\n unpainted pixels between the hexagons.\r\n - *None*: Draw outlines in the default color.\r\n - An explicit color.\r\n\r\n reduce_C_function : callable, default: `numpy.mean`\r\n The function to aggregate *C* within the bins. It is ignored if\r\n *C* is not given. This must have the signature::\r\n\r\n def reduce_C_function(C: array) -> float\r\n\r\n Commonly used functions are:\r\n\r\n - `numpy.mean`: average of the points\r\n - `numpy.sum`: integral of the point values\r\n - `numpy.max`: value taken from the largest point\r\n\r\n **kwargs : `~matplotlib.collections.PolyCollection` properties\r\n All other keyword arguments are passed on to `.PolyCollection`:\r\n\r\n %(PolyCollection)s\r\n\r\n \"\"\"\r\n self._process_unit_info(xdata=x, ydata=y, kwargs=kwargs)\r\n\r\n x, y, C = cbook.delete_masked_points(x, y, C)\r\n\r\n # Set the size of the hexagon grid\r\n if np.iterable(gridsize):\r\n nx, ny = gridsize\r\n else:\r\n nx = gridsize\r\n ny = int(nx / math.sqrt(3))\r\n # Count the number of data in each hexagon\r\n x = np.array(x, float)\r\n y = np.array(y, float)\r\n if xscale == 'log':\r\n if np.any(x <= 0.0):\r\n raise ValueError(\"x contains non-positive values, so can not\"\r\n \" be log-scaled\")\r\n x = np.log10(x)\r\n if yscale == 'log':\r\n if np.any(y <= 0.0):\r\n raise ValueError(\"y contains non-positive values, so can not\"\r\n \" be log-scaled\")\r\n y = np.log10(y)\r\n if extent is not None:\r\n xmin, xmax, ymin, ymax = extent\r\n else:\r\n xmin, xmax = (np.min(x), np.max(x)) if len(x) else (0, 1)\r\n ymin, ymax = (np.min(y), np.max(y)) if len(y) else (0, 1)\r\n\r\n # to avoid issues with singular data, expand the min/max pairs\r\n xmin, xmax = mtransforms.nonsingular(xmin, xmax, expander=0.1)\r\n ymin, ymax = mtransforms.nonsingular(ymin, ymax, expander=0.1)\r\n\r\n # In the x-direction, the hexagons exactly cover the region from\r\n # xmin to xmax. Need some padding to avoid roundoff errors.\r\n padding = 1.e-9 * (xmax - xmin)\r\n xmin -= padding\r\n xmax += padding\r\n sx = (xmax - xmin) / nx\r\n sy = (ymax - ymin) / ny\r\n\r\n if marginals:\r\n xorig = x.copy()\r\n yorig = y.copy()\r\n\r\n x = (x - xmin) / sx\r\n y = (y - ymin) / sy\r\n ix1 = np.round(x).astype(int)\r\n iy1 = np.round(y).astype(int)\r\n ix2 = np.floor(x).astype(int)\r\n iy2 = np.floor(y).astype(int)\r\n\r\n nx1 = nx + 1\r\n ny1 = ny + 1\r\n nx2 = nx\r\n ny2 = ny\r\n n = nx1 * ny1 + nx2 * ny2\r\n\r\n d1 = (x - ix1) ** 2 + 3.0 * (y - iy1) ** 2\r\n d2 = (x - ix2 - 0.5) ** 2 + 3.0 * (y - iy2 - 0.5) ** 2\r\n bdist = (d1 < d2)\r\n if C is None:\r\n lattice1 = np.zeros((nx1, ny1))\r\n lattice2 = np.zeros((nx2, ny2))\r\n c1 = (0 <= ix1) & (ix1 < nx1) & (0 <= iy1) & (iy1 < ny1) & bdist\r\n c2 = (0 <= ix2) & (ix2 < nx2) & (0 <= iy2) & (iy2 < ny2) & ~bdist\r\n np.add.at(lattice1, (ix1[c1], iy1[c1]), 1)\r\n np.add.at(lattice2, (ix2[c2], iy2[c2]), 1)\r\n if mincnt is not None:\r\n lattice1[lattice1 < mincnt] = np.nan\r\n lattice2[lattice2 < mincnt] = np.nan\r\n accum = np.concatenate([lattice1.ravel(), lattice2.ravel()])\r\n good_idxs = ~np.isnan(accum)\r\n\r\n else:\r\n if mincnt is None:\r\n mincnt = 0\r\n\r\n # create accumulation arrays\r\n lattice1 = np.empty((nx1, ny1), dtype=object)\r\n for i in range(nx1):\r\n for j in range(ny1):\r\n lattice1[i, j] = []\r\n lattice2 = np.empty((nx2, ny2), dtype=object)\r\n for i in range(nx2):\r\n for j in range(ny2):\r\n lattice2[i, j] = []\r\n\r\n for i in range(len(x)):\r\n if bdist[i]:\r\n if 0 <= ix1[i] < nx1 and 0 <= iy1[i] < ny1:\r\n lattice1[ix1[i], iy1[i]].append(C[i])\r\n else:\r\n if 0 <= ix2[i] < nx2 and 0 <= iy2[i] < ny2:\r\n lattice2[ix2[i], iy2[i]].append(C[i])\r\n\r\n for i in range(nx1):\r\n for j in range(ny1):\r\n vals = lattice1[i, j]\r\n if len(vals) > mincnt:\r\n lattice1[i, j] = reduce_C_function(vals)\r\n else:\r\n lattice1[i, j] = np.nan\r\n for i in range(nx2):\r\n for j in range(ny2):\r\n vals = lattice2[i, j]\r\n if len(vals) > mincnt:\r\n lattice2[i, j] = reduce_C_function(vals)\r\n else:\r\n lattice2[i, j] = np.nan\r\n\r\n accum = np.hstack((lattice1.astype(float).ravel(),\r\n lattice2.astype(float).ravel()))\r\n good_idxs = ~np.isnan(accum)\r\n\r\n offsets = np.zeros((n, 2), float)\r\n offsets[:nx1 * ny1, 0] = np.repeat(np.arange(nx1), ny1)\r\n offsets[:nx1 * ny1, 1] = np.tile(np.arange(ny1), nx1)\r\n offsets[nx1 * ny1:, 0] = np.repeat(np.arange(nx2) + 0.5, ny2)\r\n offsets[nx1 * ny1:, 1] = np.tile(np.arange(ny2), nx2) + 0.5\r\n offsets[:, 0] *= sx\r\n offsets[:, 1] *= sy\r\n offsets[:, 0] += xmin\r\n offsets[:, 1] += ymin\r\n # remove accumulation bins with no data\r\n offsets = offsets[good_idxs, :]\r\n accum = accum[good_idxs]\r\n\r\n polygon = [sx, sy / 3] * np.array(\r\n [[.5, -.5], [.5, .5], [0., 1.], [-.5, .5], [-.5, -.5], [0., -1.]])\r\n\r\n if linewidths is None:\r\n linewidths = [1.0]\r\n\r\n if xscale == 'log' or yscale == 'log':\r\n polygons = np.expand_dims(polygon, 0) + np.expand_dims(offsets, 1)\r\n if xscale == 'log':\r\n polygons[:, :, 0] = 10.0 ** polygons[:, :, 0]\r\n xmin = 10.0 ** xmin\r\n xmax = 10.0 ** xmax\r\n self.set_xscale(xscale)\r\n if yscale == 'log':\r\n polygons[:, :, 1] = 10.0 ** polygons[:, :, 1]\r\n ymin = 10.0 ** ymin\r\n ymax = 10.0 ** ymax\r\n self.set_yscale(yscale)\r\n collection = mcoll.PolyCollection(\r\n polygons,\r\n edgecolors=edgecolors,\r\n linewidths=linewidths,\r\n )\r\n else:\r\n collection = mcoll.PolyCollection(\r\n [polygon],\r\n edgecolors=edgecolors,\r\n linewidths=linewidths,\r\n offsets=offsets,\r\n transOffset=mtransforms.AffineDeltaTransform(self.transData),\r\n )\r\n\r\n # Set normalizer if bins is 'log'\r\n if bins == 'log':\r\n if norm is not None:\r\n cbook._warn_external(\"Only one of 'bins' and 'norm' \"\r\n \"arguments can be supplied, ignoring \"\r\n \"bins={}\".format(bins))\r\n else:\r\n norm = mcolors.LogNorm()\r\n bins = None\r\n\r\n if isinstance(norm, mcolors.LogNorm):\r\n if (accum == 0).any():\r\n # make sure we have no zeros\r\n accum += 1\r\n\r\n # autoscale the norm with curren accum values if it hasn't\r\n # been set\r\n if norm is not None:\r\n if norm.vmin is None and norm.vmax is None:\r\n norm.autoscale(accum)\r\n\r\n if bins is not None:\r\n if not np.iterable(bins):\r\n minimum, maximum = min(accum), max(accum)\r\n bins -= 1 # one less edge than bins\r\n bins = minimum + (maximum - minimum) * np.arange(bins) / bins\r\n bins = np.sort(bins)\r\n accum = bins.searchsorted(accum)\r\n\r\n collection.set_array(accum)\r\n collection.set_cmap(cmap)\r\n collection.set_norm(norm)\r\n collection.set_alpha(alpha)\r\n collection.update(kwargs)\r\n collection._scale_norm(norm, vmin, vmax)\r\n\r\n corners = ((xmin, ymin), (xmax, ymax))\r\n self.update_datalim(corners)\r\n self._request_autoscale_view(tight=True)\r\n\r\n # add the collection last\r\n self.add_collection(collection, autolim=False)\r\n if not marginals:\r\n return collection\r\n\r\n if C is None:\r\n C = np.ones(len(x))\r\n\r\n def coarse_bin(x, y, coarse):\r\n ind = coarse.searchsorted(x).clip(0, len(coarse) - 1)\r\n mus = np.zeros(len(coarse))\r\n for i in range(len(coarse)):\r\n yi = y[ind == i]\r\n if len(yi) > 0:\r\n mu = reduce_C_function(yi)\r\n else:\r\n mu = np.nan\r\n mus[i] = mu\r\n return mus\r\n\r\n coarse = np.linspace(xmin, xmax, gridsize)\r\n\r\n xcoarse = coarse_bin(xorig, C, coarse)\r\n valid = ~np.isnan(xcoarse)\r\n verts, values = [], []\r\n for i, val in enumerate(xcoarse):\r\n thismin = coarse[i]\r\n if i < len(coarse) - 1:\r\n thismax = coarse[i + 1]\r\n else:\r\n thismax = thismin + np.diff(coarse)[-1]\r\n\r\n if not valid[i]:\r\n continue\r\n\r\n verts.append([(thismin, 0),\r\n (thismin, 0.05),\r\n (thismax, 0.05),\r\n (thismax, 0)])\r\n values.append(val)\r\n\r\n values = np.array(values)\r\n trans = self.get_xaxis_transform(which='grid')\r\n\r\n hbar = mcoll.PolyCollection(verts, transform=trans, edgecolors='face')\r\n\r\n hbar.set_array(values)\r\n hbar.set_cmap(cmap)\r\n hbar.set_norm(norm)\r\n hbar.set_alpha(alpha)\r\n hbar.update(kwargs)\r\n self.add_collection(hbar, autolim=False)\r\n\r\n coarse = np.linspace(ymin, ymax, gridsize)\r\n ycoarse = coarse_bin(yorig, C, coarse)\r\n valid = ~np.isnan(ycoarse)\r\n verts, values = [], []\r\n for i, val in enumerate(ycoarse):\r\n thismin = coarse[i]\r\n if i < len(coarse) - 1:\r\n thismax = coarse[i + 1]\r\n else:\r\n thismax = thismin + np.diff(coarse)[-1]\r\n if not valid[i]:\r\n continue\r\n verts.append([(0, thismin), (0.0, thismax),\r\n (0.05, thismax), (0.05, thismin)])\r\n values.append(val)\r\n\r\n values = np.array(values)\r\n\r\n trans = self.get_yaxis_transform(which='grid')\r\n\r\n vbar = mcoll.PolyCollection(verts, transform=trans, edgecolors='face')\r\n vbar.set_array(values)\r\n vbar.set_cmap(cmap)\r\n vbar.set_norm(norm)\r\n vbar.set_alpha(alpha)\r\n vbar.update(kwargs)\r\n self.add_collection(vbar, autolim=False)\r\n\r\n collection.hbar = hbar\r\n collection.vbar = vbar\r\n\r\n def on_changed(collection):\r\n hbar.set_cmap(collection.get_cmap())\r\n hbar.set_clim(collection.get_clim())\r\n vbar.set_cmap(collection.get_cmap())\r\n vbar.set_clim(collection.get_clim())\r\n\r\n collection.callbacksSM.connect('changed', on_changed)\r\n\r\n return collection\r\n\r\n @docstring.dedent_interpd\r\n def arrow(self, x, y, dx, dy, **kwargs):\r\n \"\"\"\r\n Add an arrow to the axes.\r\n\r\n This draws an arrow from ``(x, y)`` to ``(x+dx, y+dy)``.\r\n\r\n Parameters\r\n ----------\r\n x, y : float\r\n The x and y coordinates of the arrow base.\r\n\r\n dx, dy : float\r\n The length of the arrow along x and y direction.\r\n\r\n %(FancyArrow)s\r\n\r\n Returns\r\n -------\r\n `.FancyArrow`\r\n The created `.FancyArrow` object.\r\n\r\n Notes\r\n -----\r\n The resulting arrow is affected by the axes aspect ratio and limits.\r\n This may produce an arrow whose head is not square with its stem. To\r\n create an arrow whose head is square with its stem,\r\n use :meth:`annotate` for example:\r\n\r\n >>> ax.annotate(\"\", xy=(0.5, 0.5), xytext=(0, 0),\r\n ... arrowprops=dict(arrowstyle=\"->\"))\r\n\r\n \"\"\"\r\n # Strip away units for the underlying patch since units\r\n # do not make sense to most patch-like code\r\n x = self.convert_xunits(x)\r\n y = self.convert_yunits(y)\r\n dx = self.convert_xunits(dx)\r\n dy = self.convert_yunits(dy)\r\n\r\n a = mpatches.FancyArrow(x, y, dx, dy, **kwargs)\r\n self.add_patch(a)\r\n self._request_autoscale_view()\r\n return a\r\n\r\n @docstring.copy(mquiver.QuiverKey.__init__)\r\n def quiverkey(self, Q, X, Y, U, label, **kw):\r\n qk = mquiver.QuiverKey(Q, X, Y, U, label, **kw)\r\n self.add_artist(qk)\r\n return qk\r\n\r\n # Handle units for x and y, if they've been passed\r\n def _quiver_units(self, args, kw):\r\n if len(args) > 3:\r\n x, y = args[0:2]\r\n self._process_unit_info(xdata=x, ydata=y, kwargs=kw)\r\n x = self.convert_xunits(x)\r\n y = self.convert_yunits(y)\r\n return (x, y) + args[2:]\r\n return args\r\n\r\n # args can by a combination if X, Y, U, V, C and all should be replaced\r\n @_preprocess_data()\r\n def quiver(self, *args, **kw):\r\n # Make sure units are handled for x and y values\r\n args = self._quiver_units(args, kw)\r\n\r\n q = mquiver.Quiver(self, *args, **kw)\r\n\r\n self.add_collection(q, autolim=True)\r\n self._request_autoscale_view()\r\n return q\r\n quiver.__doc__ = mquiver.Quiver.quiver_doc\r\n\r\n # args can be some combination of X, Y, U, V, C and all should be replaced\r\n @_preprocess_data()\r\n @docstring.dedent_interpd\r\n def barbs(self, *args, **kw):\r\n \"\"\"\r\n %(barbs_doc)s\r\n \"\"\"\r\n # Make sure units are handled for x and y values\r\n args = self._quiver_units(args, kw)\r\n\r\n b = mquiver.Barbs(self, *args, **kw)\r\n self.add_collection(b, autolim=True)\r\n self._request_autoscale_view()\r\n return b\r\n\r\n # Uses a custom implementation of data-kwarg handling in\r\n # _process_plot_var_args.\r\n def fill(self, *args, data=None, **kwargs):\r\n \"\"\"\r\n Plot filled polygons.\r\n\r\n Parameters\r\n ----------\r\n *args : sequence of x, y, [color]\r\n Each polygon is defined by the lists of *x* and *y* positions of\r\n its nodes, optionally followed by a *color* specifier. See\r\n :mod:`matplotlib.colors` for supported color specifiers. The\r\n standard color cycle is used for polygons without a color\r\n specifier.\r\n\r\n You can plot multiple polygons by providing multiple *x*, *y*,\r\n *[color]* groups.\r\n\r\n For example, each of the following is legal::\r\n\r\n ax.fill(x, y) # a polygon with default color\r\n ax.fill(x, y, \"b\") # a blue polygon\r\n ax.fill(x, y, x2, y2) # two polygons\r\n ax.fill(x, y, \"b\", x2, y2, \"r\") # a blue and a red polygon\r\n\r\n data : indexable object, optional\r\n An object with labelled data. If given, provide the label names to\r\n plot in *x* and *y*, e.g.::\r\n\r\n ax.fill(\"time\", \"signal\",\r\n data={\"time\": [0, 1, 2], \"signal\": [0, 1, 0]})\r\n\r\n Returns\r\n -------\r\n list of `~matplotlib.patches.Polygon`\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs : `~matplotlib.patches.Polygon` properties\r\n\r\n Notes\r\n -----\r\n Use :meth:`fill_between` if you would like to fill the region between\r\n two curves.\r\n \"\"\"\r\n # For compatibility(!), get aliases from Line2D rather than Patch.\r\n kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)\r\n # _get_patches_for_fill returns a generator, convert it to a list.\r\n patches = [*self._get_patches_for_fill(*args, data=data, **kwargs)]\r\n for poly in patches:\r\n self.add_patch(poly)\r\n self._request_autoscale_view()\r\n return patches\r\n\r\n def _fill_between_x_or_y(\r\n self, ind_dir, ind, dep1, dep2=0, *,\r\n where=None, interpolate=False, step=None, **kwargs):\r\n # Common implementation between fill_between (*ind_dir*=\"x\") and\r\n # fill_betweenx (*ind_dir*=\"y\"). *ind* is the independent variable,\r\n # *dep* the dependent variable. The docstring below is interpolated\r\n # to generate both methods' docstrings.\r\n \"\"\"\r\n Fill the area between two {dir} curves.\r\n\r\n The curves are defined by the points (*{ind}*, *{dep}1*) and (*{ind}*,\r\n *{dep}2*). This creates one or multiple polygons describing the filled\r\n area.\r\n\r\n You may exclude some {dir} sections from filling using *where*.\r\n\r\n By default, the edges connect the given points directly. Use *step*\r\n if the filling should be a step function, i.e. constant in between\r\n *{ind}*.\r\n\r\n Parameters\r\n ----------\r\n {ind} : array (length N)\r\n The {ind} coordinates of the nodes defining the curves.\r\n\r\n {dep}1 : array (length N) or scalar\r\n The {dep} coordinates of the nodes defining the first curve.\r\n\r\n {dep}2 : array (length N) or scalar, default: 0\r\n The {dep} coordinates of the nodes defining the second curve.\r\n\r\n where : array of bool (length N), optional\r\n Define *where* to exclude some {dir} regions from being filled.\r\n The filled regions are defined by the coordinates ``{ind}[where]``.\r\n More precisely, fill between ``{ind}[i]`` and ``{ind}[i+1]`` if\r\n ``where[i] and where[i+1]``. Note that this definition implies\r\n that an isolated *True* value between two *False* values in *where*\r\n will not result in filling. Both sides of the *True* position\r\n remain unfilled due to the adjacent *False* values.\r\n\r\n interpolate : bool, default: False\r\n This option is only relevant if *where* is used and the two curves\r\n are crossing each other.\r\n\r\n Semantically, *where* is often used for *{dep}1* > *{dep}2* or\r\n similar. By default, the nodes of the polygon defining the filled\r\n region will only be placed at the positions in the *{ind}* array.\r\n Such a polygon cannot describe the above semantics close to the\r\n intersection. The {ind}-sections containing the intersection are\r\n simply clipped.\r\n\r\n Setting *interpolate* to *True* will calculate the actual\r\n intersection point and extend the filled region up to this point.\r\n\r\n step : {{'pre', 'post', 'mid'}}, optional\r\n Define *step* if the filling should be a step function,\r\n i.e. constant in between *{ind}*. The value determines where the\r\n step will occur:\r\n\r\n - 'pre': The y value is continued constantly to the left from\r\n every *x* position, i.e. the interval ``(x[i-1], x[i]]`` has the\r\n value ``y[i]``.\r\n - 'post': The y value is continued constantly to the right from\r\n every *x* position, i.e. the interval ``[x[i], x[i+1])`` has the\r\n value ``y[i]``.\r\n - 'mid': Steps occur half-way between the *x* positions.\r\n\r\n Returns\r\n -------\r\n `.PolyCollection`\r\n A `.PolyCollection` containing the plotted polygons.\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs\r\n All other keyword arguments are passed on to `.PolyCollection`.\r\n They control the `.Polygon` properties:\r\n\r\n %(PolyCollection)s\r\n\r\n See Also\r\n --------\r\n fill_between : Fill between two sets of y-values.\r\n fill_betweenx : Fill between two sets of x-values.\r\n\r\n Notes\r\n -----\r\n .. [notes section required to get data note injection right]\r\n \"\"\"\r\n\r\n dep_dir = {\"x\": \"y\", \"y\": \"x\"}[ind_dir]\r\n func_name = {\"x\": \"fill_between\", \"y\": \"fill_betweenx\"}[dep_dir]\r\n\r\n if not rcParams[\"_internal.classic_mode\"]:\r\n kwargs = cbook.normalize_kwargs(kwargs, mcoll.Collection)\r\n if not any(c in kwargs for c in (\"color\", \"facecolor\")):\r\n kwargs[\"facecolor\"] = \\\r\n self._get_patches_for_fill.get_next_color()\r\n\r\n # Handle united data, such as dates\r\n self._process_unit_info(\r\n **{f\"{ind_dir}data\": ind, f\"{dep_dir}data\": dep1}, kwargs=kwargs)\r\n self._process_unit_info(\r\n **{f\"{dep_dir}data\": dep2})\r\n\r\n # Convert the arrays so we can work with them\r\n ind = ma.masked_invalid(getattr(self, f\"convert_{ind_dir}units\")(ind))\r\n dep1 = ma.masked_invalid(\r\n getattr(self, f\"convert_{dep_dir}units\")(dep1))\r\n dep2 = ma.masked_invalid(\r\n getattr(self, f\"convert_{dep_dir}units\")(dep2))\r\n\r\n for name, array in [\r\n (ind_dir, ind), (f\"{dep_dir}1\", dep1), (f\"{dep_dir}2\", dep2)]:\r\n if array.ndim > 1:\r\n raise ValueError(f\"{name!r} is not 1-dimensional\")\r\n\r\n if where is None:\r\n where = True\r\n else:\r\n where = np.asarray(where, dtype=bool)\r\n if where.size != ind.size:\r\n cbook.warn_deprecated(\r\n \"3.2\", message=f\"Since %(since)s, the parameter *where* \"\r\n f\"must have the same size as {ind} in {func_name}(). This \"\r\n \"will become an error %(removal)s.\")\r\n where = where & ~functools.reduce(\r\n np.logical_or, map(np.ma.getmask, [ind, dep1, dep2]))\r\n\r\n ind, dep1, dep2 = np.broadcast_arrays(np.atleast_1d(ind), dep1, dep2)\r\n\r\n polys = []\r\n for idx0, idx1 in cbook.contiguous_regions(where):\r\n indslice = ind[idx0:idx1]\r\n dep1slice = dep1[idx0:idx1]\r\n dep2slice = dep2[idx0:idx1]\r\n if step is not None:\r\n step_func = cbook.STEP_LOOKUP_MAP[\"steps-\" + step]\r\n indslice, dep1slice, dep2slice = \\\r\n step_func(indslice, dep1slice, dep2slice)\r\n\r\n if not len(indslice):\r\n continue\r\n\r\n N = len(indslice)\r\n pts = np.zeros((2 * N + 2, 2))\r\n\r\n if interpolate:\r\n def get_interp_point(idx):\r\n im1 = max(idx - 1, 0)\r\n ind_values = ind[im1:idx+1]\r\n diff_values = dep1[im1:idx+1] - dep2[im1:idx+1]\r\n dep1_values = dep1[im1:idx+1]\r\n\r\n if len(diff_values) == 2:\r\n if np.ma.is_masked(diff_values[1]):\r\n return ind[im1], dep1[im1]\r\n elif np.ma.is_masked(diff_values[0]):\r\n return ind[idx], dep1[idx]\r\n\r\n diff_order = diff_values.argsort()\r\n diff_root_ind = np.interp(\r\n 0, diff_values[diff_order], ind_values[diff_order])\r\n ind_order = ind_values.argsort()\r\n diff_root_dep = np.interp(\r\n diff_root_ind,\r\n ind_values[ind_order], dep1_values[ind_order])\r\n return diff_root_ind, diff_root_dep\r\n\r\n start = get_interp_point(idx0)\r\n end = get_interp_point(idx1)\r\n else:\r\n # Handle scalar dep2 (e.g. 0): the fill should go all\r\n # the way down to 0 even if none of the dep1 sample points do.\r\n start = indslice[0], dep2slice[0]\r\n end = indslice[-1], dep2slice[-1]\r\n\r\n pts[0] = start\r\n pts[N + 1] = end\r\n\r\n pts[1:N+1, 0] = indslice\r\n pts[1:N+1, 1] = dep1slice\r\n pts[N+2:, 0] = indslice[::-1]\r\n pts[N+2:, 1] = dep2slice[::-1]\r\n\r\n if ind_dir == \"y\":\r\n pts = pts[:, ::-1]\r\n\r\n polys.append(pts)\r\n\r\n collection = mcoll.PolyCollection(polys, **kwargs)\r\n\r\n # now update the datalim and autoscale\r\n pts = np.row_stack([np.column_stack([ind[where], dep1[where]]),\r\n np.column_stack([ind[where], dep2[where]])])\r\n if ind_dir == \"y\":\r\n pts = pts[:, ::-1]\r\n self.update_datalim(pts, updatex=True, updatey=True)\r\n self.add_collection(collection, autolim=False)\r\n self._request_autoscale_view()\r\n return collection\r\n\r\n def fill_between(self, x, y1, y2=0, where=None, interpolate=False,\r\n step=None, **kwargs):\r\n return self._fill_between_x_or_y(\r\n \"x\", x, y1, y2,\r\n where=where, interpolate=interpolate, step=step, **kwargs)\r\n\r\n if _fill_between_x_or_y.__doc__:\r\n fill_between.__doc__ = _fill_between_x_or_y.__doc__.format(\r\n dir=\"horizontal\", ind=\"x\", dep=\"y\"\r\n )\r\n fill_between = _preprocess_data(\r\n docstring.dedent_interpd(fill_between),\r\n replace_names=[\"x\", \"y1\", \"y2\", \"where\"])\r\n\r\n def fill_betweenx(self, y, x1, x2=0, where=None,\r\n step=None, interpolate=False, **kwargs):\r\n return self._fill_between_x_or_y(\r\n \"y\", y, x1, x2,\r\n where=where, interpolate=interpolate, step=step, **kwargs)\r\n\r\n if _fill_between_x_or_y.__doc__:\r\n fill_betweenx.__doc__ = _fill_between_x_or_y.__doc__.format(\r\n dir=\"vertical\", ind=\"y\", dep=\"x\"\r\n )\r\n fill_betweenx = _preprocess_data(\r\n docstring.dedent_interpd(fill_betweenx),\r\n replace_names=[\"y\", \"x1\", \"x2\", \"where\"])\r\n\r\n #### plotting z(x, y): imshow, pcolor and relatives, contour\r\n @_preprocess_data()\r\n def imshow(self, X, cmap=None, norm=None, aspect=None,\r\n interpolation=None, alpha=None, vmin=None, vmax=None,\r\n origin=None, extent=None, *, filternorm=True, filterrad=4.0,\r\n resample=None, url=None, **kwargs):\r\n \"\"\"\r\n Display data as an image, i.e., on a 2D regular raster.\r\n\r\n The input may either be actual RGB(A) data, or 2D scalar data, which\r\n will be rendered as a pseudocolor image. For displaying a grayscale\r\n image set up the color mapping using the parameters\r\n ``cmap='gray', vmin=0, vmax=255``.\r\n\r\n The number of pixels used to render an image is set by the axes size\r\n and the *dpi* of the figure. This can lead to aliasing artifacts when\r\n the image is resampled because the displayed image size will usually\r\n not match the size of *X* (see\r\n :doc:`/gallery/images_contours_and_fields/image_antialiasing`).\r\n The resampling can be controlled via the *interpolation* parameter\r\n and/or :rc:`image.interpolation`.\r\n\r\n Parameters\r\n ----------\r\n X : array-like or PIL image\r\n The image data. Supported array shapes are:\r\n\r\n - (M, N): an image with scalar data. The values are mapped to\r\n colors using normalization and a colormap. See parameters *norm*,\r\n *cmap*, *vmin*, *vmax*.\r\n - (M, N, 3): an image with RGB values (0-1 float or 0-255 int).\r\n - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int),\r\n i.e. including transparency.\r\n\r\n The first two dimensions (M, N) define the rows and columns of\r\n the image.\r\n\r\n Out-of-range RGB(A) values are clipped.\r\n\r\n cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`\r\n The Colormap instance or registered colormap name used to map\r\n scalar data to colors. This parameter is ignored for RGB(A) data.\r\n\r\n norm : `~matplotlib.colors.Normalize`, optional\r\n The `.Normalize` instance used to scale scalar data to the [0, 1]\r\n range before mapping to colors using *cmap*. By default, a linear\r\n scaling mapping the lowest value to 0 and the highest to 1 is used.\r\n This parameter is ignored for RGB(A) data.\r\n\r\n aspect : {'equal', 'auto'} or float, default: :rc:`image.aspect`\r\n The aspect ratio of the axes. This parameter is particularly\r\n relevant for images since it determines whether data pixels are\r\n square.\r\n\r\n This parameter is a shortcut for explicitly calling\r\n `.Axes.set_aspect`. See there for further details.\r\n\r\n - 'equal': Ensures an aspect ratio of 1. Pixels will be square\r\n (unless pixel sizes are explicitly made non-square in data\r\n coordinates using *extent*).\r\n - 'auto': The axes is kept fixed and the aspect is adjusted so\r\n that the data fit in the axes. In general, this will result in\r\n non-square pixels.\r\n\r\n interpolation : str, default: :rc:`image.interpolation`\r\n The interpolation method used.\r\n\r\n Supported values are 'none', 'antialiased', 'nearest', 'bilinear',\r\n 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite',\r\n 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell',\r\n 'sinc', 'lanczos'.\r\n\r\n If *interpolation* is 'none', then no interpolation is performed\r\n on the Agg, ps, pdf and svg backends. Other backends will fall back\r\n to 'nearest'. Note that most SVG renderers perform interpolation at\r\n rendering and that the default interpolation method they implement\r\n may differ.\r\n\r\n If *interpolation* is the default 'antialiased', then 'nearest'\r\n interpolation is used if the image is upsampled by more than a\r\n factor of three (i.e. the number of display pixels is at least\r\n three times the size of the data array). If the upsampling rate is\r\n smaller than 3, or the image is downsampled, then 'hanning'\r\n interpolation is used to act as an anti-aliasing filter, unless the\r\n image happens to be upsampled by exactly a factor of two or one.\r\n\r\n See\r\n :doc:`/gallery/images_contours_and_fields/interpolation_methods`\r\n for an overview of the supported interpolation methods, and\r\n :doc:`/gallery/images_contours_and_fields/image_antialiasing` for\r\n a discussion of image antialiasing.\r\n\r\n Some interpolation methods require an additional radius parameter,\r\n which can be set by *filterrad*. Additionally, the antigrain image\r\n resize filter is controlled by the parameter *filternorm*.\r\n\r\n alpha : float or array-like, optional\r\n The alpha blending value, between 0 (transparent) and 1 (opaque).\r\n If *alpha* is an array, the alpha blending values are applied pixel\r\n by pixel, and *alpha* must have the same shape as *X*.\r\n\r\n vmin, vmax : float, optional\r\n When using scalar data and no explicit *norm*, *vmin* and *vmax*\r\n define the data range that the colormap covers. By default,\r\n the colormap covers the complete value range of the supplied\r\n data. It is deprecated to use *vmin*/*vmax* when *norm* is given.\r\n\r\n origin : {'upper', 'lower'}, default: :rc:`image.origin`\r\n Place the [0, 0] index of the array in the upper left or lower\r\n left corner of the axes. The convention (the default) 'upper' is\r\n typically used for matrices and images.\r\n\r\n Note that the vertical axes points upward for 'lower'\r\n but downward for 'upper'.\r\n\r\n See the :doc:`/tutorials/intermediate/imshow_extent` tutorial for\r\n examples and a more detailed description.\r\n\r\n extent : floats (left, right, bottom, top), optional\r\n The bounding box in data coordinates that the image will fill.\r\n The image is stretched individually along x and y to fill the box.\r\n\r\n The default extent is determined by the following conditions.\r\n Pixels have unit size in data coordinates. Their centers are on\r\n integer coordinates, and their center coordinates range from 0 to\r\n columns-1 horizontally and from 0 to rows-1 vertically.\r\n\r\n Note that the direction of the vertical axis and thus the default\r\n values for top and bottom depend on *origin*:\r\n\r\n - For ``origin == 'upper'`` the default is\r\n ``(-0.5, numcols-0.5, numrows-0.5, -0.5)``.\r\n - For ``origin == 'lower'`` the default is\r\n ``(-0.5, numcols-0.5, -0.5, numrows-0.5)``.\r\n\r\n See the :doc:`/tutorials/intermediate/imshow_extent` tutorial for\r\n examples and a more detailed description.\r\n\r\n filternorm : bool, default: True\r\n A parameter for the antigrain image resize filter (see the\r\n antigrain documentation). If *filternorm* is set, the filter\r\n normalizes integer values and corrects the rounding errors. It\r\n doesn't do anything with the source floating point values, it\r\n corrects only integers according to the rule of 1.0 which means\r\n that any sum of pixel weights must be equal to 1.0. So, the\r\n filter function must produce a graph of the proper shape.\r\n\r\n filterrad : float > 0, default: 4.0\r\n The filter radius for filters that have a radius parameter, i.e.\r\n when interpolation is one of: 'sinc', 'lanczos' or 'blackman'.\r\n\r\n resample : bool, default: :rc:`image.resample`\r\n When *True*, use a full resampling method. When *False*, only\r\n resample when the output image is larger than the input image.\r\n\r\n url : str, optional\r\n Set the url of the created `.AxesImage`. See `.Artist.set_url`.\r\n\r\n Returns\r\n -------\r\n `~matplotlib.image.AxesImage`\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs : `~matplotlib.artist.Artist` properties\r\n These parameters are passed on to the constructor of the\r\n `.AxesImage` artist.\r\n\r\n See Also\r\n --------\r\n matshow : Plot a matrix or an array as an image.\r\n\r\n Notes\r\n -----\r\n Unless *extent* is used, pixel centers will be located at integer\r\n coordinates. In other words: the origin will coincide with the center\r\n of pixel (0, 0).\r\n\r\n There are two common representations for RGB images with an alpha\r\n channel:\r\n\r\n - Straight (unassociated) alpha: R, G, and B channels represent the\r\n color of the pixel, disregarding its opacity.\r\n - Premultiplied (associated) alpha: R, G, and B channels represent\r\n the color of the pixel, adjusted for its opacity by multiplication.\r\n\r\n `~matplotlib.pyplot.imshow` expects RGB images adopting the straight\r\n (unassociated) alpha representation.\r\n \"\"\"\r\n if aspect is None:\r\n aspect = rcParams['image.aspect']\r\n self.set_aspect(aspect)\r\n im = mimage.AxesImage(self, cmap, norm, interpolation, origin, extent,\r\n filternorm=filternorm, filterrad=filterrad,\r\n resample=resample, **kwargs)\r\n\r\n im.set_data(X)\r\n im.set_alpha(alpha)\r\n if im.get_clip_path() is None:\r\n # image does not already have clipping set, clip to axes patch\r\n im.set_clip_path(self.patch)\r\n im._scale_norm(norm, vmin, vmax)\r\n im.set_url(url)\r\n\r\n # update ax.dataLim, and, if autoscaling, set viewLim\r\n # to tightly fit the image, regardless of dataLim.\r\n im.set_extent(im.get_extent())\r\n\r\n self.add_image(im)\r\n return im\r\n\r\n def _pcolorargs(self, funcname, *args, shading='flat', **kwargs):\r\n # - create X and Y if not present;\r\n # - reshape X and Y as needed if they are 1-D;\r\n # - check for proper sizes based on `shading` kwarg;\r\n # - reset shading if shading='auto' to flat or nearest\r\n # depending on size;\r\n\r\n _valid_shading = ['gouraud', 'nearest', 'flat', 'auto']\r\n try:\r\n cbook._check_in_list(_valid_shading, shading=shading)\r\n except ValueError as err:\r\n cbook._warn_external(f\"shading value '{shading}' not in list of \"\r\n f\"valid values {_valid_shading}. Setting \"\r\n \"shading='auto'.\")\r\n shading = 'auto'\r\n\r\n if len(args) == 1:\r\n C = np.asanyarray(args[0])\r\n nrows, ncols = C.shape\r\n if shading in ['gouraud', 'nearest']:\r\n X, Y = np.meshgrid(np.arange(ncols), np.arange(nrows))\r\n else:\r\n X, Y = np.meshgrid(np.arange(ncols + 1), np.arange(nrows + 1))\r\n shading = 'flat'\r\n C = cbook.safe_masked_invalid(C)\r\n return X, Y, C, shading\r\n\r\n if len(args) == 3:\r\n # Check x and y for bad data...\r\n C = np.asanyarray(args[2])\r\n X, Y = [cbook.safe_masked_invalid(a) for a in args[:2]]\r\n # unit conversion allows e.g. datetime objects as axis values\r\n self._process_unit_info(xdata=X, ydata=Y, kwargs=kwargs)\r\n X = self.convert_xunits(X)\r\n Y = self.convert_yunits(Y)\r\n if funcname == 'pcolormesh':\r\n if np.ma.is_masked(X) or np.ma.is_masked(Y):\r\n raise ValueError(\r\n 'x and y arguments to pcolormesh cannot have '\r\n 'non-finite values or be of type '\r\n 'numpy.ma.core.MaskedArray with masked values')\r\n # safe_masked_invalid() returns an ndarray for dtypes other\r\n # than floating point.\r\n if isinstance(X, np.ma.core.MaskedArray):\r\n X = X.data # strip mask as downstream doesn't like it...\r\n if isinstance(Y, np.ma.core.MaskedArray):\r\n Y = Y.data\r\n nrows, ncols = C.shape\r\n else:\r\n raise TypeError(f'{funcname}() takes 1 or 3 positional arguments '\r\n f'but {len(args)} were given')\r\n\r\n Nx = X.shape[-1]\r\n Ny = Y.shape[0]\r\n if X.ndim != 2 or X.shape[0] == 1:\r\n x = X.reshape(1, Nx)\r\n X = x.repeat(Ny, axis=0)\r\n if Y.ndim != 2 or Y.shape[1] == 1:\r\n y = Y.reshape(Ny, 1)\r\n Y = y.repeat(Nx, axis=1)\r\n if X.shape != Y.shape:\r\n raise TypeError(\r\n 'Incompatible X, Y inputs to %s; see help(%s)' % (\r\n funcname, funcname))\r\n\r\n if shading == 'auto':\r\n if ncols == Nx and nrows == Ny:\r\n shading = 'nearest'\r\n else:\r\n shading = 'flat'\r\n\r\n if shading == 'flat':\r\n if not (ncols in (Nx, Nx - 1) and nrows in (Ny, Ny - 1)):\r\n raise TypeError('Dimensions of C %s are incompatible with'\r\n ' X (%d) and/or Y (%d); see help(%s)' % (\r\n C.shape, Nx, Ny, funcname))\r\n if (ncols == Nx or nrows == Ny):\r\n cbook.warn_deprecated(\r\n \"3.3\", message=\"shading='flat' when X and Y have the same \"\r\n \"dimensions as C is deprecated since %(since)s. Either \"\r\n \"specify the corners of the quadrilaterals with X and Y, \"\r\n \"or pass shading='auto', 'nearest' or 'gouraud', or set \"\r\n \"rcParams['pcolor.shading']. This will become an error \"\r\n \"%(removal)s.\")\r\n C = C[:Ny - 1, :Nx - 1]\r\n else: # ['nearest', 'gouraud']:\r\n if (Nx, Ny) != (ncols, nrows):\r\n raise TypeError('Dimensions of C %s are incompatible with'\r\n ' X (%d) and/or Y (%d); see help(%s)' % (\r\n C.shape, Nx, Ny, funcname))\r\n if shading in ['nearest', 'auto']:\r\n # grid is specified at the center, so define corners\r\n # at the midpoints between the grid centers and then use the\r\n # flat algorithm.\r\n def _interp_grid(X):\r\n # helper for below\r\n if np.shape(X)[1] > 1:\r\n dX = np.diff(X, axis=1)/2.\r\n if not (np.all(dX >= 0) or np.all(dX <= 0)):\r\n cbook._warn_external(\r\n f\"The input coordinates to {funcname} are \"\r\n \"interpreted as cell centers, but are not \"\r\n \"monotonically increasing or decreasing. \"\r\n \"This may lead to incorrectly calculated cell \"\r\n \"edges, in which case, please supply \"\r\n f\"explicit cell edges to {funcname}.\")\r\n X = np.hstack((X[:, [0]] - dX[:, [0]],\r\n X[:, :-1] + dX,\r\n X[:, [-1]] + dX[:, [-1]]))\r\n else:\r\n # This is just degenerate, but we can't reliably guess\r\n # a dX if there is just one value.\r\n X = np.hstack((X, X))\r\n return X\r\n\r\n if ncols == Nx:\r\n X = _interp_grid(X)\r\n Y = _interp_grid(Y)\r\n if nrows == Ny:\r\n X = _interp_grid(X.T).T\r\n Y = _interp_grid(Y.T).T\r\n shading = 'flat'\r\n\r\n C = cbook.safe_masked_invalid(C)\r\n return X, Y, C, shading\r\n\r\n @_preprocess_data()\r\n @docstring.dedent_interpd\r\n def pcolor(self, *args, shading=None, alpha=None, norm=None, cmap=None,\r\n vmin=None, vmax=None, **kwargs):\r\n r\"\"\"\r\n Create a pseudocolor plot with a non-regular rectangular grid.\r\n\r\n Call signature::\r\n\r\n pcolor([X, Y,] C, **kwargs)\r\n\r\n *X* and *Y* can be used to specify the corners of the quadrilaterals.\r\n\r\n .. hint::\r\n\r\n ``pcolor()`` can be very slow for large arrays. In most\r\n cases you should use the similar but much faster\r\n `~.Axes.pcolormesh` instead. See\r\n :ref:`Differences between pcolor() and pcolormesh()\r\n <differences-pcolor-pcolormesh>` for a discussion of the\r\n differences.\r\n\r\n Parameters\r\n ----------\r\n C : array-like\r\n A scalar 2-D array. The values will be color-mapped.\r\n\r\n X, Y : array-like, optional\r\n The coordinates of the corners of quadrilaterals of a pcolormesh::\r\n\r\n (X[i+1, j], Y[i+1, j]) (X[i+1, j+1], Y[i+1, j+1])\r\n +-----+\r\n | |\r\n +-----+\r\n (X[i, j], Y[i, j]) (X[i, j+1], Y[i, j+1])\r\n\r\n Note that the column index corresponds to the x-coordinate, and\r\n the row index corresponds to y. For details, see the\r\n :ref:`Notes <axes-pcolormesh-grid-orientation>` section below.\r\n\r\n If ``shading='flat'`` the dimensions of *X* and *Y* should be one\r\n greater than those of *C*, and the quadrilateral is colored due\r\n to the value at ``C[i, j]``. If *X*, *Y* and *C* have equal\r\n dimensions, a warning will be raised and the last row and column\r\n of *C* will be ignored.\r\n\r\n If ``shading='nearest'``, the dimensions of *X* and *Y* should be\r\n the same as those of *C* (if not, a ValueError will be raised). The\r\n color ``C[i, j]`` will be centered on ``(X[i, j], Y[i, j])``.\r\n\r\n If *X* and/or *Y* are 1-D arrays or column vectors they will be\r\n expanded as needed into the appropriate 2-D arrays, making a\r\n rectangular grid.\r\n\r\n shading : {'flat', 'nearest', 'auto'}, optional\r\n The fill style for the quadrilateral; defaults to 'flat' or\r\n :rc:`pcolor.shading`. Possible values:\r\n\r\n - 'flat': A solid color is used for each quad. The color of the\r\n quad (i, j), (i+1, j), (i, j+1), (i+1, j+1) is given by\r\n ``C[i, j]``. The dimensions of *X* and *Y* should be\r\n one greater than those of *C*; if they are the same as *C*,\r\n then a deprecation warning is raised, and the last row\r\n and column of *C* are dropped.\r\n - 'nearest': Each grid point will have a color centered on it,\r\n extending halfway between the adjacent grid centers. The\r\n dimensions of *X* and *Y* must be the same as *C*.\r\n - 'auto': Choose 'flat' if dimensions of *X* and *Y* are one\r\n larger than *C*. Choose 'nearest' if dimensions are the same.\r\n\r\n See :doc:`/gallery/images_contours_and_fields/pcolormesh_grids`\r\n for more description.\r\n\r\n cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`\r\n A Colormap instance or registered colormap name. The colormap\r\n maps the *C* values to colors.\r\n\r\n norm : `~matplotlib.colors.Normalize`, optional\r\n The Normalize instance scales the data values to the canonical\r\n colormap range [0, 1] for mapping to colors. By default, the data\r\n range is mapped to the colorbar range using linear scaling.\r\n\r\n vmin, vmax : float, default: None\r\n The colorbar range. If *None*, suitable min/max values are\r\n automatically chosen by the `~.Normalize` instance (defaults to\r\n the respective min/max values of *C* in case of the default linear\r\n scaling).\r\n It is deprecated to use *vmin*/*vmax* when *norm* is given.\r\n\r\n edgecolors : {'none', None, 'face', color, color sequence}, optional\r\n The color of the edges. Defaults to 'none'. Possible values:\r\n\r\n - 'none' or '': No edge.\r\n - *None*: :rc:`patch.edgecolor` will be used. Note that currently\r\n :rc:`patch.force_edgecolor` has to be True for this to work.\r\n - 'face': Use the adjacent face color.\r\n - A color or sequence of colors will set the edge color.\r\n\r\n The singular form *edgecolor* works as an alias.\r\n\r\n alpha : float, default: None\r\n The alpha blending value of the face color, between 0 (transparent)\r\n and 1 (opaque). Note: The edgecolor is currently not affected by\r\n this.\r\n\r\n snap : bool, default: False\r\n Whether to snap the mesh to pixel boundaries.\r\n\r\n Returns\r\n -------\r\n `matplotlib.collections.Collection`\r\n\r\n Other Parameters\r\n ----------------\r\n antialiaseds : bool, default: False\r\n The default *antialiaseds* is False if the default\r\n *edgecolors*\\ =\"none\" is used. This eliminates artificial lines\r\n at patch boundaries, and works regardless of the value of alpha.\r\n If *edgecolors* is not \"none\", then the default *antialiaseds*\r\n is taken from :rc:`patch.antialiased`.\r\n Stroking the edges may be preferred if *alpha* is 1, but will\r\n cause artifacts otherwise.\r\n\r\n **kwargs\r\n Additionally, the following arguments are allowed. They are passed\r\n along to the `~matplotlib.collections.PolyCollection` constructor:\r\n\r\n %(PolyCollection)s\r\n\r\n See Also\r\n --------\r\n pcolormesh : for an explanation of the differences between\r\n pcolor and pcolormesh.\r\n imshow : If *X* and *Y* are each equidistant, `~.Axes.imshow` can be a\r\n faster alternative.\r\n\r\n Notes\r\n -----\r\n **Masked arrays**\r\n\r\n *X*, *Y* and *C* may be masked arrays. If either ``C[i, j]``, or one\r\n of the vertices surrounding ``C[i, j]`` (*X* or *Y* at\r\n ``[i, j], [i+1, j], [i, j+1], [i+1, j+1]``) is masked, nothing is\r\n plotted.\r\n\r\n .. _axes-pcolor-grid-orientation:\r\n\r\n **Grid orientation**\r\n\r\n The grid orientation follows the standard matrix convention: An array\r\n *C* with shape (nrows, ncolumns) is plotted with the column number as\r\n *X* and the row number as *Y*.\r\n \"\"\"\r\n\r\n if shading is None:\r\n shading = rcParams['pcolor.shading']\r\n shading = shading.lower()\r\n X, Y, C, shading = self._pcolorargs('pcolor', *args, shading=shading,\r\n kwargs=kwargs)\r\n Ny, Nx = X.shape\r\n\r\n # convert to MA, if necessary.\r\n C = ma.asarray(C)\r\n X = ma.asarray(X)\r\n Y = ma.asarray(Y)\r\n\r\n mask = ma.getmaskarray(X) + ma.getmaskarray(Y)\r\n xymask = (mask[0:-1, 0:-1] + mask[1:, 1:] +\r\n mask[0:-1, 1:] + mask[1:, 0:-1])\r\n # don't plot if C or any of the surrounding vertices are masked.\r\n mask = ma.getmaskarray(C) + xymask\r\n\r\n unmask = ~mask\r\n X1 = ma.filled(X[:-1, :-1])[unmask]\r\n Y1 = ma.filled(Y[:-1, :-1])[unmask]\r\n X2 = ma.filled(X[1:, :-1])[unmask]\r\n Y2 = ma.filled(Y[1:, :-1])[unmask]\r\n X3 = ma.filled(X[1:, 1:])[unmask]\r\n Y3 = ma.filled(Y[1:, 1:])[unmask]\r\n X4 = ma.filled(X[:-1, 1:])[unmask]\r\n Y4 = ma.filled(Y[:-1, 1:])[unmask]\r\n npoly = len(X1)\r\n\r\n xy = np.stack([X1, Y1, X2, Y2, X3, Y3, X4, Y4, X1, Y1], axis=-1)\r\n verts = xy.reshape((npoly, 5, 2))\r\n\r\n C = ma.filled(C[:Ny - 1, :Nx - 1])[unmask]\r\n\r\n linewidths = (0.25,)\r\n if 'linewidth' in kwargs:\r\n kwargs['linewidths'] = kwargs.pop('linewidth')\r\n kwargs.setdefault('linewidths', linewidths)\r\n\r\n if 'edgecolor' in kwargs:\r\n kwargs['edgecolors'] = kwargs.pop('edgecolor')\r\n ec = kwargs.setdefault('edgecolors', 'none')\r\n\r\n # aa setting will default via collections to patch.antialiased\r\n # unless the boundary is not stroked, in which case the\r\n # default will be False; with unstroked boundaries, aa\r\n # makes artifacts that are often disturbing.\r\n if 'antialiased' in kwargs:\r\n kwargs['antialiaseds'] = kwargs.pop('antialiased')\r\n if 'antialiaseds' not in kwargs and cbook._str_lower_equal(ec, \"none\"):\r\n kwargs['antialiaseds'] = False\r\n\r\n kwargs.setdefault('snap', False)\r\n\r\n collection = mcoll.PolyCollection(verts, **kwargs)\r\n\r\n collection.set_alpha(alpha)\r\n collection.set_array(C)\r\n collection.set_cmap(cmap)\r\n collection.set_norm(norm)\r\n collection._scale_norm(norm, vmin, vmax)\r\n self.grid(False)\r\n\r\n x = X.compressed()\r\n y = Y.compressed()\r\n\r\n # Transform from native to data coordinates?\r\n t = collection._transform\r\n if (not isinstance(t, mtransforms.Transform) and\r\n hasattr(t, '_as_mpl_transform')):\r\n t = t._as_mpl_transform(self.axes)\r\n\r\n if t and any(t.contains_branch_seperately(self.transData)):\r\n trans_to_data = t - self.transData\r\n pts = np.vstack([x, y]).T.astype(float)\r\n transformed_pts = trans_to_data.transform(pts)\r\n x = transformed_pts[..., 0]\r\n y = transformed_pts[..., 1]\r\n\r\n self.add_collection(collection, autolim=False)\r\n\r\n minx = np.min(x)\r\n maxx = np.max(x)\r\n miny = np.min(y)\r\n maxy = np.max(y)\r\n collection.sticky_edges.x[:] = [minx, maxx]\r\n collection.sticky_edges.y[:] = [miny, maxy]\r\n corners = (minx, miny), (maxx, maxy)\r\n self.update_datalim(corners)\r\n self._request_autoscale_view()\r\n return collection\r\n\r\n @_preprocess_data()\r\n @docstring.dedent_interpd\r\n def pcolormesh(self, *args, alpha=None, norm=None, cmap=None, vmin=None,\r\n vmax=None, shading=None, antialiased=False, **kwargs):\r\n \"\"\"\r\n Create a pseudocolor plot with a non-regular rectangular grid.\r\n\r\n Call signature::\r\n\r\n pcolormesh([X, Y,] C, **kwargs)\r\n\r\n *X* and *Y* can be used to specify the corners of the quadrilaterals.\r\n\r\n .. hint::\r\n\r\n `~.Axes.pcolormesh` is similar to `~.Axes.pcolor`. It is much faster\r\n and preferred in most cases. For a detailed discussion on the\r\n differences see :ref:`Differences between pcolor() and pcolormesh()\r\n <differences-pcolor-pcolormesh>`.\r\n\r\n Parameters\r\n ----------\r\n C : array-like\r\n A scalar 2-D array. The values will be color-mapped.\r\n\r\n X, Y : array-like, optional\r\n The coordinates of the corners of quadrilaterals of a pcolormesh::\r\n\r\n (X[i+1, j], Y[i+1, j]) (X[i+1, j+1], Y[i+1, j+1])\r\n +-----+\r\n | |\r\n +-----+\r\n (X[i, j], Y[i, j]) (X[i, j+1], Y[i, j+1])\r\n\r\n Note that the column index corresponds to the x-coordinate, and\r\n the row index corresponds to y. For details, see the\r\n :ref:`Notes <axes-pcolormesh-grid-orientation>` section below.\r\n\r\n If ``shading='flat'`` the dimensions of *X* and *Y* should be one\r\n greater than those of *C*, and the quadrilateral is colored due\r\n to the value at ``C[i, j]``. If *X*, *Y* and *C* have equal\r\n dimensions, a warning will be raised and the last row and column\r\n of *C* will be ignored.\r\n\r\n If ``shading='nearest'`` or ``'gouraud'``, the dimensions of *X*\r\n and *Y* should be the same as those of *C* (if not, a ValueError\r\n will be raised). For ``'nearest'`` the color ``C[i, j]`` is\r\n centered on ``(X[i, j], Y[i, j])``. For ``'gouraud'``, a smooth\r\n interpolation is caried out between the quadrilateral corners.\r\n\r\n If *X* and/or *Y* are 1-D arrays or column vectors they will be\r\n expanded as needed into the appropriate 2-D arrays, making a\r\n rectangular grid.\r\n\r\n cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`\r\n A Colormap instance or registered colormap name. The colormap\r\n maps the *C* values to colors.\r\n\r\n norm : `~matplotlib.colors.Normalize`, optional\r\n The Normalize instance scales the data values to the canonical\r\n colormap range [0, 1] for mapping to colors. By default, the data\r\n range is mapped to the colorbar range using linear scaling.\r\n\r\n vmin, vmax : float, default: None\r\n The colorbar range. If *None*, suitable min/max values are\r\n automatically chosen by the `~.Normalize` instance (defaults to\r\n the respective min/max values of *C* in case of the default linear\r\n scaling).\r\n It is deprecated to use *vmin*/*vmax* when *norm* is given.\r\n\r\n edgecolors : {'none', None, 'face', color, color sequence}, optional\r\n The color of the edges. Defaults to 'none'. Possible values:\r\n\r\n - 'none' or '': No edge.\r\n - *None*: :rc:`patch.edgecolor` will be used. Note that currently\r\n :rc:`patch.force_edgecolor` has to be True for this to work.\r\n - 'face': Use the adjacent face color.\r\n - A color or sequence of colors will set the edge color.\r\n\r\n The singular form *edgecolor* works as an alias.\r\n\r\n alpha : float, default: None\r\n The alpha blending value, between 0 (transparent) and 1 (opaque).\r\n\r\n shading : {'flat', 'nearest', 'gouraud', 'auto'}, optional\r\n The fill style for the quadrilateral; defaults to\r\n 'flat' or :rc:`pcolor.shading`. Possible values:\r\n\r\n - 'flat': A solid color is used for each quad. The color of the\r\n quad (i, j), (i+1, j), (i, j+1), (i+1, j+1) is given by\r\n ``C[i, j]``. The dimensions of *X* and *Y* should be\r\n one greater than those of *C*; if they are the same as *C*,\r\n then a deprecation warning is raised, and the last row\r\n and column of *C* are dropped.\r\n - 'nearest': Each grid point will have a color centered on it,\r\n extending halfway between the adjacent grid centers. The\r\n dimensions of *X* and *Y* must be the same as *C*.\r\n - 'gouraud': Each quad will be Gouraud shaded: The color of the\r\n corners (i', j') are given by ``C[i', j']``. The color values of\r\n the area in between is interpolated from the corner values.\r\n The dimensions of *X* and *Y* must be the same as *C*. When\r\n Gouraud shading is used, *edgecolors* is ignored.\r\n - 'auto': Choose 'flat' if dimensions of *X* and *Y* are one\r\n larger than *C*. Choose 'nearest' if dimensions are the same.\r\n\r\n See :doc:`/gallery/images_contours_and_fields/pcolormesh_grids`\r\n for more description.\r\n\r\n snap : bool, default: False\r\n Whether to snap the mesh to pixel boundaries.\r\n\r\n Returns\r\n -------\r\n `matplotlib.collections.QuadMesh`\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs\r\n Additionally, the following arguments are allowed. They are passed\r\n along to the `~matplotlib.collections.QuadMesh` constructor:\r\n\r\n %(QuadMesh)s\r\n\r\n See Also\r\n --------\r\n pcolor : An alternative implementation with slightly different\r\n features. For a detailed discussion on the differences see\r\n :ref:`Differences between pcolor() and pcolormesh()\r\n <differences-pcolor-pcolormesh>`.\r\n imshow : If *X* and *Y* are each equidistant, `~.Axes.imshow` can be a\r\n faster alternative.\r\n\r\n Notes\r\n -----\r\n **Masked arrays**\r\n\r\n *C* may be a masked array. If ``C[i, j]`` is masked, the corresponding\r\n quadrilateral will be transparent. Masking of *X* and *Y* is not\r\n supported. Use `~.Axes.pcolor` if you need this functionality.\r\n\r\n .. _axes-pcolormesh-grid-orientation:\r\n\r\n **Grid orientation**\r\n\r\n The grid orientation follows the standard matrix convention: An array\r\n *C* with shape (nrows, ncolumns) is plotted with the column number as\r\n *X* and the row number as *Y*.\r\n\r\n .. _differences-pcolor-pcolormesh:\r\n\r\n **Differences between pcolor() and pcolormesh()**\r\n\r\n Both methods are used to create a pseudocolor plot of a 2-D array\r\n using quadrilaterals.\r\n\r\n The main difference lies in the created object and internal data\r\n handling:\r\n While `~.Axes.pcolor` returns a `.PolyCollection`, `~.Axes.pcolormesh`\r\n returns a `.QuadMesh`. The latter is more specialized for the given\r\n purpose and thus is faster. It should almost always be preferred.\r\n\r\n There is also a slight difference in the handling of masked arrays.\r\n Both `~.Axes.pcolor` and `~.Axes.pcolormesh` support masked arrays\r\n for *C*. However, only `~.Axes.pcolor` supports masked arrays for *X*\r\n and *Y*. The reason lies in the internal handling of the masked values.\r\n `~.Axes.pcolor` leaves out the respective polygons from the\r\n PolyCollection. `~.Axes.pcolormesh` sets the facecolor of the masked\r\n elements to transparent. You can see the difference when using\r\n edgecolors. While all edges are drawn irrespective of masking in a\r\n QuadMesh, the edge between two adjacent masked quadrilaterals in\r\n `~.Axes.pcolor` is not drawn as the corresponding polygons do not\r\n exist in the PolyCollection.\r\n\r\n Another difference is the support of Gouraud shading in\r\n `~.Axes.pcolormesh`, which is not available with `~.Axes.pcolor`.\r\n\r\n \"\"\"\r\n if shading is None:\r\n shading = rcParams['pcolor.shading']\r\n shading = shading.lower()\r\n kwargs.setdefault('edgecolors', 'None')\r\n\r\n X, Y, C, shading = self._pcolorargs('pcolormesh', *args,\r\n shading=shading, kwargs=kwargs)\r\n Ny, Nx = X.shape\r\n X = X.ravel()\r\n Y = Y.ravel()\r\n\r\n # convert to one dimensional arrays\r\n C = C.ravel()\r\n coords = np.column_stack((X, Y)).astype(float, copy=False)\r\n collection = mcoll.QuadMesh(Nx - 1, Ny - 1, coords,\r\n antialiased=antialiased, shading=shading,\r\n **kwargs)\r\n collection.set_alpha(alpha)\r\n collection.set_array(C)\r\n collection.set_cmap(cmap)\r\n collection.set_norm(norm)\r\n collection._scale_norm(norm, vmin, vmax)\r\n\r\n self.grid(False)\r\n\r\n # Transform from native to data coordinates?\r\n t = collection._transform\r\n if (not isinstance(t, mtransforms.Transform) and\r\n hasattr(t, '_as_mpl_transform')):\r\n t = t._as_mpl_transform(self.axes)\r\n\r\n if t and any(t.contains_branch_seperately(self.transData)):\r\n trans_to_data = t - self.transData\r\n coords = trans_to_data.transform(coords)\r\n\r\n self.add_collection(collection, autolim=False)\r\n\r\n minx, miny = np.min(coords, axis=0)\r\n maxx, maxy = np.max(coords, axis=0)\r\n collection.sticky_edges.x[:] = [minx, maxx]\r\n collection.sticky_edges.y[:] = [miny, maxy]\r\n corners = (minx, miny), (maxx, maxy)\r\n self.update_datalim(corners)\r\n self._request_autoscale_view()\r\n return collection\r\n\r\n @_preprocess_data()\r\n @docstring.dedent_interpd\r\n def pcolorfast(self, *args, alpha=None, norm=None, cmap=None, vmin=None,\r\n vmax=None, **kwargs):\r\n \"\"\"\r\n Create a pseudocolor plot with a non-regular rectangular grid.\r\n\r\n Call signature::\r\n\r\n ax.pcolorfast([X, Y], C, /, **kwargs)\r\n\r\n This method is similar to `~.Axes.pcolor` and `~.Axes.pcolormesh`.\r\n It's designed to provide the fastest pcolor-type plotting with the\r\n Agg backend. To achieve this, it uses different algorithms internally\r\n depending on the complexity of the input grid (regular rectangular,\r\n non-regular rectangular or arbitrary quadrilateral).\r\n\r\n .. warning::\r\n\r\n This method is experimental. Compared to `~.Axes.pcolor` or\r\n `~.Axes.pcolormesh` it has some limitations:\r\n\r\n - It supports only flat shading (no outlines)\r\n - It lacks support for log scaling of the axes.\r\n - It does not have a have a pyplot wrapper.\r\n\r\n Parameters\r\n ----------\r\n C : array-like(M, N)\r\n The image data. Supported array shapes are:\r\n\r\n - (M, N): an image with scalar data. The data is visualized\r\n using a colormap.\r\n - (M, N, 3): an image with RGB values (0-1 float or 0-255 int).\r\n - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int),\r\n i.e. including transparency.\r\n\r\n The first two dimensions (M, N) define the rows and columns of\r\n the image.\r\n\r\n This parameter can only be passed positionally.\r\n\r\n X, Y : tuple or array-like, default: ``(0, N)``, ``(0, M)``\r\n *X* and *Y* are used to specify the coordinates of the\r\n quadrilaterals. There are different ways to do this:\r\n\r\n - Use tuples ``X=(xmin, xmax)`` and ``Y=(ymin, ymax)`` to define\r\n a *uniform rectangular grid*.\r\n\r\n The tuples define the outer edges of the grid. All individual\r\n quadrilaterals will be of the same size. This is the fastest\r\n version.\r\n\r\n - Use 1D arrays *X*, *Y* to specify a *non-uniform rectangular\r\n grid*.\r\n\r\n In this case *X* and *Y* have to be monotonic 1D arrays of length\r\n *N+1* and *M+1*, specifying the x and y boundaries of the cells.\r\n\r\n The speed is intermediate. Note: The grid is checked, and if\r\n found to be uniform the fast version is used.\r\n\r\n - Use 2D arrays *X*, *Y* if you need an *arbitrary quadrilateral\r\n grid* (i.e. if the quadrilaterals are not rectangular).\r\n\r\n In this case *X* and *Y* are 2D arrays with shape (M + 1, N + 1),\r\n specifying the x and y coordinates of the corners of the colored\r\n quadrilaterals.\r\n\r\n This is the most general, but the slowest to render. It may\r\n produce faster and more compact output using ps, pdf, and\r\n svg backends, however.\r\n\r\n These arguments can only be passed positionally.\r\n\r\n cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`\r\n A Colormap instance or registered colormap name. The colormap\r\n maps the *C* values to colors.\r\n\r\n norm : `~matplotlib.colors.Normalize`, optional\r\n The Normalize instance scales the data values to the canonical\r\n colormap range [0, 1] for mapping to colors. By default, the data\r\n range is mapped to the colorbar range using linear scaling.\r\n\r\n vmin, vmax : float, default: None\r\n The colorbar range. If *None*, suitable min/max values are\r\n automatically chosen by the `~.Normalize` instance (defaults to\r\n the respective min/max values of *C* in case of the default linear\r\n scaling).\r\n It is deprecated to use *vmin*/*vmax* when *norm* is given.\r\n\r\n alpha : float, default: None\r\n The alpha blending value, between 0 (transparent) and 1 (opaque).\r\n\r\n snap : bool, default: False\r\n Whether to snap the mesh to pixel boundaries.\r\n\r\n Returns\r\n -------\r\n `.AxesImage` or `.PcolorImage` or `.QuadMesh`\r\n The return type depends on the type of grid:\r\n\r\n - `.AxesImage` for a regular rectangular grid.\r\n - `.PcolorImage` for a non-regular rectangular grid.\r\n - `.QuadMesh` for a non-rectangular grid.\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs\r\n Supported additional parameters depend on the type of grid.\r\n See return types of *image* for further description.\r\n\r\n Notes\r\n -----\r\n .. [notes section required to get data note injection right]\r\n \"\"\"\r\n\r\n C = args[-1]\r\n nr, nc = np.shape(C)[:2]\r\n if len(args) == 1:\r\n style = \"image\"\r\n x = [0, nc]\r\n y = [0, nr]\r\n elif len(args) == 3:\r\n x, y = args[:2]\r\n x = np.asarray(x)\r\n y = np.asarray(y)\r\n if x.ndim == 1 and y.ndim == 1:\r\n if x.size == 2 and y.size == 2:\r\n style = \"image\"\r\n else:\r\n dx = np.diff(x)\r\n dy = np.diff(y)\r\n if (np.ptp(dx) < 0.01 * abs(dx.mean()) and\r\n np.ptp(dy) < 0.01 * abs(dy.mean())):\r\n style = \"image\"\r\n else:\r\n style = \"pcolorimage\"\r\n elif x.ndim == 2 and y.ndim == 2:\r\n style = \"quadmesh\"\r\n else:\r\n raise TypeError(\"arguments do not match valid signatures\")\r\n else:\r\n raise TypeError(\"need 1 argument or 3 arguments\")\r\n\r\n if style == \"quadmesh\":\r\n # data point in each cell is value at lower left corner\r\n coords = np.stack([x, y], axis=-1)\r\n if np.ndim(C) == 2:\r\n qm_kwargs = {\"array\": np.ma.ravel(C)}\r\n elif np.ndim(C) == 3:\r\n qm_kwargs = {\"color\": np.ma.reshape(C, (-1, C.shape[-1]))}\r\n else:\r\n raise ValueError(\"C must be 2D or 3D\")\r\n collection = mcoll.QuadMesh(\r\n nc, nr, coords, **qm_kwargs,\r\n alpha=alpha, cmap=cmap, norm=norm,\r\n antialiased=False, edgecolors=\"none\")\r\n self.add_collection(collection, autolim=False)\r\n xl, xr, yb, yt = x.min(), x.max(), y.min(), y.max()\r\n ret = collection\r\n\r\n else: # It's one of the two image styles.\r\n extent = xl, xr, yb, yt = x[0], x[-1], y[0], y[-1]\r\n if style == \"image\":\r\n im = mimage.AxesImage(\r\n self, cmap, norm,\r\n data=C, alpha=alpha, extent=extent,\r\n interpolation='nearest', origin='lower',\r\n **kwargs)\r\n elif style == \"pcolorimage\":\r\n im = mimage.PcolorImage(\r\n self, x, y, C,\r\n cmap=cmap, norm=norm, alpha=alpha, extent=extent,\r\n **kwargs)\r\n self.add_image(im)\r\n ret = im\r\n\r\n if np.ndim(C) == 2: # C.ndim == 3 is RGB(A) so doesn't need scaling.\r\n ret._scale_norm(norm, vmin, vmax)\r\n\r\n if ret.get_clip_path() is None:\r\n # image does not already have clipping set, clip to axes patch\r\n ret.set_clip_path(self.patch)\r\n\r\n ret.sticky_edges.x[:] = [xl, xr]\r\n ret.sticky_edges.y[:] = [yb, yt]\r\n self.update_datalim(np.array([[xl, yb], [xr, yt]]))\r\n self._request_autoscale_view(tight=True)\r\n return ret\r\n\r\n @_preprocess_data()\r\n def contour(self, *args, **kwargs):\r\n kwargs['filled'] = False\r\n contours = mcontour.QuadContourSet(self, *args, **kwargs)\r\n self._request_autoscale_view()\r\n return contours\r\n contour.__doc__ = mcontour.QuadContourSet._contour_doc\r\n\r\n @_preprocess_data()\r\n def contourf(self, *args, **kwargs):\r\n kwargs['filled'] = True\r\n contours = mcontour.QuadContourSet(self, *args, **kwargs)\r\n self._request_autoscale_view()\r\n return contours\r\n contourf.__doc__ = mcontour.QuadContourSet._contour_doc\r\n\r\n def clabel(self, CS, levels=None, **kwargs):\r\n \"\"\"\r\n Label a contour plot.\r\n\r\n Adds labels to line contours in given `.ContourSet`.\r\n\r\n Parameters\r\n ----------\r\n CS : `~.ContourSet` instance\r\n Line contours to label.\r\n\r\n levels : array-like, optional\r\n A list of level values, that should be labeled. The list must be\r\n a subset of ``CS.levels``. If not given, all levels are labeled.\r\n\r\n **kwargs\r\n All other parameters are documented in `~.ContourLabeler.clabel`.\r\n \"\"\"\r\n return CS.clabel(levels, **kwargs)\r\n\r\n #### Data analysis\r\n\r\n @_preprocess_data(replace_names=[\"x\", 'weights'], label_namer=\"x\")\r\n def hist(self, x, bins=None, range=None, density=False, weights=None,\r\n cumulative=False, bottom=None, histtype='bar', align='mid',\r\n orientation='vertical', rwidth=None, log=False,\r\n color=None, label=None, stacked=False, **kwargs):\r\n \"\"\"\r\n Plot a histogram.\r\n\r\n Compute and draw the histogram of *x*. The return value is a tuple\r\n (*n*, *bins*, *patches*) or ([*n0*, *n1*, ...], *bins*, [*patches0*,\r\n *patches1*, ...]) if the input contains multiple data. See the\r\n documentation of the *weights* parameter to draw a histogram of\r\n already-binned data.\r\n\r\n Multiple data can be provided via *x* as a list of datasets\r\n of potentially different length ([*x0*, *x1*, ...]), or as\r\n a 2-D ndarray in which each column is a dataset. Note that\r\n the ndarray form is transposed relative to the list form.\r\n\r\n Masked arrays are not supported.\r\n\r\n The *bins*, *range*, *weights*, and *density* parameters behave as in\r\n `numpy.histogram`.\r\n\r\n Parameters\r\n ----------\r\n x : (n,) array or sequence of (n,) arrays\r\n Input values, this takes either a single array or a sequence of\r\n arrays which are not required to be of the same length.\r\n\r\n bins : int or sequence or str, default: :rc:`hist.bins`\r\n If *bins* is an integer, it defines the number of equal-width bins\r\n in the range.\r\n\r\n If *bins* is a sequence, it defines the bin edges, including the\r\n left edge of the first bin and the right edge of the last bin;\r\n in this case, bins may be unequally spaced. All but the last\r\n (righthand-most) bin is half-open. In other words, if *bins* is::\r\n\r\n [1, 2, 3, 4]\r\n\r\n then the first bin is ``[1, 2)`` (including 1, but excluding 2) and\r\n the second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which\r\n *includes* 4.\r\n\r\n If *bins* is a string, it is one of the binning strategies\r\n supported by `numpy.histogram_bin_edges`: 'auto', 'fd', 'doane',\r\n 'scott', 'stone', 'rice', 'sturges', or 'sqrt'.\r\n\r\n range : tuple or None, default: None\r\n The lower and upper range of the bins. Lower and upper outliers\r\n are ignored. If not provided, *range* is ``(x.min(), x.max())``.\r\n Range has no effect if *bins* is a sequence.\r\n\r\n If *bins* is a sequence or *range* is specified, autoscaling\r\n is based on the specified bin range instead of the\r\n range of x.\r\n\r\n density : bool, default: False\r\n If ``True``, draw and return a probability density: each bin\r\n will display the bin's raw count divided by the total number of\r\n counts *and the bin width*\r\n (``density = counts / (sum(counts) * np.diff(bins))``),\r\n so that the area under the histogram integrates to 1\r\n (``np.sum(density * np.diff(bins)) == 1``).\r\n\r\n If *stacked* is also ``True``, the sum of the histograms is\r\n normalized to 1.\r\n\r\n weights : (n,) array-like or None, default: None\r\n An array of weights, of the same shape as *x*. Each value in\r\n *x* only contributes its associated weight towards the bin count\r\n (instead of 1). If *density* is ``True``, the weights are\r\n normalized, so that the integral of the density over the range\r\n remains 1.\r\n\r\n This parameter can be used to draw a histogram of data that has\r\n already been binned, e.g. using `numpy.histogram` (by treating each\r\n bin as a single point with a weight equal to its count) ::\r\n\r\n counts, bins = np.histogram(data)\r\n plt.hist(bins[:-1], bins, weights=counts)\r\n\r\n (or you may alternatively use `~.bar()`).\r\n\r\n cumulative : bool or -1, default: False\r\n If ``True``, then a histogram is computed where each bin gives the\r\n counts in that bin plus all bins for smaller values. The last bin\r\n gives the total number of datapoints.\r\n\r\n If *density* is also ``True`` then the histogram is normalized such\r\n that the last bin equals 1.\r\n\r\n If *cumulative* is a number less than 0 (e.g., -1), the direction\r\n of accumulation is reversed. In this case, if *density* is also\r\n ``True``, then the histogram is normalized such that the first bin\r\n equals 1.\r\n\r\n bottom : array-like, scalar, or None, default: None\r\n Location of the bottom of each bin, ie. bins are drawn from\r\n ``bottom`` to ``bottom + hist(x, bins)`` If a scalar, the bottom\r\n of each bin is shifted by the same amount. If an array, each bin\r\n is shifted independently and the length of bottom must match the\r\n number of bins. If None, defaults to 0.\r\n\r\n histtype : {'bar', 'barstacked', 'step', 'stepfilled'}, default: 'bar'\r\n The type of histogram to draw.\r\n\r\n - 'bar' is a traditional bar-type histogram. If multiple data\r\n are given the bars are arranged side by side.\r\n - 'barstacked' is a bar-type histogram where multiple\r\n data are stacked on top of each other.\r\n - 'step' generates a lineplot that is by default unfilled.\r\n - 'stepfilled' generates a lineplot that is by default filled.\r\n\r\n align : {'left', 'mid', 'right'}, default: 'mid'\r\n The horizontal alignment of the histogram bars.\r\n\r\n - 'left': bars are centered on the left bin edges.\r\n - 'mid': bars are centered between the bin edges.\r\n - 'right': bars are centered on the right bin edges.\r\n\r\n orientation : {'vertical', 'horizontal'}, default: 'vertical'\r\n If 'horizontal', `~.Axes.barh` will be used for bar-type histograms\r\n and the *bottom* kwarg will be the left edges.\r\n\r\n rwidth : float or None, default: None\r\n The relative width of the bars as a fraction of the bin width. If\r\n ``None``, automatically compute the width.\r\n\r\n Ignored if *histtype* is 'step' or 'stepfilled'.\r\n\r\n log : bool, default: False\r\n If ``True``, the histogram axis will be set to a log scale. If\r\n *log* is ``True`` and *x* is a 1D array, empty bins will be\r\n filtered out and only the non-empty ``(n, bins, patches)``\r\n will be returned.\r\n\r\n color : color or array-like of colors or None, default: None\r\n Color or sequence of colors, one per dataset. Default (``None``)\r\n uses the standard line color sequence.\r\n\r\n label : str or None, default: None\r\n String, or sequence of strings to match multiple datasets. Bar\r\n charts yield multiple patches per dataset, but only the first gets\r\n the label, so that `~.Axes.legend` will work as expected.\r\n\r\n stacked : bool, default: False\r\n If ``True``, multiple data are stacked on top of each other If\r\n ``False`` multiple data are arranged side by side if histtype is\r\n 'bar' or on top of each other if histtype is 'step'\r\n\r\n Returns\r\n -------\r\n n : array or list of arrays\r\n The values of the histogram bins. See *density* and *weights* for a\r\n description of the possible semantics. If input *x* is an array,\r\n then this is an array of length *nbins*. If input is a sequence of\r\n arrays ``[data1, data2, ...]``, then this is a list of arrays with\r\n the values of the histograms for each of the arrays in the same\r\n order. The dtype of the array *n* (or of its element arrays) will\r\n always be float even if no weighting or normalization is used.\r\n\r\n bins : array\r\n The edges of the bins. Length nbins + 1 (nbins left edges and right\r\n edge of last bin). Always a single array even when multiple data\r\n sets are passed in.\r\n\r\n patches : `.BarContainer` or list of a single `.Polygon` or list of \\\r\nsuch objects\r\n Container of individual artists used to create the histogram\r\n or list of such containers if there are multiple input datasets.\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs\r\n `~matplotlib.patches.Patch` properties\r\n\r\n See Also\r\n --------\r\n hist2d : 2D histograms\r\n\r\n Notes\r\n -----\r\n For large numbers of bins (>1000), 'step' and 'stepfilled' can be\r\n significantly faster than 'bar' and 'barstacked'.\r\n\r\n \"\"\"\r\n # Avoid shadowing the builtin.\r\n bin_range = range\r\n from builtins import range\r\n\r\n if np.isscalar(x):\r\n x = [x]\r\n\r\n if bins is None:\r\n bins = rcParams['hist.bins']\r\n\r\n # Validate string inputs here to avoid cluttering subsequent code.\r\n cbook._check_in_list(['bar', 'barstacked', 'step', 'stepfilled'],\r\n histtype=histtype)\r\n cbook._check_in_list(['left', 'mid', 'right'], align=align)\r\n cbook._check_in_list(['horizontal', 'vertical'],\r\n orientation=orientation)\r\n\r\n if histtype == 'barstacked' and not stacked:\r\n stacked = True\r\n\r\n # Massage 'x' for processing.\r\n x = cbook._reshape_2D(x, 'x')\r\n nx = len(x) # number of datasets\r\n\r\n # Process unit information\r\n # Unit conversion is done individually on each dataset\r\n self._process_unit_info(xdata=x[0], kwargs=kwargs)\r\n x = [self.convert_xunits(xi) for xi in x]\r\n\r\n if bin_range is not None:\r\n bin_range = self.convert_xunits(bin_range)\r\n\r\n if not cbook.is_scalar_or_string(bins):\r\n bins = self.convert_xunits(bins)\r\n\r\n # We need to do to 'weights' what was done to 'x'\r\n if weights is not None:\r\n w = cbook._reshape_2D(weights, 'weights')\r\n else:\r\n w = [None] * nx\r\n\r\n if len(w) != nx:\r\n raise ValueError('weights should have the same shape as x')\r\n\r\n input_empty = True\r\n for xi, wi in zip(x, w):\r\n len_xi = len(xi)\r\n if wi is not None and len(wi) != len_xi:\r\n raise ValueError('weights should have the same shape as x')\r\n if len_xi:\r\n input_empty = False\r\n\r\n if color is None:\r\n color = [self._get_lines.get_next_color() for i in range(nx)]\r\n else:\r\n color = mcolors.to_rgba_array(color)\r\n if len(color) != nx:\r\n raise ValueError(f\"The 'color' keyword argument must have one \"\r\n f\"color per dataset, but {nx} datasets and \"\r\n f\"{len(color)} colors were provided\")\r\n\r\n hist_kwargs = dict()\r\n\r\n # if the bin_range is not given, compute without nan numpy\r\n # does not do this for us when guessing the range (but will\r\n # happily ignore nans when computing the histogram).\r\n if bin_range is None:\r\n xmin = np.inf\r\n xmax = -np.inf\r\n for xi in x:\r\n if len(xi):\r\n # python's min/max ignore nan,\r\n # np.minnan returns nan for all nan input\r\n xmin = min(xmin, np.nanmin(xi))\r\n xmax = max(xmax, np.nanmax(xi))\r\n if xmin <= xmax: # Only happens if we have seen a finite value.\r\n bin_range = (xmin, xmax)\r\n\r\n # If bins are not specified either explicitly or via range,\r\n # we need to figure out the range required for all datasets,\r\n # and supply that to np.histogram.\r\n if not input_empty and len(x) > 1:\r\n if weights is not None:\r\n _w = np.concatenate(w)\r\n else:\r\n _w = None\r\n bins = np.histogram_bin_edges(\r\n np.concatenate(x), bins, bin_range, _w)\r\n else:\r\n hist_kwargs['range'] = bin_range\r\n\r\n density = bool(density)\r\n if density and not stacked:\r\n hist_kwargs['density'] = density\r\n\r\n # List to store all the top coordinates of the histograms\r\n tops = [] # Will have shape (n_datasets, n_bins).\r\n # Loop through datasets\r\n for i in range(nx):\r\n # this will automatically overwrite bins,\r\n # so that each histogram uses the same bins\r\n m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs)\r\n tops.append(m)\r\n tops = np.array(tops, float) # causes problems later if it's an int\r\n if stacked:\r\n tops = tops.cumsum(axis=0)\r\n # If a stacked density plot, normalize so the area of all the\r\n # stacked histograms together is 1\r\n if density:\r\n tops = (tops / np.diff(bins)) / tops[-1].sum()\r\n if cumulative:\r\n slc = slice(None)\r\n if isinstance(cumulative, Number) and cumulative < 0:\r\n slc = slice(None, None, -1)\r\n if density:\r\n tops = (tops * np.diff(bins))[:, slc].cumsum(axis=1)[:, slc]\r\n else:\r\n tops = tops[:, slc].cumsum(axis=1)[:, slc]\r\n\r\n patches = []\r\n\r\n # Save autoscale state for later restoration; turn autoscaling\r\n # off so we can do it all a single time at the end, instead\r\n # of having it done by bar or fill and then having to be redone.\r\n _saved_autoscalex = self.get_autoscalex_on()\r\n _saved_autoscaley = self.get_autoscaley_on()\r\n self.set_autoscalex_on(False)\r\n self.set_autoscaley_on(False)\r\n\r\n if histtype.startswith('bar'):\r\n\r\n totwidth = np.diff(bins)\r\n\r\n if rwidth is not None:\r\n dr = np.clip(rwidth, 0, 1)\r\n elif (len(tops) > 1 and\r\n ((not stacked) or rcParams['_internal.classic_mode'])):\r\n dr = 0.8\r\n else:\r\n dr = 1.0\r\n\r\n if histtype == 'bar' and not stacked:\r\n width = dr * totwidth / nx\r\n dw = width\r\n boffset = -0.5 * dr * totwidth * (1 - 1 / nx)\r\n elif histtype == 'barstacked' or stacked:\r\n width = dr * totwidth\r\n boffset, dw = 0.0, 0.0\r\n\r\n if align == 'mid':\r\n boffset += 0.5 * totwidth\r\n elif align == 'right':\r\n boffset += totwidth\r\n\r\n if orientation == 'horizontal':\r\n _barfunc = self.barh\r\n bottom_kwarg = 'left'\r\n else: # orientation == 'vertical'\r\n _barfunc = self.bar\r\n bottom_kwarg = 'bottom'\r\n\r\n for m, c in zip(tops, color):\r\n if bottom is None:\r\n bottom = np.zeros(len(m))\r\n if stacked:\r\n height = m - bottom\r\n else:\r\n height = m\r\n bars = _barfunc(bins[:-1]+boffset, height, width,\r\n align='center', log=log,\r\n color=c, **{bottom_kwarg: bottom})\r\n patches.append(bars)\r\n if stacked:\r\n bottom[:] = m\r\n boffset += dw\r\n # Remove stickies from all bars but the lowest ones, as otherwise\r\n # margin expansion would be unable to cross the stickies in the\r\n # middle of the bars.\r\n for bars in patches[1:]:\r\n for patch in bars:\r\n patch.sticky_edges.x[:] = patch.sticky_edges.y[:] = []\r\n\r\n elif histtype.startswith('step'):\r\n # these define the perimeter of the polygon\r\n x = np.zeros(4 * len(bins) - 3)\r\n y = np.zeros(4 * len(bins) - 3)\r\n\r\n x[0:2*len(bins)-1:2], x[1:2*len(bins)-1:2] = bins, bins[:-1]\r\n x[2*len(bins)-1:] = x[1:2*len(bins)-1][::-1]\r\n\r\n if bottom is None:\r\n bottom = 0\r\n\r\n y[1:2*len(bins)-1:2] = y[2:2*len(bins):2] = bottom\r\n y[2*len(bins)-1:] = y[1:2*len(bins)-1][::-1]\r\n\r\n if log:\r\n if orientation == 'horizontal':\r\n self.set_xscale('log', nonpositive='clip')\r\n else: # orientation == 'vertical'\r\n self.set_yscale('log', nonpositive='clip')\r\n\r\n if align == 'left':\r\n x -= 0.5*(bins[1]-bins[0])\r\n elif align == 'right':\r\n x += 0.5*(bins[1]-bins[0])\r\n\r\n # If fill kwarg is set, it will be passed to the patch collection,\r\n # overriding this\r\n fill = (histtype == 'stepfilled')\r\n\r\n xvals, yvals = [], []\r\n for m in tops:\r\n if stacked:\r\n # top of the previous polygon becomes the bottom\r\n y[2*len(bins)-1:] = y[1:2*len(bins)-1][::-1]\r\n # set the top of this polygon\r\n y[1:2*len(bins)-1:2] = y[2:2*len(bins):2] = m + bottom\r\n\r\n # The starting point of the polygon has not yet been\r\n # updated. So far only the endpoint was adjusted. This\r\n # assignment closes the polygon. The redundant endpoint is\r\n # later discarded (for step and stepfilled).\r\n y[0] = y[-1]\r\n\r\n if orientation == 'horizontal':\r\n xvals.append(y.copy())\r\n yvals.append(x.copy())\r\n else:\r\n xvals.append(x.copy())\r\n yvals.append(y.copy())\r\n\r\n # stepfill is closed, step is not\r\n split = -1 if fill else 2 * len(bins)\r\n # add patches in reverse order so that when stacking,\r\n # items lower in the stack are plotted on top of\r\n # items higher in the stack\r\n for x, y, c in reversed(list(zip(xvals, yvals, color))):\r\n patches.append(self.fill(\r\n x[:split], y[:split],\r\n closed=True if fill else None,\r\n facecolor=c,\r\n edgecolor=None if fill else c,\r\n fill=fill if fill else None,\r\n zorder=None if fill else mlines.Line2D.zorder))\r\n for patch_list in patches:\r\n for patch in patch_list:\r\n if orientation == 'vertical':\r\n patch.sticky_edges.y.append(0)\r\n elif orientation == 'horizontal':\r\n patch.sticky_edges.x.append(0)\r\n\r\n # we return patches, so put it back in the expected order\r\n patches.reverse()\r\n\r\n self.set_autoscalex_on(_saved_autoscalex)\r\n self.set_autoscaley_on(_saved_autoscaley)\r\n self._request_autoscale_view()\r\n\r\n # If None, make all labels None (via zip_longest below); otherwise,\r\n # cast each element to str, but keep a single str as it.\r\n labels = [] if label is None else np.atleast_1d(np.asarray(label, str))\r\n for patch, lbl in itertools.zip_longest(patches, labels):\r\n if patch:\r\n p = patch[0]\r\n p.update(kwargs)\r\n if lbl is not None:\r\n p.set_label(lbl)\r\n for p in patch[1:]:\r\n p.update(kwargs)\r\n p.set_label('_nolegend_')\r\n\r\n if nx == 1:\r\n return tops[0], bins, patches[0]\r\n else:\r\n patch_type = (\"BarContainer\" if histtype.startswith(\"bar\")\r\n else \"List[Polygon]\")\r\n return tops, bins, cbook.silent_list(patch_type, patches)\r\n\r\n @_preprocess_data(replace_names=[\"x\", \"y\", \"weights\"])\r\n @docstring.dedent_interpd\r\n def hist2d(self, x, y, bins=10, range=None, density=False, weights=None,\r\n cmin=None, cmax=None, **kwargs):\r\n \"\"\"\r\n Make a 2D histogram plot.\r\n\r\n Parameters\r\n ----------\r\n x, y : array-like, shape (n, )\r\n Input values\r\n\r\n bins : None or int or [int, int] or array-like or [array, array]\r\n\r\n The bin specification:\r\n\r\n - If int, the number of bins for the two dimensions\r\n (nx=ny=bins).\r\n - If ``[int, int]``, the number of bins in each dimension\r\n (nx, ny = bins).\r\n - If array-like, the bin edges for the two dimensions\r\n (x_edges=y_edges=bins).\r\n - If ``[array, array]``, the bin edges in each dimension\r\n (x_edges, y_edges = bins).\r\n\r\n The default value is 10.\r\n\r\n range : array-like shape(2, 2), optional\r\n The leftmost and rightmost edges of the bins along each dimension\r\n (if not specified explicitly in the bins parameters): ``[[xmin,\r\n xmax], [ymin, ymax]]``. All values outside of this range will be\r\n considered outliers and not tallied in the histogram.\r\n\r\n density : bool, default: False\r\n Normalize histogram. See the documentation for the *density*\r\n parameter of `~.Axes.hist` for more details.\r\n\r\n weights : array-like, shape (n, ), optional\r\n An array of values w_i weighing each sample (x_i, y_i).\r\n\r\n cmin, cmax : float, default: None\r\n All bins that has count less than *cmin* or more than *cmax* will\r\n not be displayed (set to NaN before passing to imshow) and these\r\n count values in the return value count histogram will also be set\r\n to nan upon return.\r\n\r\n Returns\r\n -------\r\n h : 2D array\r\n The bi-dimensional histogram of samples x and y. Values in x are\r\n histogrammed along the first dimension and values in y are\r\n histogrammed along the second dimension.\r\n xedges : 1D array\r\n The bin edges along the x axis.\r\n yedges : 1D array\r\n The bin edges along the y axis.\r\n image : `~.matplotlib.collections.QuadMesh`\r\n\r\n Other Parameters\r\n ----------------\r\n cmap : Colormap or str, optional\r\n A `.colors.Colormap` instance. If not set, use rc settings.\r\n\r\n norm : Normalize, optional\r\n A `.colors.Normalize` instance is used to\r\n scale luminance data to ``[0, 1]``. If not set, defaults to\r\n `.colors.Normalize()`.\r\n\r\n vmin/vmax : None or scalar, optional\r\n Arguments passed to the `~.colors.Normalize` instance.\r\n\r\n alpha : ``0 <= scalar <= 1`` or ``None``, optional\r\n The alpha blending value.\r\n\r\n **kwargs\r\n Additional parameters are passed along to the\r\n `~.Axes.pcolormesh` method and `~matplotlib.collections.QuadMesh`\r\n constructor.\r\n\r\n See Also\r\n --------\r\n hist : 1D histogram plotting\r\n\r\n Notes\r\n -----\r\n - Currently ``hist2d`` calculates its own axis limits, and any limits\r\n previously set are ignored.\r\n - Rendering the histogram with a logarithmic color scale is\r\n accomplished by passing a `.colors.LogNorm` instance to the *norm*\r\n keyword argument. Likewise, power-law normalization (similar\r\n in effect to gamma correction) can be accomplished with\r\n `.colors.PowerNorm`.\r\n \"\"\"\r\n\r\n h, xedges, yedges = np.histogram2d(x, y, bins=bins, range=range,\r\n density=density, weights=weights)\r\n\r\n if cmin is not None:\r\n h[h < cmin] = None\r\n if cmax is not None:\r\n h[h > cmax] = None\r\n\r\n pc = self.pcolormesh(xedges, yedges, h.T, **kwargs)\r\n self.set_xlim(xedges[0], xedges[-1])\r\n self.set_ylim(yedges[0], yedges[-1])\r\n\r\n return h, xedges, yedges, pc\r\n\r\n @_preprocess_data(replace_names=[\"x\"])\r\n @docstring.dedent_interpd\r\n def psd(self, x, NFFT=None, Fs=None, Fc=None, detrend=None,\r\n window=None, noverlap=None, pad_to=None,\r\n sides=None, scale_by_freq=None, return_line=None, **kwargs):\r\n r\"\"\"\r\n Plot the power spectral density.\r\n\r\n The power spectral density :math:`P_{xx}` by Welch's average\r\n periodogram method. The vector *x* is divided into *NFFT* length\r\n segments. Each segment is detrended by function *detrend* and\r\n windowed by function *window*. *noverlap* gives the length of\r\n the overlap between segments. The :math:`|\\mathrm{fft}(i)|^2`\r\n of each segment :math:`i` are averaged to compute :math:`P_{xx}`,\r\n with a scaling to correct for power loss due to windowing.\r\n\r\n If len(*x*) < *NFFT*, it will be zero padded to *NFFT*.\r\n\r\n Parameters\r\n ----------\r\n x : 1-D array or sequence\r\n Array or sequence containing the data\r\n\r\n %(Spectral)s\r\n\r\n %(PSD)s\r\n\r\n noverlap : int, default: 0 (no overlap)\r\n The number of points of overlap between segments.\r\n\r\n Fc : int, default: 0\r\n The center frequency of *x*, which offsets the x extents of the\r\n plot to reflect the frequency range used when a signal is acquired\r\n and then filtered and downsampled to baseband.\r\n\r\n return_line : bool, default: False\r\n Whether to include the line object plotted in the returned values.\r\n\r\n Returns\r\n -------\r\n Pxx : 1-D array\r\n The values for the power spectrum :math:`P_{xx}` before scaling\r\n (real valued).\r\n\r\n freqs : 1-D array\r\n The frequencies corresponding to the elements in *Pxx*.\r\n\r\n line : `~matplotlib.lines.Line2D`\r\n The line created by this function.\r\n Only returned if *return_line* is True.\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs\r\n Keyword arguments control the `.Line2D` properties:\r\n\r\n %(_Line2D_docstr)s\r\n\r\n See Also\r\n --------\r\n specgram\r\n Differs in the default overlap; in not returning the mean of the\r\n segment periodograms; in returning the times of the segments; and\r\n in plotting a colormap instead of a line.\r\n magnitude_spectrum\r\n Plots the magnitude spectrum.\r\n csd\r\n Plots the spectral density between two signals.\r\n\r\n Notes\r\n -----\r\n For plotting, the power is plotted as\r\n :math:`10\\log_{10}(P_{xx})` for decibels, though *Pxx* itself\r\n is returned.\r\n\r\n References\r\n ----------\r\n Bendat & Piersol -- Random Data: Analysis and Measurement Procedures,\r\n John Wiley & Sons (1986)\r\n \"\"\"\r\n if Fc is None:\r\n Fc = 0\r\n\r\n pxx, freqs = mlab.psd(x=x, NFFT=NFFT, Fs=Fs, detrend=detrend,\r\n window=window, noverlap=noverlap, pad_to=pad_to,\r\n sides=sides, scale_by_freq=scale_by_freq)\r\n freqs += Fc\r\n\r\n if scale_by_freq in (None, True):\r\n psd_units = 'dB/Hz'\r\n else:\r\n psd_units = 'dB'\r\n\r\n line = self.plot(freqs, 10 * np.log10(pxx), **kwargs)\r\n self.set_xlabel('Frequency')\r\n self.set_ylabel('Power Spectral Density (%s)' % psd_units)\r\n self.grid(True)\r\n vmin, vmax = self.viewLim.intervaly\r\n intv = vmax - vmin\r\n logi = int(np.log10(intv))\r\n if logi == 0:\r\n logi = .1\r\n step = 10 * logi\r\n ticks = np.arange(math.floor(vmin), math.ceil(vmax) + 1, step)\r\n self.set_yticks(ticks)\r\n\r\n if return_line is None or not return_line:\r\n return pxx, freqs\r\n else:\r\n return pxx, freqs, line\r\n\r\n @_preprocess_data(replace_names=[\"x\", \"y\"], label_namer=\"y\")\r\n @docstring.dedent_interpd\r\n def csd(self, x, y, NFFT=None, Fs=None, Fc=None, detrend=None,\r\n window=None, noverlap=None, pad_to=None,\r\n sides=None, scale_by_freq=None, return_line=None, **kwargs):\r\n r\"\"\"\r\n Plot the cross-spectral density.\r\n\r\n The cross spectral density :math:`P_{xy}` by Welch's average\r\n periodogram method. The vectors *x* and *y* are divided into\r\n *NFFT* length segments. Each segment is detrended by function\r\n *detrend* and windowed by function *window*. *noverlap* gives\r\n the length of the overlap between segments. The product of\r\n the direct FFTs of *x* and *y* are averaged over each segment\r\n to compute :math:`P_{xy}`, with a scaling to correct for power\r\n loss due to windowing.\r\n\r\n If len(*x*) < *NFFT* or len(*y*) < *NFFT*, they will be zero\r\n padded to *NFFT*.\r\n\r\n Parameters\r\n ----------\r\n x, y : 1-D arrays or sequences\r\n Arrays or sequences containing the data.\r\n\r\n %(Spectral)s\r\n\r\n %(PSD)s\r\n\r\n noverlap : int, default: 0 (no overlap)\r\n The number of points of overlap between segments.\r\n\r\n Fc : int, default: 0\r\n The center frequency of *x*, which offsets the x extents of the\r\n plot to reflect the frequency range used when a signal is acquired\r\n and then filtered and downsampled to baseband.\r\n\r\n return_line : bool, default: False\r\n Whether to include the line object plotted in the returned values.\r\n\r\n Returns\r\n -------\r\n Pxy : 1-D array\r\n The values for the cross spectrum :math:`P_{xy}` before scaling\r\n (complex valued).\r\n\r\n freqs : 1-D array\r\n The frequencies corresponding to the elements in *Pxy*.\r\n\r\n line : `~matplotlib.lines.Line2D`\r\n The line created by this function.\r\n Only returned if *return_line* is True.\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs\r\n Keyword arguments control the `.Line2D` properties:\r\n\r\n %(_Line2D_docstr)s\r\n\r\n See Also\r\n --------\r\n psd : is equivalent to setting ``y = x``.\r\n\r\n Notes\r\n -----\r\n For plotting, the power is plotted as\r\n :math:`10 \\log_{10}(P_{xy})` for decibels, though :math:`P_{xy}` itself\r\n is returned.\r\n\r\n References\r\n ----------\r\n Bendat & Piersol -- Random Data: Analysis and Measurement Procedures,\r\n John Wiley & Sons (1986)\r\n \"\"\"\r\n if Fc is None:\r\n Fc = 0\r\n\r\n pxy, freqs = mlab.csd(x=x, y=y, NFFT=NFFT, Fs=Fs, detrend=detrend,\r\n window=window, noverlap=noverlap, pad_to=pad_to,\r\n sides=sides, scale_by_freq=scale_by_freq)\r\n # pxy is complex\r\n freqs += Fc\r\n\r\n line = self.plot(freqs, 10 * np.log10(np.abs(pxy)), **kwargs)\r\n self.set_xlabel('Frequency')\r\n self.set_ylabel('Cross Spectrum Magnitude (dB)')\r\n self.grid(True)\r\n vmin, vmax = self.viewLim.intervaly\r\n\r\n intv = vmax - vmin\r\n step = 10 * int(np.log10(intv))\r\n\r\n ticks = np.arange(math.floor(vmin), math.ceil(vmax) + 1, step)\r\n self.set_yticks(ticks)\r\n\r\n if return_line is None or not return_line:\r\n return pxy, freqs\r\n else:\r\n return pxy, freqs, line\r\n\r\n @_preprocess_data(replace_names=[\"x\"])\r\n @docstring.dedent_interpd\r\n def magnitude_spectrum(self, x, Fs=None, Fc=None, window=None,\r\n pad_to=None, sides=None, scale=None,\r\n **kwargs):\r\n \"\"\"\r\n Plot the magnitude spectrum.\r\n\r\n Compute the magnitude spectrum of *x*. Data is padded to a\r\n length of *pad_to* and the windowing function *window* is applied to\r\n the signal.\r\n\r\n Parameters\r\n ----------\r\n x : 1-D array or sequence\r\n Array or sequence containing the data.\r\n\r\n %(Spectral)s\r\n\r\n %(Single_Spectrum)s\r\n\r\n scale : {'default', 'linear', 'dB'}\r\n The scaling of the values in the *spec*. 'linear' is no scaling.\r\n 'dB' returns the values in dB scale, i.e., the dB amplitude\r\n (20 * log10). 'default' is 'linear'.\r\n\r\n Fc : int, default: 0\r\n The center frequency of *x*, which offsets the x extents of the\r\n plot to reflect the frequency range used when a signal is acquired\r\n and then filtered and downsampled to baseband.\r\n\r\n Returns\r\n -------\r\n spectrum : 1-D array\r\n The values for the magnitude spectrum before scaling (real valued).\r\n\r\n freqs : 1-D array\r\n The frequencies corresponding to the elements in *spectrum*.\r\n\r\n line : `~matplotlib.lines.Line2D`\r\n The line created by this function.\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs\r\n Keyword arguments control the `.Line2D` properties:\r\n\r\n %(_Line2D_docstr)s\r\n\r\n See Also\r\n --------\r\n psd\r\n Plots the power spectral density.\r\n angle_spectrum\r\n Plots the angles of the corresponding frequencies.\r\n phase_spectrum\r\n Plots the phase (unwrapped angle) of the corresponding frequencies.\r\n specgram\r\n Can plot the magnitude spectrum of segments within the signal in a\r\n colormap.\r\n \"\"\"\r\n if Fc is None:\r\n Fc = 0\r\n\r\n spec, freqs = mlab.magnitude_spectrum(x=x, Fs=Fs, window=window,\r\n pad_to=pad_to, sides=sides)\r\n freqs += Fc\r\n\r\n yunits = cbook._check_getitem(\r\n {None: 'energy', 'default': 'energy', 'linear': 'energy',\r\n 'dB': 'dB'},\r\n scale=scale)\r\n if yunits == 'energy':\r\n Z = spec\r\n else: # yunits == 'dB'\r\n Z = 20. * np.log10(spec)\r\n\r\n line, = self.plot(freqs, Z, **kwargs)\r\n self.set_xlabel('Frequency')\r\n self.set_ylabel('Magnitude (%s)' % yunits)\r\n\r\n return spec, freqs, line\r\n\r\n @_preprocess_data(replace_names=[\"x\"])\r\n @docstring.dedent_interpd\r\n def angle_spectrum(self, x, Fs=None, Fc=None, window=None,\r\n pad_to=None, sides=None, **kwargs):\r\n \"\"\"\r\n Plot the angle spectrum.\r\n\r\n Compute the angle spectrum (wrapped phase spectrum) of *x*.\r\n Data is padded to a length of *pad_to* and the windowing function\r\n *window* is applied to the signal.\r\n\r\n Parameters\r\n ----------\r\n x : 1-D array or sequence\r\n Array or sequence containing the data.\r\n\r\n %(Spectral)s\r\n\r\n %(Single_Spectrum)s\r\n\r\n Fc : int, default: 0\r\n The center frequency of *x*, which offsets the x extents of the\r\n plot to reflect the frequency range used when a signal is acquired\r\n and then filtered and downsampled to baseband.\r\n\r\n Returns\r\n -------\r\n spectrum : 1-D array\r\n The values for the angle spectrum in radians (real valued).\r\n\r\n freqs : 1-D array\r\n The frequencies corresponding to the elements in *spectrum*.\r\n\r\n line : `~matplotlib.lines.Line2D`\r\n The line created by this function.\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs\r\n Keyword arguments control the `.Line2D` properties:\r\n\r\n %(_Line2D_docstr)s\r\n\r\n See Also\r\n --------\r\n magnitude_spectrum\r\n Plots the magnitudes of the corresponding frequencies.\r\n phase_spectrum\r\n Plots the unwrapped version of this function.\r\n specgram\r\n Can plot the angle spectrum of segments within the signal in a\r\n colormap.\r\n \"\"\"\r\n if Fc is None:\r\n Fc = 0\r\n\r\n spec, freqs = mlab.angle_spectrum(x=x, Fs=Fs, window=window,\r\n pad_to=pad_to, sides=sides)\r\n freqs += Fc\r\n\r\n lines = self.plot(freqs, spec, **kwargs)\r\n self.set_xlabel('Frequency')\r\n self.set_ylabel('Angle (radians)')\r\n\r\n return spec, freqs, lines[0]\r\n\r\n @_preprocess_data(replace_names=[\"x\"])\r\n @docstring.dedent_interpd\r\n def phase_spectrum(self, x, Fs=None, Fc=None, window=None,\r\n pad_to=None, sides=None, **kwargs):\r\n \"\"\"\r\n Plot the phase spectrum.\r\n\r\n Compute the phase spectrum (unwrapped angle spectrum) of *x*.\r\n Data is padded to a length of *pad_to* and the windowing function\r\n *window* is applied to the signal.\r\n\r\n Parameters\r\n ----------\r\n x : 1-D array or sequence\r\n Array or sequence containing the data\r\n\r\n %(Spectral)s\r\n\r\n %(Single_Spectrum)s\r\n\r\n Fc : int, default: 0\r\n The center frequency of *x*, which offsets the x extents of the\r\n plot to reflect the frequency range used when a signal is acquired\r\n and then filtered and downsampled to baseband.\r\n\r\n Returns\r\n -------\r\n spectrum : 1-D array\r\n The values for the phase spectrum in radians (real valued).\r\n\r\n freqs : 1-D array\r\n The frequencies corresponding to the elements in *spectrum*.\r\n\r\n line : `~matplotlib.lines.Line2D`\r\n The line created by this function.\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs\r\n Keyword arguments control the `.Line2D` properties:\r\n\r\n %(_Line2D_docstr)s\r\n\r\n See Also\r\n --------\r\n magnitude_spectrum\r\n Plots the magnitudes of the corresponding frequencies.\r\n angle_spectrum\r\n Plots the wrapped version of this function.\r\n specgram\r\n Can plot the phase spectrum of segments within the signal in a\r\n colormap.\r\n \"\"\"\r\n if Fc is None:\r\n Fc = 0\r\n\r\n spec, freqs = mlab.phase_spectrum(x=x, Fs=Fs, window=window,\r\n pad_to=pad_to, sides=sides)\r\n freqs += Fc\r\n\r\n lines = self.plot(freqs, spec, **kwargs)\r\n self.set_xlabel('Frequency')\r\n self.set_ylabel('Phase (radians)')\r\n\r\n return spec, freqs, lines[0]\r\n\r\n @_preprocess_data(replace_names=[\"x\", \"y\"])\r\n @docstring.dedent_interpd\r\n def cohere(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,\r\n window=mlab.window_hanning, noverlap=0, pad_to=None,\r\n sides='default', scale_by_freq=None, **kwargs):\r\n r\"\"\"\r\n Plot the coherence between *x* and *y*.\r\n\r\n Plot the coherence between *x* and *y*. Coherence is the\r\n normalized cross spectral density:\r\n\r\n .. math::\r\n\r\n C_{xy} = \\frac{|P_{xy}|^2}{P_{xx}P_{yy}}\r\n\r\n Parameters\r\n ----------\r\n %(Spectral)s\r\n\r\n %(PSD)s\r\n\r\n noverlap : int, default: 0 (no overlap)\r\n The number of points of overlap between blocks.\r\n\r\n Fc : int, default: 0\r\n The center frequency of *x*, which offsets the x extents of the\r\n plot to reflect the frequency range used when a signal is acquired\r\n and then filtered and downsampled to baseband.\r\n\r\n Returns\r\n -------\r\n Cxy : 1-D array\r\n The coherence vector.\r\n\r\n freqs : 1-D array\r\n The frequencies for the elements in *Cxy*.\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs\r\n Keyword arguments control the `.Line2D` properties:\r\n\r\n %(_Line2D_docstr)s\r\n\r\n References\r\n ----------\r\n Bendat & Piersol -- Random Data: Analysis and Measurement Procedures,\r\n John Wiley & Sons (1986)\r\n \"\"\"\r\n cxy, freqs = mlab.cohere(x=x, y=y, NFFT=NFFT, Fs=Fs, detrend=detrend,\r\n window=window, noverlap=noverlap,\r\n scale_by_freq=scale_by_freq)\r\n freqs += Fc\r\n\r\n self.plot(freqs, cxy, **kwargs)\r\n self.set_xlabel('Frequency')\r\n self.set_ylabel('Coherence')\r\n self.grid(True)\r\n\r\n return cxy, freqs\r\n\r\n @_preprocess_data(replace_names=[\"x\"])\r\n @docstring.dedent_interpd\r\n def specgram(self, x, NFFT=None, Fs=None, Fc=None, detrend=None,\r\n window=None, noverlap=None,\r\n cmap=None, xextent=None, pad_to=None, sides=None,\r\n scale_by_freq=None, mode=None, scale=None,\r\n vmin=None, vmax=None, **kwargs):\r\n \"\"\"\r\n Plot a spectrogram.\r\n\r\n Compute and plot a spectrogram of data in *x*. Data are split into\r\n *NFFT* length segments and the spectrum of each section is\r\n computed. The windowing function *window* is applied to each\r\n segment, and the amount of overlap of each segment is\r\n specified with *noverlap*. The spectrogram is plotted as a colormap\r\n (using imshow).\r\n\r\n Parameters\r\n ----------\r\n x : 1-D array or sequence\r\n Array or sequence containing the data.\r\n\r\n %(Spectral)s\r\n\r\n %(PSD)s\r\n\r\n mode : {'default', 'psd', 'magnitude', 'angle', 'phase'}\r\n What sort of spectrum to use. Default is 'psd', which takes the\r\n power spectral density. 'magnitude' returns the magnitude\r\n spectrum. 'angle' returns the phase spectrum without unwrapping.\r\n 'phase' returns the phase spectrum with unwrapping.\r\n\r\n noverlap : int\r\n The number of points of overlap between blocks. The\r\n default value is 128.\r\n\r\n scale : {'default', 'linear', 'dB'}\r\n The scaling of the values in the *spec*. 'linear' is no scaling.\r\n 'dB' returns the values in dB scale. When *mode* is 'psd',\r\n this is dB power (10 * log10). Otherwise this is dB amplitude\r\n (20 * log10). 'default' is 'dB' if *mode* is 'psd' or\r\n 'magnitude' and 'linear' otherwise. This must be 'linear'\r\n if *mode* is 'angle' or 'phase'.\r\n\r\n Fc : int, default: 0\r\n The center frequency of *x*, which offsets the x extents of the\r\n plot to reflect the frequency range used when a signal is acquired\r\n and then filtered and downsampled to baseband.\r\n\r\n cmap : `.Colormap`, default: :rc:`image.cmap`\r\n\r\n xextent : *None* or (xmin, xmax)\r\n The image extent along the x-axis. The default sets *xmin* to the\r\n left border of the first bin (*spectrum* column) and *xmax* to the\r\n right border of the last bin. Note that for *noverlap>0* the width\r\n of the bins is smaller than those of the segments.\r\n\r\n **kwargs\r\n Additional keyword arguments are passed on to `~.axes.Axes.imshow`\r\n which makes the specgram image.\r\n\r\n Returns\r\n -------\r\n spectrum : 2-D array\r\n Columns are the periodograms of successive segments.\r\n\r\n freqs : 1-D array\r\n The frequencies corresponding to the rows in *spectrum*.\r\n\r\n t : 1-D array\r\n The times corresponding to midpoints of segments (i.e., the columns\r\n in *spectrum*).\r\n\r\n im : `.AxesImage`\r\n The image created by imshow containing the spectrogram.\r\n\r\n See Also\r\n --------\r\n psd\r\n Differs in the default overlap; in returning the mean of the\r\n segment periodograms; in not returning times; and in generating a\r\n line plot instead of colormap.\r\n magnitude_spectrum\r\n A single spectrum, similar to having a single segment when *mode*\r\n is 'magnitude'. Plots a line instead of a colormap.\r\n angle_spectrum\r\n A single spectrum, similar to having a single segment when *mode*\r\n is 'angle'. Plots a line instead of a colormap.\r\n phase_spectrum\r\n A single spectrum, similar to having a single segment when *mode*\r\n is 'phase'. Plots a line instead of a colormap.\r\n\r\n Notes\r\n -----\r\n The parameters *detrend* and *scale_by_freq* do only apply when *mode*\r\n is set to 'psd'.\r\n \"\"\"\r\n if NFFT is None:\r\n NFFT = 256 # same default as in mlab.specgram()\r\n if Fc is None:\r\n Fc = 0 # same default as in mlab._spectral_helper()\r\n if noverlap is None:\r\n noverlap = 128 # same default as in mlab.specgram()\r\n if Fs is None:\r\n Fs = 2 # same default as in mlab._spectral_helper()\r\n\r\n if mode == 'complex':\r\n raise ValueError('Cannot plot a complex specgram')\r\n\r\n if scale is None or scale == 'default':\r\n if mode in ['angle', 'phase']:\r\n scale = 'linear'\r\n else:\r\n scale = 'dB'\r\n elif mode in ['angle', 'phase'] and scale == 'dB':\r\n raise ValueError('Cannot use dB scale with angle or phase mode')\r\n\r\n spec, freqs, t = mlab.specgram(x=x, NFFT=NFFT, Fs=Fs,\r\n detrend=detrend, window=window,\r\n noverlap=noverlap, pad_to=pad_to,\r\n sides=sides,\r\n scale_by_freq=scale_by_freq,\r\n mode=mode)\r\n\r\n if scale == 'linear':\r\n Z = spec\r\n elif scale == 'dB':\r\n if mode is None or mode == 'default' or mode == 'psd':\r\n Z = 10. * np.log10(spec)\r\n else:\r\n Z = 20. * np.log10(spec)\r\n else:\r\n raise ValueError('Unknown scale %s', scale)\r\n\r\n Z = np.flipud(Z)\r\n\r\n if xextent is None:\r\n # padding is needed for first and last segment:\r\n pad_xextent = (NFFT-noverlap) / Fs / 2\r\n xextent = np.min(t) - pad_xextent, np.max(t) + pad_xextent\r\n xmin, xmax = xextent\r\n freqs += Fc\r\n extent = xmin, xmax, freqs[0], freqs[-1]\r\n im = self.imshow(Z, cmap, extent=extent, vmin=vmin, vmax=vmax,\r\n **kwargs)\r\n self.axis('auto')\r\n\r\n return spec, freqs, t, im\r\n\r\n @docstring.dedent_interpd\r\n def spy(self, Z, precision=0, marker=None, markersize=None,\r\n aspect='equal', origin=\"upper\", **kwargs):\r\n \"\"\"\r\n Plot the sparsity pattern of a 2D array.\r\n\r\n This visualizes the non-zero values of the array.\r\n\r\n Two plotting styles are available: image and marker. Both\r\n are available for full arrays, but only the marker style\r\n works for `scipy.sparse.spmatrix` instances.\r\n\r\n **Image style**\r\n\r\n If *marker* and *markersize* are *None*, `~.Axes.imshow` is used. Any\r\n extra remaining keyword arguments are passed to this method.\r\n\r\n **Marker style**\r\n\r\n If *Z* is a `scipy.sparse.spmatrix` or *marker* or *markersize* are\r\n *None*, a `.Line2D` object will be returned with the value of marker\r\n determining the marker type, and any remaining keyword arguments\r\n passed to `~.Axes.plot`.\r\n\r\n Parameters\r\n ----------\r\n Z : array-like (M, N)\r\n The array to be plotted.\r\n\r\n precision : float or 'present', default: 0\r\n If *precision* is 0, any non-zero value will be plotted. Otherwise,\r\n values of :math:`|Z| > precision` will be plotted.\r\n\r\n For `scipy.sparse.spmatrix` instances, you can also\r\n pass 'present'. In this case any value present in the array\r\n will be plotted, even if it is identically zero.\r\n\r\n aspect : {'equal', 'auto', None} or float, default: 'equal'\r\n The aspect ratio of the axes. This parameter is particularly\r\n relevant for images since it determines whether data pixels are\r\n square.\r\n\r\n This parameter is a shortcut for explicitly calling\r\n `.Axes.set_aspect`. See there for further details.\r\n\r\n - 'equal': Ensures an aspect ratio of 1. Pixels will be square.\r\n - 'auto': The axes is kept fixed and the aspect is adjusted so\r\n that the data fit in the axes. In general, this will result in\r\n non-square pixels.\r\n - *None*: Use :rc:`image.aspect`.\r\n\r\n origin : {'upper', 'lower'}, default: :rc:`image.origin`\r\n Place the [0, 0] index of the array in the upper left or lower left\r\n corner of the axes. The convention 'upper' is typically used for\r\n matrices and images.\r\n\r\n Returns\r\n -------\r\n `~matplotlib.image.AxesImage` or `.Line2D`\r\n The return type depends on the plotting style (see above).\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs\r\n The supported additional parameters depend on the plotting style.\r\n\r\n For the image style, you can pass the following additional\r\n parameters of `~.Axes.imshow`:\r\n\r\n - *cmap*\r\n - *alpha*\r\n - *url*\r\n - any `.Artist` properties (passed on to the `.AxesImage`)\r\n\r\n For the marker style, you can pass any `.Line2D` property except\r\n for *linestyle*:\r\n\r\n %(_Line2D_docstr)s\r\n \"\"\"\r\n if marker is None and markersize is None and hasattr(Z, 'tocoo'):\r\n marker = 's'\r\n cbook._check_in_list([\"upper\", \"lower\"], origin=origin)\r\n if marker is None and markersize is None:\r\n Z = np.asarray(Z)\r\n mask = np.abs(Z) > precision\r\n\r\n if 'cmap' not in kwargs:\r\n kwargs['cmap'] = mcolors.ListedColormap(['w', 'k'],\r\n name='binary')\r\n if 'interpolation' in kwargs:\r\n raise TypeError(\r\n \"spy() got an unexpected keyword argument 'interpolation'\")\r\n ret = self.imshow(mask, interpolation='nearest', aspect=aspect,\r\n origin=origin, **kwargs)\r\n else:\r\n if hasattr(Z, 'tocoo'):\r\n c = Z.tocoo()\r\n if precision == 'present':\r\n y = c.row\r\n x = c.col\r\n else:\r\n nonzero = np.abs(c.data) > precision\r\n y = c.row[nonzero]\r\n x = c.col[nonzero]\r\n else:\r\n Z = np.asarray(Z)\r\n nonzero = np.abs(Z) > precision\r\n y, x = np.nonzero(nonzero)\r\n if marker is None:\r\n marker = 's'\r\n if markersize is None:\r\n markersize = 10\r\n if 'linestyle' in kwargs:\r\n raise TypeError(\r\n \"spy() got an unexpected keyword argument 'linestyle'\")\r\n ret = mlines.Line2D(\r\n x, y, linestyle='None', marker=marker, markersize=markersize,\r\n **kwargs)\r\n self.add_line(ret)\r\n nr, nc = Z.shape\r\n self.set_xlim(-0.5, nc - 0.5)\r\n if origin == \"upper\":\r\n self.set_ylim(nr - 0.5, -0.5)\r\n else:\r\n self.set_ylim(-0.5, nr - 0.5)\r\n self.set_aspect(aspect)\r\n self.title.set_y(1.05)\r\n if origin == \"upper\":\r\n self.xaxis.tick_top()\r\n else:\r\n self.xaxis.tick_bottom()\r\n self.xaxis.set_ticks_position('both')\r\n self.xaxis.set_major_locator(\r\n mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True))\r\n self.yaxis.set_major_locator(\r\n mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True))\r\n return ret\r\n\r\n def matshow(self, Z, **kwargs):\r\n \"\"\"\r\n Plot the values of a 2D matrix or array as color-coded image.\r\n\r\n The matrix will be shown the way it would be printed, with the first\r\n row at the top. Row and column numbering is zero-based.\r\n\r\n Parameters\r\n ----------\r\n Z : array-like(M, N)\r\n The matrix to be displayed.\r\n\r\n Returns\r\n -------\r\n `~matplotlib.image.AxesImage`\r\n\r\n Other Parameters\r\n ----------------\r\n **kwargs : `~matplotlib.axes.Axes.imshow` arguments\r\n\r\n See Also\r\n --------\r\n imshow : More general function to plot data on a 2D regular raster.\r\n\r\n Notes\r\n -----\r\n This is just a convenience function wrapping `.imshow` to set useful\r\n defaults for displaying a matrix. In particular:\r\n\r\n - Set ``origin='upper'``.\r\n - Set ``interpolation='nearest'``.\r\n - Set ``aspect='equal'``.\r\n - Ticks are placed to the left and above.\r\n - Ticks are formatted to show integer indices.\r\n\r\n \"\"\"\r\n Z = np.asanyarray(Z)\r\n kw = {'origin': 'upper',\r\n 'interpolation': 'nearest',\r\n 'aspect': 'equal', # (already the imshow default)\r\n **kwargs}\r\n im = self.imshow(Z, **kw)\r\n self.title.set_y(1.05)\r\n self.xaxis.tick_top()\r\n self.xaxis.set_ticks_position('both')\r\n self.xaxis.set_major_locator(\r\n mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True))\r\n self.yaxis.set_major_locator(\r\n mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True))\r\n return im\r\n\r\n @_preprocess_data(replace_names=[\"dataset\"])\r\n def violinplot(self, dataset, positions=None, vert=True, widths=0.5,\r\n showmeans=False, showextrema=True, showmedians=False,\r\n quantiles=None, points=100, bw_method=None):\r\n \"\"\"\r\n Make a violin plot.\r\n\r\n Make a violin plot for each column of *dataset* or each vector in\r\n sequence *dataset*. Each filled area extends to represent the\r\n entire data range, with optional lines at the mean, the median,\r\n the minimum, the maximum, and user-specified quantiles.\r\n\r\n Parameters\r\n ----------\r\n dataset : Array or a sequence of vectors.\r\n The input data.\r\n\r\n positions : array-like, default: [1, 2, ..., n]\r\n Sets the positions of the violins. The ticks and limits are\r\n automatically set to match the positions.\r\n\r\n vert : bool, default: True.\r\n If true, creates a vertical violin plot.\r\n Otherwise, creates a horizontal violin plot.\r\n\r\n widths : array-like, default: 0.5\r\n Either a scalar or a vector that sets the maximal width of\r\n each violin. The default is 0.5, which uses about half of the\r\n available horizontal space.\r\n\r\n showmeans : bool, default: False\r\n If `True`, will toggle rendering of the means.\r\n\r\n showextrema : bool, default: True\r\n If `True`, will toggle rendering of the extrema.\r\n\r\n showmedians : bool, default: False\r\n If `True`, will toggle rendering of the medians.\r\n\r\n quantiles : array-like, default: None\r\n If not None, set a list of floats in interval [0, 1] for each violin,\r\n which stands for the quantiles that will be rendered for that\r\n violin.\r\n\r\n points : int, default: 100\r\n Defines the number of points to evaluate each of the\r\n gaussian kernel density estimations at.\r\n\r\n bw_method : str, scalar or callable, optional\r\n The method used to calculate the estimator bandwidth. This can be\r\n 'scott', 'silverman', a scalar constant or a callable. If a\r\n scalar, this will be used directly as `kde.factor`. If a\r\n callable, it should take a `GaussianKDE` instance as its only\r\n parameter and return a scalar. If None (default), 'scott' is used.\r\n\r\n Returns\r\n -------\r\n dict\r\n A dictionary mapping each component of the violinplot to a\r\n list of the corresponding collection instances created. The\r\n dictionary has the following keys:\r\n\r\n - ``bodies``: A list of the `~.collections.PolyCollection`\r\n instances containing the filled area of each violin.\r\n\r\n - ``cmeans``: A `~.collections.LineCollection` instance that marks\r\n the mean values of each of the violin's distribution.\r\n\r\n - ``cmins``: A `~.collections.LineCollection` instance that marks\r\n the bottom of each violin's distribution.\r\n\r\n - ``cmaxes``: A `~.collections.LineCollection` instance that marks\r\n the top of each violin's distribution.\r\n\r\n - ``cbars``: A `~.collections.LineCollection` instance that marks\r\n the centers of each violin's distribution.\r\n\r\n - ``cmedians``: A `~.collections.LineCollection` instance that\r\n marks the median values of each of the violin's distribution.\r\n\r\n - ``cquantiles``: A `~.collections.LineCollection` instance created\r\n to identify the quantile values of each of the violin's\r\n distribution.\r\n\r\n \"\"\"\r\n\r\n def _kde_method(X, coords):\r\n if hasattr(X, 'values'): # support pandas.Series\r\n X = X.values\r\n # fallback gracefully if the vector contains only one value\r\n if np.all(X[0] == X):\r\n return (X[0] == coords).astype(float)\r\n kde = mlab.GaussianKDE(X, bw_method)\r\n return kde.evaluate(coords)\r\n\r\n vpstats = cbook.violin_stats(dataset, _kde_method, points=points,\r\n quantiles=quantiles)\r\n return self.violin(vpstats, positions=positions, vert=vert,\r\n widths=widths, showmeans=showmeans,\r\n showextrema=showextrema, showmedians=showmedians)\r\n\r\n def violin(self, vpstats, positions=None, vert=True, widths=0.5,\r\n showmeans=False, showextrema=True, showmedians=False):\r\n \"\"\"\r\n Drawing function for violin plots.\r\n\r\n Draw a violin plot for each column of *vpstats*. Each filled area\r\n extends to represent the entire data range, with optional lines at the\r\n mean, the median, the minimum, the maximum, and the quantiles values.\r\n\r\n Parameters\r\n ----------\r\n vpstats : list of dicts\r\n A list of dictionaries containing stats for each violin plot.\r\n Required keys are:\r\n\r\n - ``coords``: A list of scalars containing the coordinates that\r\n the violin's kernel density estimate were evaluated at.\r\n\r\n - ``vals``: A list of scalars containing the values of the\r\n kernel density estimate at each of the coordinates given\r\n in *coords*.\r\n\r\n - ``mean``: The mean value for this violin's dataset.\r\n\r\n - ``median``: The median value for this violin's dataset.\r\n\r\n - ``min``: The minimum value for this violin's dataset.\r\n\r\n - ``max``: The maximum value for this violin's dataset.\r\n\r\n Optional keys are:\r\n\r\n - ``quantiles``: A list of scalars containing the quantile values\r\n for this violin's dataset.\r\n\r\n positions : array-like, default: [1, 2, ..., n]\r\n Sets the positions of the violins. The ticks and limits are\r\n automatically set to match the positions.\r\n\r\n vert : bool, default: True.\r\n If true, plots the violins vertically.\r\n Otherwise, plots the violins horizontally.\r\n\r\n widths : array-like, default: 0.5\r\n Either a scalar or a vector that sets the maximal width of\r\n each violin. The default is 0.5, which uses about half of the\r\n available horizontal space.\r\n\r\n showmeans : bool, default: False\r\n If true, will toggle rendering of the means.\r\n\r\n showextrema : bool, default: True\r\n If true, will toggle rendering of the extrema.\r\n\r\n showmedians : bool, default: False\r\n If true, will toggle rendering of the medians.\r\n\r\n Returns\r\n -------\r\n dict\r\n A dictionary mapping each component of the violinplot to a\r\n list of the corresponding collection instances created. The\r\n dictionary has the following keys:\r\n\r\n - ``bodies``: A list of the `~.collections.PolyCollection`\r\n instances containing the filled area of each violin.\r\n\r\n - ``cmeans``: A `~.collections.LineCollection` instance that marks\r\n the mean values of each of the violin's distribution.\r\n\r\n - ``cmins``: A `~.collections.LineCollection` instance that marks\r\n the bottom of each violin's distribution.\r\n\r\n - ``cmaxes``: A `~.collections.LineCollection` instance that marks\r\n the top of each violin's distribution.\r\n\r\n - ``cbars``: A `~.collections.LineCollection` instance that marks\r\n the centers of each violin's distribution.\r\n\r\n - ``cmedians``: A `~.collections.LineCollection` instance that\r\n marks the median values of each of the violin's distribution.\r\n\r\n - ``cquantiles``: A `~.collections.LineCollection` instance created\r\n to identify the quantiles values of each of the violin's\r\n distribution.\r\n\r\n \"\"\"\r\n\r\n # Statistical quantities to be plotted on the violins\r\n means = []\r\n mins = []\r\n maxes = []\r\n medians = []\r\n quantiles = np.asarray([])\r\n\r\n # Collections to be returned\r\n artists = {}\r\n\r\n N = len(vpstats)\r\n datashape_message = (\"List of violinplot statistics and `{0}` \"\r\n \"values must have the same length\")\r\n\r\n # Validate positions\r\n if positions is None:\r\n positions = range(1, N + 1)\r\n elif len(positions) != N:\r\n raise ValueError(datashape_message.format(\"positions\"))\r\n\r\n # Validate widths\r\n if np.isscalar(widths):\r\n widths = [widths] * N\r\n elif len(widths) != N:\r\n raise ValueError(datashape_message.format(\"widths\"))\r\n\r\n # Calculate ranges for statistics lines\r\n pmins = -0.25 * np.array(widths) + positions\r\n pmaxes = 0.25 * np.array(widths) + positions\r\n\r\n # Check whether we are rendering vertically or horizontally\r\n if vert:\r\n fill = self.fill_betweenx\r\n perp_lines = self.hlines\r\n par_lines = self.vlines\r\n else:\r\n fill = self.fill_between\r\n perp_lines = self.vlines\r\n par_lines = self.hlines\r\n\r\n if rcParams['_internal.classic_mode']:\r\n fillcolor = 'y'\r\n edgecolor = 'r'\r\n else:\r\n fillcolor = edgecolor = self._get_lines.get_next_color()\r\n\r\n # Render violins\r\n bodies = []\r\n for stats, pos, width in zip(vpstats, positions, widths):\r\n # The 0.5 factor reflects the fact that we plot from v-p to\r\n # v+p\r\n vals = np.array(stats['vals'])\r\n vals = 0.5 * width * vals / vals.max()\r\n bodies += [fill(stats['coords'],\r\n -vals + pos,\r\n vals + pos,\r\n facecolor=fillcolor,\r\n alpha=0.3)]\r\n means.append(stats['mean'])\r\n mins.append(stats['min'])\r\n maxes.append(stats['max'])\r\n medians.append(stats['median'])\r\n q = stats.get('quantiles')\r\n if q is not None:\r\n # If exist key quantiles, assume it's a list of floats\r\n quantiles = np.concatenate((quantiles, q))\r\n artists['bodies'] = bodies\r\n\r\n # Render means\r\n if showmeans:\r\n artists['cmeans'] = perp_lines(means, pmins, pmaxes,\r\n colors=edgecolor)\r\n\r\n # Render extrema\r\n if showextrema:\r\n artists['cmaxes'] = perp_lines(maxes, pmins, pmaxes,\r\n colors=edgecolor)\r\n artists['cmins'] = perp_lines(mins, pmins, pmaxes,\r\n colors=edgecolor)\r\n artists['cbars'] = par_lines(positions, mins, maxes,\r\n colors=edgecolor)\r\n\r\n # Render medians\r\n if showmedians:\r\n artists['cmedians'] = perp_lines(medians,\r\n pmins,\r\n pmaxes,\r\n colors=edgecolor)\r\n\r\n # Render quantile values\r\n if quantiles.size > 0:\r\n # Recalculate ranges for statistics lines for quantiles.\r\n # ppmins are the left end of quantiles lines\r\n ppmins = np.asarray([])\r\n # pmaxes are the right end of quantiles lines\r\n ppmaxs = np.asarray([])\r\n for stats, cmin, cmax in zip(vpstats, pmins, pmaxes):\r\n q = stats.get('quantiles')\r\n if q is not None:\r\n ppmins = np.concatenate((ppmins, [cmin] * np.size(q)))\r\n ppmaxs = np.concatenate((ppmaxs, [cmax] * np.size(q)))\r\n # Start rendering\r\n artists['cquantiles'] = perp_lines(quantiles, ppmins, ppmaxs,\r\n colors=edgecolor)\r\n\r\n return artists\r\n\r\n # Methods that are entirely implemented in other modules.\r\n\r\n table = mtable.table\r\n\r\n # args can by either Y or y1, y2, ... and all should be replaced\r\n stackplot = _preprocess_data()(mstack.stackplot)\r\n\r\n streamplot = _preprocess_data(\r\n replace_names=[\"x\", \"y\", \"u\", \"v\", \"start_points\"])(mstream.streamplot)\r\n\r\n tricontour = mtri.tricontour\r\n tricontourf = mtri.tricontourf\r\n tripcolor = mtri.tripcolor\r\n triplot = mtri.triplot\r\n" ]
[ [ "torch.conv2d", "torch.conv3d", "torch.conv_transpose1d", "torch.conv1d", "torch.conv_transpose2d", "torch.conv_transpose3d" ], [ "torch.testing._internal.common_methods_invocations.unpack_variables", "torch.Size", "torch.jit.trace", "torch.randint", "torch.jit._disable_emit_hooks", "torch.zeros", "torch.set_default_dtype", "torch.randn", "torch.full", "torch.ones", "torch.empty", "torch.is_tensor", "torch.tensor", "torch.testing._internal.common_methods_invocations.create_input", "torch.rand", "torch.jit.CompilationUnit" ], [ "matplotlib.pyplot.gca", "matplotlib.font_manager.findfont", "matplotlib.testing.decorators.check_figures_equal", "matplotlib.pyplot.subplots", "matplotlib.pyplot.savefig", "matplotlib.testing.decorators.image_comparison", "numpy.all", "matplotlib.mathtext.MathTextParser", "matplotlib.ft2font.FT2Font", "matplotlib.pyplot.text", "matplotlib.pyplot.figure" ], [ "torch.cat", "torch.zeros", "torch.nn.EmbeddingBag", "torch.testing._internal.common_distributed.requires_gloo", "torch.ones", "torch.distributed.autograd.backward", "torch.distributed.barrier", "torch.distributed.rpc.rpc_sync", "torch.distributed.autograd.context", "torch.rand", "torch.testing._internal.common_distributed.skip_if_lt_x_gpu", "torch.LongTensor", "torch.testing._internal.common_distributed.requires_nccl", "torch.zeros_like", "torch.nn.Linear", "torch.distributed.rpc.remote", "torch.distributed.autograd.get_gradients", "torch.distributed.destroy_process_group", "torch.nn.parallel.DistributedDataParallel", "torch.distributed.nn.RemoteModule", "torch.Tensor", "torch.manual_seed", "torch.distributed.new_group", "torch.nn.ReLU" ], [ "torch.distributions.utils.broadcast_all", "torch.Size", "torch.tan", "torch.atan" ], [ "torch._C.default_generator.set_state", "torch._C.default_generator.seed", "torch._C.default_generator.initial_seed", "torch._C.default_generator.manual_seed", "torch._C.default_generator.get_state" ], [ "torch.norm_except_dim", "torch._weight_norm", "torch.nn.parameter.Parameter" ], [ "numpy.nanmax", "matplotlib.cbook.boxplot_stats", "numpy.cumsum", "numpy.all", "matplotlib.cbook._check_in_list", "matplotlib.legend._parse_legend_args", "matplotlib.ticker.FixedLocator", "numpy.ma.is_masked", "matplotlib.patches.PathPatch", "numpy.asanyarray", "numpy.diff", "matplotlib.cbook._check_getitem", "matplotlib.cbook.safe_masked_invalid", "matplotlib.mlab.GaussianKDE", "numpy.zeros", "matplotlib.docstring.copy", "matplotlib.cbook._reshape_2D", "matplotlib.collections.BrokenBarHCollection", "matplotlib.cbook.delete_masked_points", "matplotlib.cbook._str_lower_equal", "matplotlib.mlab.magnitude_spectrum", "numpy.log10", "numpy.floor", "numpy.array", "matplotlib.axes._secondary_axes.SecondaryAxis", "matplotlib.colors.LogNorm", "matplotlib.transforms.IdentityTransform", "numpy.shape", "matplotlib.cbook.warn_deprecated", "numpy.isinf", "numpy.vstack", "matplotlib.colors.to_rgba_array", "numpy.expand_dims", "numpy.asarray", "numpy.concatenate", "matplotlib.transforms.nonsingular", "matplotlib.legend.Legend", "matplotlib.cbook.normalize_kwargs", "numpy.ma.getmaskarray", "numpy.ma.ravel", "numpy.atleast_1d", "numpy.size", "matplotlib.cbook.violin_stats", "matplotlib.text.Text", "matplotlib.transforms.Bbox.from_bounds", "matplotlib.docstring.dedent_interpd", "matplotlib.contour.QuadContourSet", "numpy.ma.asarray", "numpy.min", "matplotlib.transforms.AffineDeltaTransform", "numpy.ndim", "matplotlib.cbook.silent_list", "matplotlib.container.BarContainer", "matplotlib.mlab.psd", "numpy.ma.filled", "matplotlib.cbook._rename_parameter", "numpy.ma.column_stack", "matplotlib.mlab.angle_spectrum", "matplotlib._preprocess_data", "numpy.ones", "numpy.ptp", "numpy.isscalar", "matplotlib.collections.PolyCollection", "matplotlib.quiver.Quiver", "matplotlib.axes._base._process_plot_format", "numpy.empty", "numpy.linspace", "matplotlib.collections.QuadMesh", "matplotlib.rcParams.items", "numpy.flipud", "numpy.rad2deg", "numpy.round", "matplotlib.mlab.specgram", "matplotlib.patches.Polygon", "numpy.histogram", "matplotlib.mlab.csd", "numpy.hstack", "matplotlib.collections.EventCollection", "numpy.clip", "numpy.interp", "numpy.column_stack", "matplotlib.text.Annotation", "matplotlib.cbook._combine_masks", "matplotlib.mlab.phase_spectrum", "numpy.nonzero", "matplotlib.collections.LineCollection", "numpy.isnan", "matplotlib.patches.Rectangle", "numpy.iterable", "numpy.correlate", "matplotlib.transforms.TransformedBbox", "numpy.histogram2d", "matplotlib.quiver.Barbs", "numpy.ma.masked_invalid", "matplotlib.patches.ConnectionPatch", "numpy.dot", "matplotlib.ticker.FixedFormatter", "numpy.nanmin", "matplotlib.cbook.is_scalar_or_string", "numpy.max", "numpy.any", "matplotlib.lines._AxLine", "matplotlib.cbook._local_over_kwdict", "matplotlib.cbook.safe_first_element", "matplotlib.cbook._warn_external", "numpy.arange", "numpy.stack", "matplotlib.quiver.QuiverKey", "numpy.ravel", "matplotlib.mlab.cohere", "matplotlib.cbook._delete_parameter", "matplotlib.image.AxesImage", "matplotlib.patches.Shadow", "matplotlib.container.StemContainer", "matplotlib.colors.ListedColormap", "matplotlib.image.PcolorImage", "matplotlib.cbook.contiguous_regions", "numpy.add.at", "numpy.ma.reshape", "matplotlib.markers.MarkerStyle", "numpy.abs", "matplotlib.patches.FancyArrow", "matplotlib.lines.Line2D", "matplotlib.legend._get_legend_handles_labels", "numpy.sort", "matplotlib.ticker.MaxNLocator" ] ]
[ { "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": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
gpspelle/pose-estimation
[ "1dec506ac8abf00616dc0fe76bf476ccdfd6b93e" ]
[ "tf_pose/slim/nets/mobilenet/mobilenet.py" ]
[ "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Mobilenet Base Class.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport collections\nimport contextlib\nimport copy\nimport os\n\nimport tensorflow as tf\n\n\nslim = tf.contrib.slim\n\n\[email protected]_arg_scope\ndef apply_activation(x, name=None, activation_fn=None):\n return activation_fn(x, name=name) if activation_fn else x\n\n\ndef _fixed_padding(inputs, kernel_size, rate=1):\n \"\"\"Pads the input along the spatial dimensions independently of input size.\n\n Pads the input such that if it was used in a convolution with 'VALID' padding,\n the output would have the same dimensions as if the unpadded input was used\n in a convolution with 'SAME' padding.\n\n Args:\n inputs: A tensor of size [batch, height_in, width_in, channels].\n kernel_size: The kernel to be used in the conv2d or max_pool2d operation.\n rate: An integer, rate for atrous convolution.\n\n Returns:\n output: A tensor of size [batch, height_out, width_out, channels] with the\n input, either intact (if kernel_size == 1) or padded (if kernel_size > 1).\n \"\"\"\n kernel_size_effective = [kernel_size[0] + (kernel_size[0] - 1) * (rate - 1),\n kernel_size[0] + (kernel_size[0] - 1) * (rate - 1)]\n pad_total = [kernel_size_effective[0] - 1, kernel_size_effective[1] - 1]\n pad_beg = [pad_total[0] // 2, pad_total[1] // 2]\n pad_end = [pad_total[0] - pad_beg[0], pad_total[1] - pad_beg[1]]\n padded_inputs = tf.pad(inputs, [[0, 0], [pad_beg[0], pad_end[0]],\n [pad_beg[1], pad_end[1]], [0, 0]])\n return padded_inputs\n\n\ndef _make_divisible(v, divisor, min_value=None):\n if min_value is None:\n min_value = divisor\n new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)\n # Make sure that round down does not go down by more than 10%.\n if new_v < 0.9 * v:\n new_v += divisor\n return new_v\n\n\[email protected]\ndef _set_arg_scope_defaults(defaults):\n \"\"\"Sets arg scope defaults for all items present in defaults.\n\n Args:\n defaults: dictionary/list of pairs, containing a mapping from\n function to a dictionary of default args.\n\n Yields:\n context manager where all defaults are set.\n \"\"\"\n if hasattr(defaults, 'items'):\n items = list(defaults.items())\n else:\n items = defaults\n if not items:\n yield\n else:\n func, default_arg = items[0]\n with slim.arg_scope(func, **default_arg):\n with _set_arg_scope_defaults(items[1:]):\n yield\n\n\[email protected]_arg_scope\ndef depth_multiplier(output_params,\n multiplier,\n divisible_by=8,\n min_depth=8,\n **unused_kwargs):\n if 'num_outputs' not in output_params:\n return\n d = output_params['num_outputs']\n output_params['num_outputs'] = _make_divisible(d * multiplier, divisible_by,\n min_depth)\n\n\n_Op = collections.namedtuple('Op', ['op', 'params', 'multiplier_func'])\n\n\ndef op(opfunc, **params):\n multiplier = params.pop('multiplier_transorm', depth_multiplier)\n return _Op(opfunc, params=params, multiplier_func=multiplier)\n\n\nclass NoOpScope(object):\n \"\"\"No-op context manager.\"\"\"\n\n def __enter__(self):\n return None\n\n def __exit__(self, exc_type, exc_value, traceback):\n return False\n\n\ndef safe_arg_scope(funcs, **kwargs):\n \"\"\"Returns `slim.arg_scope` with all None arguments removed.\n\n Arguments:\n funcs: Functions to pass to `arg_scope`.\n **kwargs: Arguments to pass to `arg_scope`.\n\n Returns:\n arg_scope or No-op context manager.\n\n Note: can be useful if None value should be interpreted as \"do not overwrite\n this parameter value\".\n \"\"\"\n filtered_args = {name: value for name, value in kwargs.items()\n if value is not None}\n if filtered_args:\n return slim.arg_scope(funcs, **filtered_args)\n else:\n return NoOpScope()\n\n\[email protected]_arg_scope\ndef mobilenet_base( # pylint: disable=invalid-name\n inputs,\n conv_defs,\n multiplier=1.0,\n final_endpoint=None,\n output_stride=None,\n use_explicit_padding=False,\n scope=None,\n is_training=False):\n \"\"\"Mobilenet base network.\n\n Constructs a network from inputs to the given final endpoint. By default\n the network is constructed in inference mode. To create network\n in training mode use:\n\n with slim.arg_scope(mobilenet.training_scope()):\n logits, endpoints = mobilenet_base(...)\n\n Args:\n inputs: a tensor of shape [batch_size, height, width, channels].\n conv_defs: A list of op(...) layers specifying the net architecture.\n multiplier: Float multiplier for the depth (number of channels)\n for all convolution ops. The value must be greater than zero. Typical\n usage will be to set this value in (0, 1) to reduce the number of\n parameters or computation cost of the model.\n final_endpoint: The name of last layer, for early termination for\n for V1-based networks: last layer is \"layer_14\", for V2: \"layer_20\"\n output_stride: An integer that specifies the requested ratio of input to\n output spatial resolution. If not None, then we invoke atrous convolution\n if necessary to prevent the network from reducing the spatial resolution\n of the activation maps. Allowed values are 1 or any even number, excluding\n zero. Typical values are 8 (accurate fully convolutional mode), 16\n (fast fully convolutional mode), and 32 (classification mode).\n\n NOTE- output_stride relies on all consequent operators to support dilated\n operators via \"rate\" parameter. This might require wrapping non-conv\n operators to operate properly.\n\n use_explicit_padding: Use 'VALID' padding for convolutions, but prepad\n inputs so that the output dimensions are the same as if 'SAME' padding\n were used.\n scope: optional variable scope.\n is_training: How to setup batch_norm and other ops. Note: most of the time\n this does not need be set directly. Use mobilenet.training_scope() to set\n up training instead. This parameter is here for backward compatibility\n only. It is safe to set it to the value matching\n training_scope(is_training=...). It is also safe to explicitly set\n it to False, even if there is outer training_scope set to to training.\n (The network will be built in inference mode). If this is set to None,\n no arg_scope is added for slim.batch_norm's is_training parameter.\n\n Returns:\n tensor_out: output tensor.\n end_points: a set of activations for external use, for example summaries or\n losses.\n\n Raises:\n ValueError: depth_multiplier <= 0, or the target output_stride is not\n allowed.\n \"\"\"\n if multiplier <= 0:\n raise ValueError('multiplier is not greater than zero.')\n\n # Set conv defs defaults and overrides.\n conv_defs_defaults = conv_defs.get('defaults', {})\n conv_defs_overrides = conv_defs.get('overrides', {})\n if use_explicit_padding:\n conv_defs_overrides = copy.deepcopy(conv_defs_overrides)\n conv_defs_overrides[\n (slim.conv2d, slim.separable_conv2d)] = {'padding': 'VALID'}\n\n if output_stride is not None:\n if output_stride == 0 or (output_stride > 1 and output_stride % 2):\n raise ValueError('Output stride must be None, 1 or a multiple of 2.')\n\n # a) Set the tensorflow scope\n # b) set padding to default: note we might consider removing this\n # since it is also set by mobilenet_scope\n # c) set all defaults\n # d) set all extra overrides.\n with _scope_all(scope, default_scope='Mobilenet'), \\\n safe_arg_scope([slim.batch_norm], is_training=is_training), \\\n _set_arg_scope_defaults(conv_defs_defaults), \\\n _set_arg_scope_defaults(conv_defs_overrides):\n # The current_stride variable keeps track of the output stride of the\n # activations, i.e., the running product of convolution strides up to the\n # current network layer. This allows us to invoke atrous convolution\n # whenever applying the next convolution would result in the activations\n # having output stride larger than the target output_stride.\n current_stride = 1\n\n # The atrous convolution rate parameter.\n rate = 1\n\n net = inputs\n # Insert default parameters before the base scope which includes\n # any custom overrides set in mobilenet.\n end_points = {}\n scopes = {}\n for i, opdef in enumerate(conv_defs['spec']):\n params = dict(opdef.params)\n opdef.multiplier_func(params, multiplier)\n stride = params.get('stride', 1)\n if output_stride is not None and current_stride == output_stride:\n # If we have reached the target output_stride, then we need to employ\n # atrous convolution with stride=1 and multiply the atrous rate by the\n # current unit's stride for use in subsequent layers.\n layer_stride = 1\n layer_rate = rate\n rate *= stride\n else:\n layer_stride = stride\n layer_rate = 1\n current_stride *= stride\n # Update params.\n params['stride'] = layer_stride\n # Only insert rate to params if rate > 1.\n if layer_rate > 1:\n params['rate'] = layer_rate\n # Set padding\n if use_explicit_padding:\n if 'kernel_size' in params:\n net = _fixed_padding(net, params['kernel_size'], layer_rate)\n else:\n params['use_explicit_padding'] = True\n\n end_point = 'layer_%d' % (i + 1)\n try:\n net = opdef.op(net, **params)\n except Exception:\n print('Failed to create op %i: %r params: %r' % (i, opdef, params))\n raise\n end_points[end_point] = net\n scope = os.path.dirname(net.name)\n scopes[scope] = end_point\n if final_endpoint is not None and end_point == final_endpoint:\n break\n\n # Add all tensors that end with 'output' to\n # endpoints\n for t in net.graph.get_operations():\n scope = os.path.dirname(t.name)\n bn = os.path.basename(t.name)\n if scope in scopes and t.name.endswith('output'):\n end_points[scopes[scope] + '/' + bn] = t.outputs[0]\n return net, end_points\n\n\[email protected]\ndef _scope_all(scope, default_scope=None):\n with tf.variable_scope(scope, default_name=default_scope) as s,\\\n tf.name_scope(s.original_name_scope):\n yield s\n\n\[email protected]_arg_scope\ndef mobilenet(inputs,\n num_classes=1001,\n prediction_fn=slim.softmax,\n reuse=None,\n scope='Mobilenet',\n base_only=False,\n **mobilenet_args):\n \"\"\"Mobilenet model for classification, supports both V1 and V2.\n\n Note: default mode is inference, use mobilenet.training_scope to create\n training network.\n\n\n Args:\n inputs: a tensor of shape [batch_size, height, width, channels].\n num_classes: number of predicted classes. If 0 or None, the logits layer\n is omitted and the input features to the logits layer (before dropout)\n are returned instead.\n prediction_fn: a function to get predictions out of logits\n (default softmax).\n reuse: whether or not the network and its variables should be reused. To be\n able to reuse 'scope' must be given.\n scope: Optional variable_scope.\n base_only: if True will only create the base of the network (no pooling\n and no logits).\n **mobilenet_args: passed to mobilenet_base verbatim.\n - conv_defs: list of conv defs\n - multiplier: Float multiplier for the depth (number of channels)\n for all convolution ops. The value must be greater than zero. Typical\n usage will be to set this value in (0, 1) to reduce the number of\n parameters or computation cost of the model.\n - output_stride: will ensure that the last layer has at most total stride.\n If the architecture calls for more stride than that provided\n (e.g. output_stride=16, but the architecture has 5 stride=2 operators),\n it will replace output_stride with fractional convolutions using Atrous\n Convolutions.\n\n Returns:\n logits: the pre-softmax activations, a tensor of size\n [batch_size, num_classes]\n end_points: a dictionary from components of the network to the corresponding\n activation tensor.\n\n Raises:\n ValueError: Input rank is invalid.\n \"\"\"\n is_training = mobilenet_args.get('is_training', False)\n input_shape = inputs.get_shape().as_list()\n if len(input_shape) != 4:\n raise ValueError('Expected rank 4 input, was: %d' % len(input_shape))\n\n with tf.variable_scope(scope, 'Mobilenet', reuse=reuse) as scope:\n inputs = tf.identity(inputs, 'input')\n net, end_points = mobilenet_base(inputs, scope=scope, **mobilenet_args)\n if base_only:\n return net, end_points\n\n net = tf.identity(net, name='embedding')\n\n with tf.variable_scope('Logits'):\n net = global_pool(net)\n end_points['global_pool'] = net\n if not num_classes:\n return net, end_points\n net = slim.dropout(net, scope='Dropout', is_training=is_training)\n # 1 x 1 x num_classes\n # Note: legacy scope name.\n logits = slim.conv2d(\n net,\n num_classes, [1, 1],\n activation_fn=None,\n normalizer_fn=None,\n biases_initializer=tf.zeros_initializer(),\n scope='Conv2d_1c_1x1')\n\n logits = tf.squeeze(logits, [1, 2])\n\n logits = tf.identity(logits, name='output')\n end_points['Logits'] = logits\n if prediction_fn:\n end_points['Predictions'] = prediction_fn(logits, 'Predictions')\n return logits, end_points\n\n\ndef global_pool(input_tensor, pool_op=tf.nn.avg_pool):\n \"\"\"Applies avg pool to produce 1x1 output.\n\n NOTE: This function is funcitonally equivalenet to reduce_mean, but it has\n baked in average pool which has better support across hardware.\n\n Args:\n input_tensor: input tensor\n pool_op: pooling op (avg pool is default)\n Returns:\n a tensor batch_size x 1 x 1 x depth.\n \"\"\"\n shape = input_tensor.get_shape().as_list()\n if shape[1] is None or shape[2] is None:\n kernel_size = tf.convert_to_tensor(\n [1, tf.shape(input_tensor)[1],\n tf.shape(input_tensor)[2], 1])\n else:\n kernel_size = [1, shape[1], shape[2], 1]\n output = pool_op(\n input_tensor, ksize=kernel_size, strides=[1, 1, 1, 1], padding='VALID')\n # Recover output shape, for unknown shape.\n output.set_shape([None, 1, 1, None])\n return output\n\n\ndef training_scope(is_training=True,\n weight_decay=0.00004,\n stddev=0.09,\n dropout_keep_prob=0.8,\n bn_decay=0.997):\n \"\"\"Defines Mobilenet training scope.\n\n Usage:\n with tf.contrib.slim.arg_scope(mobilenet.training_scope()):\n logits, endpoints = mobilenet_v2.mobilenet(input_tensor)\n\n # the network created will be trainble with dropout/batch norm\n # initialized appropriately.\n Args:\n is_training: if set to False this will ensure that all customizations are\n set to non-training mode. This might be helpful for code that is reused\n across both training/evaluation, but most of the time training_scope with\n value False is not needed. If this is set to None, the parameters is not\n added to the batch_norm arg_scope.\n\n weight_decay: The weight decay to use for regularizing the model.\n stddev: Standard deviation for initialization, if negative uses xavier.\n dropout_keep_prob: dropout keep probability (not set if equals to None).\n bn_decay: decay for the batch norm moving averages (not set if equals to\n None).\n\n Returns:\n An argument scope to use via arg_scope.\n \"\"\"\n # Note: do not introduce parameters that would change the inference\n # model here (for example whether to use bias), modify conv_def instead.\n batch_norm_params = {\n 'decay': bn_decay,\n 'is_training': is_training\n }\n if stddev < 0:\n weight_intitializer = slim.initializers.xavier_initializer()\n else:\n weight_intitializer = tf.truncated_normal_initializer(stddev=stddev)\n\n # Set weight_decay for weights in Conv and FC layers.\n with slim.arg_scope(\n [slim.conv2d, slim.fully_connected, slim.separable_conv2d],\n weights_initializer=weight_intitializer,\n normalizer_fn=slim.batch_norm), \\\n slim.arg_scope([mobilenet_base, mobilenet], is_training=is_training),\\\n safe_arg_scope([slim.batch_norm], **batch_norm_params), \\\n safe_arg_scope([slim.dropout], is_training=is_training,\n keep_prob=dropout_keep_prob), \\\n slim.arg_scope([slim.conv2d], \\\n weights_regularizer=slim.l2_regularizer(weight_decay)), \\\n slim.arg_scope([slim.separable_conv2d], weights_regularizer=None) as s:\n return s\n" ]
[ [ "tensorflow.shape", "tensorflow.zeros_initializer", "tensorflow.identity", "tensorflow.truncated_normal_initializer", "tensorflow.squeeze", "tensorflow.name_scope", "tensorflow.pad", "tensorflow.variable_scope" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.4", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
tao2020/Horizon
[ "0f9a1b16ddd6e5a8ac98e61acd227aae7c201b57" ]
[ "ml/rl/workflow/dqn_workflow.py" ]
[ "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.\n\nimport logging\nimport sys\nfrom typing import Dict\n\nimport numpy as np\nfrom ml.rl.evaluation.evaluator import Evaluator\nfrom ml.rl.preprocessing.preprocessor import Preprocessor\nfrom ml.rl.preprocessing.sparse_to_dense import PandasSparseToDenseProcessor\nfrom ml.rl.readers.json_dataset_reader import JSONDatasetReader\nfrom ml.rl.tensorboardX import summary_writer_context\nfrom ml.rl.thrift.core.ttypes import (\n DiscreteActionModelParameters,\n NormalizationParameters,\n RainbowDQNParameters,\n RLParameters,\n TrainingParameters,\n)\nfrom ml.rl.training.dqn_trainer import DQNTrainer\nfrom ml.rl.workflow.base_workflow import BaseWorkflow\nfrom ml.rl.workflow.helpers import (\n export_trainer_and_predictor,\n minibatch_size_multiplier,\n parse_args,\n update_model_for_warm_start,\n)\nfrom ml.rl.workflow.preprocess_handler import DqnPreprocessHandler, PreprocessHandler\nfrom tensorboardX import SummaryWriter\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass DqnWorkflow(BaseWorkflow):\n def __init__(\n self,\n model_params: DiscreteActionModelParameters,\n preprocess_handler: PreprocessHandler,\n state_normalization: Dict[int, NormalizationParameters],\n use_gpu: bool,\n use_all_avail_gpus: bool,\n ):\n logger.info(\"Running DQN workflow with params:\")\n logger.info(model_params)\n model_params = model_params\n\n trainer = DQNTrainer(\n model_params,\n state_normalization,\n use_gpu=use_gpu,\n use_all_avail_gpus=use_all_avail_gpus,\n )\n trainer = update_model_for_warm_start(trainer)\n assert type(trainer) == DQNTrainer, \"Warm started wrong model type: \" + str(\n type(trainer)\n )\n\n evaluator = Evaluator(\n model_params.actions,\n model_params.rl.gamma,\n trainer,\n metrics_to_score=trainer.metrics_to_score,\n )\n\n super(DqnWorkflow, self).__init__(\n preprocess_handler, trainer, evaluator, model_params.training.minibatch_size\n )\n\n\ndef main(params):\n # Set minibatch size based on # of devices being used to train\n params[\"training\"][\"minibatch_size\"] *= minibatch_size_multiplier(\n params[\"use_gpu\"], params[\"use_all_avail_gpus\"]\n )\n\n rl_parameters = RLParameters(**params[\"rl\"])\n training_parameters = TrainingParameters(**params[\"training\"])\n rainbow_parameters = RainbowDQNParameters(**params[\"rainbow\"])\n\n model_params = DiscreteActionModelParameters(\n actions=params[\"actions\"],\n rl=rl_parameters,\n training=training_parameters,\n rainbow=rainbow_parameters,\n )\n state_normalization = BaseWorkflow.read_norm_file(params[\"state_norm_data_path\"])\n\n writer = SummaryWriter(log_dir=params[\"model_output_path\"])\n logger.info(\"TensorBoard logging location is: {}\".format(writer.log_dir))\n\n preprocess_handler = DqnPreprocessHandler(\n Preprocessor(state_normalization, False),\n np.array(model_params.actions),\n PandasSparseToDenseProcessor(),\n )\n\n workflow = DqnWorkflow(\n model_params,\n preprocess_handler,\n state_normalization,\n params[\"use_gpu\"],\n params[\"use_all_avail_gpus\"],\n )\n\n train_dataset = JSONDatasetReader(\n params[\"training_data_path\"], batch_size=training_parameters.minibatch_size\n )\n eval_dataset = JSONDatasetReader(params[\"eval_data_path\"], batch_size=16)\n\n with summary_writer_context(writer):\n workflow.train_network(train_dataset, eval_dataset, int(params[\"epochs\"]))\n return export_trainer_and_predictor(\n workflow.trainer, params[\"model_output_path\"]\n ) # noqa\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(stream=sys.stdout, level=logging.INFO)\n params = parse_args(sys.argv)\n\n main(params)\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
yphsieh/rPPG_blink
[ "31be5b818d34892eb9f2c1abd3b00f370413e3db" ]
[ "evaluation.py" ]
[ "import os\nimport argparse\nfrom keras.models import load_model\nimport numpy as np\nfrom sklearn.metrics import accuracy_score, f1_score\n\nfrom data_preprocessing import *\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-m', '--model_name', default='save/RDNN.h5', type=str)\nparser.add_argument('--smooth', type=bool, default=False)\nparser.add_argument('--scale', type=bool, default=False)\nargs = parser.parse_args()\nprint(args)\n\n\nx_test = np.load('data/data_test_600.npy')\ny_test = np.load('data/label_test_600.npy').reshape(-1, 1)\nprint('x_test: {}'.format(x_test.shape))\nprint('y_test: {}'.format(y_test.shape))\n\nlie_ratio = np.sum(y_test)/y_test.shape[0]\nprint('Lie Ratio: {}'.format(lie_ratio))\n\nx_test = TestPreprocess(x_test, args.smooth, args.scale)\n\nprint('='*20, 'Model Loading...', '='*20)\nmodel = load_model(args.model_name)\nprint('='*20, 'Model Loaded', '='*20)\n\n# os.system('clear')\n\npredict = model.predict(x_test)\ny_predict = (predict > 0.3).astype(np.int)\n\nlie_ratio = np.sum(y_predict)/y_predict.shape[0]\nprint('Lie Ratio Predicted: {}'.format(lie_ratio))\n\n\nscore_f1 = f1_score(y_test, y_predict)\nscore_acc = accuracy_score(y_test, y_predict)\nprint('f1 score: {}'.format(score_f1))\nprint('accuracy score: {}'.format(score_acc))\n" ]
[ [ "numpy.load", "sklearn.metrics.f1_score", "numpy.sum", "sklearn.metrics.accuracy_score" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
decarlof/algotom
[ "3dce086bcc0c4df97700c60f8ec90e07ee95d040", "3dce086bcc0c4df97700c60f8ec90e07ee95d040" ]
[ "tests/test_util/test_calibration.py", "algotom/io/loadersaver.py" ]
[ "# ============================================================================\n# ============================================================================\n# Copyright (c) 2021 Nghia T. Vo. 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# Author: Nghia T. Vo\n# E-mail: [email protected]\n# Description: Tests for the Algotom package.\n# Contributors:\n# ============================================================================\n\"\"\"\nTests for methods in util/calibration.py\n\"\"\"\n\nimport unittest\nimport numpy as np\nimport scipy.ndimage as ndi\nimport algotom.util.calibration as cali\n\n\nclass CalibrationMethods(unittest.TestCase):\n\n def setUp(self):\n self.eps = 10 ** (-6)\n self.var = 0.05\n sigma = 30\n (self.hei, self.wid) = (64, 64)\n (ycen, xcen) = (self.hei // 2, self.wid // 2)\n y, x = np.ogrid[-ycen:self.hei - ycen, -xcen:self.wid - xcen]\n num = 2.0 * sigma * sigma\n self.bck = np.exp(-(x * x / num + y * y / num))\n mat = np.zeros((self.hei, self.wid), dtype=np.float32)\n self.num_dots = 1\n mat[ycen - 3:ycen + 3, xcen - 3:xcen + 3] = 1\n self.mat_dots = np.float32(ndi.binary_dilation(mat, iterations=2))\n\n def test_normalize_background(self):\n mat_nor = cali.normalize_background(self.bck, 3)\n std_val = np.std(mat_nor)\n self.assertTrue(std_val <= self.var)\n\n def test_normalize_background_based_fft(self):\n mat_nor = cali.normalize_background_based_fft(self.bck, sigma=5, pad=10)\n std_val = np.std(mat_nor)\n self.assertTrue(std_val <= self.var)\n\n def test_binarize_image(self):\n bck = 0.5 * np.random.rand(self.hei, self.wid)\n mat_bin = cali.binarize_image(self.mat_dots + bck, bgr=\"dark\",\n denoise=False)\n num_dots = ndi.label(mat_bin)[-1]\n self.assertTrue(self.num_dots == num_dots)\n\n def test_calculate_distance(self):\n mat1 = np.zeros((self.hei, self.wid), dtype=np.float32)\n mat2 = np.zeros_like(mat1)\n bck = 0.5 * np.random.rand(self.hei, self.wid)\n mat1[5, 10] = 1.0\n mat1 = np.float32(ndi.binary_dilation(mat1, iterations=3))\n mat2[5, 20] = 1.0\n mat2 = np.float32(ndi.binary_dilation(mat2, iterations=3))\n dis = cali.calculate_distance(mat1 + bck, mat2 + bck, bgr=\"dark\",\n denoise=False)\n self.assertTrue(np.abs(dis - 10.0) <= self.eps)\n", "# ============================================================================\n# ============================================================================\n# Copyright (c) 2021 Nghia T. Vo. 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# Author: Nghia T. Vo\n# E-mail: [email protected]\n# Description: Python codes for loading and saving data.\n# Contributors:\n# ============================================================================\n\n\"\"\"\nModule for I/O tasks:\n- Load data from an image file (tif, png, jpeg) or a hdf/nxs file.\n- Get dataset information in a hdf/nxs file.\n- Search for datasets in a hdf/nxs file.\n- Save a 2D array as a tif image or 2D, 3D array to a hdf/nxs file.\n- Search file names, make a file/folder name.\n- Load distortion coefficients from a txt file.\n\"\"\"\n\nimport os\nimport glob\nimport h5py\nimport numpy as np\nfrom PIL import Image\nfrom collections import OrderedDict\n\n\ndef load_image(file_path):\n \"\"\"\n Load data from an image.\n\n Parameters\n ----------\n file_path : str\n Path to the file.\n\n Returns\n -------\n float\n 2D array.\n \"\"\"\n if \"\\\\\" in file_path:\n raise ValueError(\n \"Please use the forward slash in the file path\")\n try:\n mat = np.asarray(Image.open(file_path), dtype=np.float32)\n except IOError:\n print(\"No such file or directory: {}\".format(file_path))\n raise\n if len(mat.shape) > 2:\n axis_m = np.argmin(mat.shape)\n mat = np.mean(mat, axis=axis_m)\n return mat\n\n\ndef get_hdf_information(file_path):\n \"\"\"\n Get information of datasets in a hdf/nxs file.\n\n Parameters\n ----------\n file_path : str\n Path to the file.\n\n Returns\n -------\n list_key : str\n Keys to the datasets.\n list_shape : tuple of int\n Shapes of the datasets.\n list_type : str\n Types of the datasets.\n \"\"\"\n ifile = h5py.File(file_path, 'r')\n keys = []\n ifile.visit(keys.append)\n list_key = []\n list_shape = []\n list_type = []\n for key in keys:\n data = ifile[key]\n if isinstance(data, h5py.Group):\n for key2, _ in list(data.items()):\n list_key.append(key + \"/\" + key2)\n else:\n list_key.append(data.name)\n for i, key in enumerate(list_key):\n data = ifile[list_key[i]]\n try:\n shape = data.shape\n except AttributeError:\n shape = \"None\"\n try:\n dtype = data.dtype\n except AttributeError:\n dtype = \"None\"\n if isinstance(data, list):\n if len(data) == 1:\n if not isinstance(data, np.ndarray):\n dtype = str(list(data)[0])\n dtype = dtype.replace(\"b'\", \"'\")\n list_shape.append(shape)\n list_type.append(dtype)\n ifile.close()\n return list_key, list_shape, list_type\n\n\ndef find_hdf_key(file_path, pattern):\n \"\"\"\n Find datasets matching the pattern in a hdf/nxs file.\n\n Parameters\n ----------\n file_path : str\n Path to the file.\n pattern : str\n Pattern to find the full names of the datasets.\n\n Returns\n -------\n list_key : str\n Keys to the datasets.\n list_shape : tuple of int\n Shapes of the datasets.\n list_type : str\n Types of the datasets.\n \"\"\"\n ifile = h5py.File(file_path, 'r')\n list_key = []\n keys = []\n ifile.visit(keys.append)\n for key in keys:\n data = ifile[key]\n if isinstance(data, h5py.Group):\n for key2, _ in list(data.items()):\n list_key.append(data.name + \"/\" + key2)\n else:\n list_key.append(data.name)\n list_dkey = []\n list_dshape = []\n list_dtype = []\n for _, key in enumerate(list_key):\n if pattern in key:\n list_dkey.append(key)\n data = ifile[key]\n try:\n shape = data.shape\n except AttributeError:\n shape = \"None\"\n list_dshape.append(shape)\n try:\n dtype = data.dtype\n except AttributeError:\n dtype = \"None\"\n list_dtype.append(dtype)\n if isinstance(data, list):\n if len(data) == 1:\n dtype = str(list(data)[0])\n dtype = dtype.replace(\"b'\", \"'\")\n ifile.close()\n return list_dkey, list_dshape, list_dtype\n\n\ndef load_hdf(file_path, key_path):\n \"\"\"\n Load a hdf/nexus dataset as an object.\n\n Parameters\n ----------\n file_path : str\n Path to the file.\n key_path : str\n Key path to the dataset.\n\n Returns\n -------\n object\n hdf/nxs object.\n \"\"\"\n try:\n ifile = h5py.File(file_path, 'r')\n except IOError:\n print(\"Couldn't open file: {}\".format(file_path))\n raise\n check = key_path in ifile\n if not check:\n print(\"Couldn't open object with the key path: {}\".format(key_path))\n raise ValueError(\"!!! Wrong key !!!\")\n return ifile[key_path]\n\n\ndef make_folder(file_path):\n \"\"\"\n Create a folder if not exist.\n\n Parameters\n ----------\n file_path : str\n \"\"\"\n file_base = os.path.dirname(file_path)\n if not os.path.exists(file_base):\n try:\n os.makedirs(file_base)\n except OSError:\n raise ValueError(\"Can't create the folder: {}\".format(file_path))\n\n\ndef make_file_name(file_path):\n \"\"\"\n Create a new file name to avoid overwriting.\n\n Parameters\n ----------\n file_path : str\n\n Returns\n -------\n str\n Updated file path.\n \"\"\"\n file_base, file_ext = os.path.splitext(file_path)\n if os.path.isfile(file_path):\n nfile = 0\n check = True\n while check:\n name_add = '0000' + str(nfile)\n file_path = file_base + \"_\" + name_add[-4:] + file_ext\n if os.path.isfile(file_path):\n nfile = nfile + 1\n else:\n check = False\n return file_path\n\n\ndef make_folder_name(folder_path, name_prefix=\"Output\"):\n \"\"\"\n Create a new folder name to avoid overwriting.\n E.g: Output_00001, Output_00002...\n\n Parameters\n ----------\n folder_path : str\n Path to the parent folder.\n name_prefix : str\n Name prefix\n\n Returns\n -------\n str\n Name of the folder.\n \"\"\"\n zero_prefix = 5\n scan_name_prefix = name_prefix + \"_\"\n num_folder_exist = len(\n glob.glob(folder_path + \"/\" + scan_name_prefix + \"*\"))\n num_folder_new = num_folder_exist + 1\n name_tmp = \"00000\" + str(num_folder_new)\n scan_name = scan_name_prefix + name_tmp[-zero_prefix:]\n while os.path.isdir(folder_path + \"/\" + scan_name):\n num_folder_new = num_folder_new + 1\n name_tmp = \"00000\" + str(num_folder_new)\n scan_name = scan_name_prefix + name_tmp[-zero_prefix:]\n return scan_name\n\n\ndef find_file(path):\n \"\"\"\n Search file\n\n Parameters\n ----------\n path : str\n Path and pattern to find files.\n\n Returns\n -------\n str or list of str\n List of files.\n \"\"\"\n file_path = glob.glob(path)\n if len(file_path) == 0:\n raise ValueError(\"!!! No files found in: {}\".format(path))\n for i in range(len(file_path)):\n file_path[i] = file_path[i].replace(\"\\\\\", \"/\")\n return sorted(file_path)\n\n\ndef save_image(file_path, mat, overwrite=True):\n \"\"\"\n Save a 2D array to an image.\n\n Parameters\n ----------\n file_path : str\n Path to the file.\n mat : int or float\n 2D array.\n overwrite : bool\n Overwrite an existing file if True.\n\n Returns\n -------\n str\n Updated file path.\n \"\"\"\n if \"\\\\\" in file_path:\n raise ValueError(\n \"Please use the forward slash in the file path\")\n _, file_ext = os.path.splitext(file_path)\n if not ((file_ext == \".tif\") or (file_ext == \".tiff\")):\n mat = np.uint8(255 * (mat - np.min(mat)) / (np.max(mat) - np.min(mat)))\n make_folder(file_path)\n if not overwrite:\n file_path = make_file_name(file_path)\n image = Image.fromarray(mat)\n try:\n image.save(file_path)\n except IOError:\n print(\"Couldn't write to file {}\".format(file_path))\n raise\n return file_path\n\n\ndef open_hdf_stream(file_path, data_shape, key_path='entry/data',\n data_type='float32', overwrite=True, **options):\n \"\"\"\n Write an array to a hdf/nxs file with options to add metadata.\n\n Parameters\n ----------\n file_path : str\n Path to the file.\n data_shape : tuple of int\n Shape of the data.\n key_path : str\n Key path to the dataset.\n data_type: str\n Type of data.\n overwrite : bool\n Overwrite the existing file if True.\n options : dict, optional\n Add metadata. E.g. options={\"entry/angles\": angles, \"entry/energy\": 53}.\n\n Returns\n -------\n object\n hdf object.\n \"\"\"\n file_base, file_ext = os.path.splitext(file_path)\n if not (file_ext == '.hdf' or file_ext == '.h5' or file_ext == \".nxs\"):\n file_ext = '.hdf'\n file_path = file_base + file_ext\n make_folder(file_path)\n if not overwrite:\n file_path = make_file_name(file_path)\n try:\n ofile = h5py.File(file_path, 'w')\n except IOError:\n print(\"Couldn't write to file: {}\".format(file_path))\n raise\n if len(options) != 0:\n for opt_name in options:\n opts = options[opt_name]\n for key in opts:\n if key_path in key:\n msg = \"!!! Selected key path, '{0}', can not be a child \"\\\n \"key-path of '{1}' !!!\\n!!! Change to make sure they\"\\\n \" are at the same level !!!\".format(key, key_path)\n raise ValueError(msg)\n ofile.create_dataset(key, data=opts[key])\n data_out = ofile.create_dataset(key_path, data_shape, dtype=data_type)\n return data_out\n\n\ndef load_distortion_coefficient(file_path):\n \"\"\"\n Load distortion coefficients from a text file.\n\n Parameters\n ----------\n file_path : str\n Path to the file\n\n Returns\n -------\n tuple of float and list\n Tuple of (xcenter, ycenter, list_fact).\n \"\"\"\n if \"\\\\\" in file_path:\n raise ValueError(\n \"Please use the forward slash in the file path\")\n with open(file_path, 'r') as f:\n x = f.read().splitlines()\n list_data = []\n for i in x:\n list_data.append(float(i.split()[-1]))\n xcenter = list_data[0]\n ycenter = list_data[1]\n list_fact = list_data[2:]\n return xcenter, ycenter, list_fact\n\n\ndef save_distortion_coefficient(file_path, xcenter, ycenter, list_fact,\n overwrite=True):\n \"\"\"\n Write distortion coefficients to a text file.\n\n Parameters\n ----------\n file_path : str\n Path to the file.\n xcenter : float\n Center of distortion in x-direction.\n ycenter : float\n Center of distortion in y-direction.\n list_fact : float\n 1D array. Coefficients of the polynomial fit.\n overwrite : bool\n Overwrite an existing file if True.\n\n Returns\n -------\n str\n Updated file path.\n \"\"\"\n file_base, file_ext = os.path.splitext(file_path)\n if not ((file_ext == '.txt') or (file_ext == '.dat')):\n file_ext = '.txt'\n file_path = file_base + file_ext\n make_folder(file_path)\n if not overwrite:\n file_path = make_file_name(file_path)\n metadata = OrderedDict()\n metadata['xcenter'] = xcenter\n metadata['ycenter'] = ycenter\n for i, fact in enumerate(list_fact):\n kname = 'factor' + str(i)\n metadata[kname] = fact\n with open(file_path, \"w\") as f:\n for line in metadata:\n f.write(str(line) + \" = \" + str(metadata[line]))\n f.write('\\n')\n return file_path\n" ]
[ [ "numpy.abs", "scipy.ndimage.label", "numpy.std", "numpy.zeros_like", "numpy.random.rand", "scipy.ndimage.binary_dilation", "numpy.exp", "numpy.zeros" ], [ "numpy.max", "numpy.argmin", "numpy.mean", "numpy.min" ] ]
[ { "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": [] } ]
thompsonsed/pycoalescence
[ "eddce52ad7b3584e1fb208532d6851751b27dd4a" ]
[ "pycoalescence/tests/test_coalescence_tree.py" ]
[ "\"\"\"\nTests the coalescence tree object.\n\"\"\"\nimport os\nimport random\nimport shutil\nimport sqlite3\nimport sys\nimport unittest\n\nimport numpy as np\nimport pandas as pd\nfrom pandas.testing import assert_frame_equal\nfrom setup_tests import setUpAll, tearDownAll, skipLongTest\n\nfrom pycoalescence import Simulation\nfrom pycoalescence.coalescence_tree import CoalescenceTree, get_parameter_description\nfrom pycoalescence.sqlite_connection import check_sql_table_exist\n\n\ndef setUpModule():\n \"\"\"\n Creates the output directory and moves logging files\n \"\"\"\n setUpAll()\n t = CoalescenceTree(\"sample/sample.db\")\n t.clear_calculations()\n\n\ndef tearDownModule():\n \"\"\"\n Removes the output directory\n \"\"\"\n tearDownAll()\n\n\nclass TestNullSimulationErrors(unittest.TestCase):\n \"\"\"\n Tests that simulations that are not linked raise the correct error.\n \"\"\"\n\n def testRaisesError(self):\n \"\"\"\n Tests that a null simulation will raise an error when any operation is performed.\n \"\"\"\n t = CoalescenceTree()\n with self.assertRaises(RuntimeError):\n t.get_species_richness()\n with self.assertRaises(RuntimeError):\n t.calculate_fragment_richness()\n with self.assertRaises(RuntimeError):\n t.calculate_alpha_diversity()\n with self.assertRaises(RuntimeError):\n t.calculate_beta_diversity()\n with self.assertRaises(RuntimeError):\n t.calculate_fragment_abundances()\n with self.assertRaises(RuntimeError):\n t.calculate_fragment_octaves()\n with self.assertRaises(RuntimeError):\n t.calculate_octaves()\n with self.assertRaises(RuntimeError):\n t.get_fragment_list()\n with self.assertRaises(RuntimeError):\n t.get_alpha_diversity()\n with self.assertRaises(RuntimeError):\n t.get_beta_diversity()\n with self.assertRaises(RuntimeError):\n t.get_community_references()\n with self.assertRaises(RuntimeError):\n t.get_metacommunity_references()\n with self.assertRaises(RuntimeError):\n t.get_species_locations()\n with self.assertRaises(RuntimeError):\n t.get_species_abundances()\n with self.assertRaises(RuntimeError):\n t.get_species_list()\n with self.assertRaises(RuntimeError):\n _ = t.get_simulation_parameters()\n with self.assertRaises(RuntimeError):\n t.get_fragment_abundances(\"null\", 1)\n with self.assertRaises(RuntimeError):\n t.get_species_richness()\n with self.assertRaises(RuntimeError):\n t.get_octaves(1)\n\n\nclass TestParameterDescriptions(unittest.TestCase):\n \"\"\"\n Tests that program correctly reads from the parameter_descriptions.json dictionary.\n \"\"\"\n\n def testReadsCorrectly(self):\n \"\"\"\n Tests that the dictionary is read correctly.\n \"\"\"\n tmp_dict = {\n \"habitat_change_rate\": \"the rate of change from present density maps to historic density maps\",\n \"sample_file\": \"the sample area map for spatially selective sampling. Can be null to sample all \" \"cells\",\n \"sample_x\": \"the sample map x dimension\",\n \"sample_y\": \"the sample map y dimension\",\n \"sample_x_offset\": \"the sample x map offset from the grid\",\n \"sample_y_offset\": \"the sample y map offset from the grid\",\n \"output_dir\": \"the output directory for the simulation database\",\n \"seed\": \"the random seed to start the simulation, for repeatability\",\n \"coarse_map_x\": \"the coarse density map x dimension\",\n \"fine_map_file\": \"the density map file location at the finer resolution, covering a smaller area\",\n \"tau\": \"the tau dispersal value for fat-tailed dispersal\",\n \"grid_y\": \"the simulated grid y dimension\",\n \"dispersal_relative_cost\": \"the relative rate of moving through non-habitat compared to habitat\",\n \"fine_map_y_offset\": \"the number of cells the fine map is offset from the sample map in the y \"\n \"dimension, at the fine resolution\",\n \"gen_since_historical\": \"the number of generations that occur before the historical, or historic,\"\n \" state is reached\",\n \"dispersal_method\": \"the dispersal method used. Can be one of 'normal', 'norm-uniform' or \" \"'fat-tail'.\",\n \"historical_fine_map\": \"the historical, or historic, coarse density map file location\",\n \"coarse_map_scale\": \"the scale of the coarse density map compared to the fine density map. 1 \"\n \"means equal density\",\n \"grid_x\": \"the simulated grid x dimension\",\n \"coarse_map_file\": \"the density map file location at the coarser resolution, covering a larger \" \"area\",\n \"min_num_species\": \"the minimum number of species known to exist (currently has no effect)\",\n \"historical_coarse_map\": \"the historical, or historic, coarse density map file location\",\n \"m_probability\": \"the probability of choosing from the uniform dispersal kernel in normal-uniform\"\n \" dispersal\",\n \"sigma\": \"the sigma dispersal value for normal, fat-tailed and normal-uniform dispersals\",\n \"deme\": \"the number of individuals inhabiting a cell at a map density of 1\",\n \"time_config_file\": \"will be 'set' if temporal sampling is used, 'null' otherwise\",\n \"coarse_map_y\": \"the coarse density map y dimension\",\n \"fine_map_x\": \"the fine density map x dimension\",\n \"coarse_map_y_offset\": \"the number of cells the coarse map is offset from the fine map in the y \"\n \"dimension, at the fine resolution\",\n \"cutoff\": \"the maximal dispersal distance possible, for normal-uniform dispersal\",\n \"fine_map_y\": \"the fine density map y dimension\",\n \"sample_size\": \"the proportion of individuals to sample from each cell (0-1)\",\n \"fine_map_x_offset\": \"the number of cells the fine map is offset from the sample map in the x \"\n \"dimension, at the fine resolution\",\n \"speciation_rate\": \"the minimum speciation rate the simulation was run with\",\n \"task\": \"the job or task reference number given to this simulation\",\n \"coarse_map_x_offset\": \"the number of cells the coarse map is offset from the fine map in the x \"\n \"dimension, at the fine resolution\",\n \"landscape_type\": \"if false, landscapes have hard boundaries. Otherwise, can be infinite, \"\n \"with 1s everywhere, or tiled_coarse or tiled_fine for repeated units of tiled \"\n \"maps\",\n \"max_time\": \"the maximum simulation time to run for (in seconds)\",\n \"sim_complete\": \"set to true upon simulation completion, false for incomplete simulations\",\n \"protracted\": \"if true, the simulation was run with protracted speciation.\",\n \"min_speciation_gen\": \"the minimum number of generations required before speciation can occur\",\n \"max_speciation_gen\": \"the maximum number of generations a lineage can exist before it is \" \"speciated\",\n \"dispersal_map\": \"a tif file where rows represent cumulative dispersal probability to every other \"\n \"cell, using the row number = x + (y * x_max)\",\n }\n t = CoalescenceTree(\"sample/sample.db\")\n sim_output = t.get_simulation_parameters()\n for key in sim_output.keys():\n self.assertIn(key, get_parameter_description().keys())\n self.assertEqual(get_parameter_description(key), t.get_parameter_description(key))\n for key in get_parameter_description().keys():\n self.assertIn(key, sim_output.keys())\n for key in tmp_dict.keys():\n self.assertEqual(tmp_dict[key], get_parameter_description(key))\n self.assertDictEqual(tmp_dict, get_parameter_description())\n with self.assertRaises(KeyError):\n get_parameter_description(key=\"notakey\")\n dispersal_parameters = t.dispersal_parameters()\n expected_disp_dict = {\n \"dispersal_method\": \"normal\",\n \"sigma\": 3.55,\n \"tau\": 0.470149,\n \"m_probability\": 0,\n \"cutoff\": 0,\n }\n for key in dispersal_parameters.keys():\n self.assertIn(key, tmp_dict.keys())\n self.assertIn(key, expected_disp_dict.keys())\n for key, val in expected_disp_dict.items():\n self.assertIn(key, dispersal_parameters.keys())\n if isinstance(val, float):\n self.assertAlmostEqual(val, dispersal_parameters[key])\n else:\n self.assertEqual(val, dispersal_parameters[key])\n\n\nclass TestCoalescenceTreeSettingSpeciationParameters(unittest.TestCase):\n \"\"\"Tests that the correct errors are raised when speciation parameters are supplied incorrectly.\"\"\"\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Generates the temporary databases to attempt analysis on.\"\"\"\n src = [os.path.join(\"sample\", \"sample{}.db\".format(x)) for x in [2, 3]]\n cls.dst = [os.path.join(\"output\", \"sample{}.db\".format(x)) for x in [2, 3]]\n for tmp_src, tmp_dst in zip(src, cls.dst):\n if os.path.exists(tmp_dst):\n os.remove(tmp_dst)\n shutil.copy(tmp_src, tmp_dst)\n\n def testSetSpeciationRates(self):\n \"\"\"Tests setting speciation rates works as intended and raises appropriate errors\"\"\"\n ct = CoalescenceTree(self.dst[0])\n for attempt in [\"a string\", [\"a\", \"string\"], [[\"list\", \"list2\"], 0.2, 0.1], [None]]:\n with self.assertRaises(TypeError):\n ct._set_speciation_rates(attempt)\n with self.assertRaises(RuntimeError):\n ct._set_speciation_rates(None)\n for attempt in [-10, -2.0, 1.1, 100, [-1, 0.1, 0.2], [0.2, 0.8, 1.1]]:\n with self.assertRaises(ValueError):\n ct._set_speciation_rates(attempt)\n expected_list = [0.1, 0.2, 0.3]\n ct._set_speciation_rates(expected_list)\n self.assertEqual(expected_list, ct.applied_speciation_rates_list)\n ct._set_speciation_rates(0.2)\n self.assertEqual([0.2], ct.applied_speciation_rates_list)\n\n def testSetRecordFragments(self):\n \"\"\"Tests that setting the record_fragments flag works as expected.\"\"\"\n ct = CoalescenceTree(self.dst[0])\n ct._set_record_fragments(True)\n self.assertEqual(\"null\", ct.record_fragments)\n ct._set_record_fragments(False)\n self.assertEqual(\"F\", ct.record_fragments)\n for each in [\"PlotBiodiversityMetrics.db\", \"doesntexist.csv\"]:\n config_path = os.path.join(\"sample\", each)\n with self.assertRaises(IOError):\n ct._set_record_fragments(config_path)\n expected = os.path.join(\"sample\", \"FragmentsTest.csv\")\n ct._set_record_fragments(expected)\n self.assertEqual(expected, ct.record_fragments)\n\n def testSetRecordSpatial(self):\n \"\"\"Tests that the setting the record_spatial flag works as expected\"\"\"\n ct = CoalescenceTree(self.dst[0])\n ct._set_record_spatial(\"T\")\n self.assertTrue(ct.record_spatial)\n ct._set_record_spatial(\"F\")\n self.assertFalse(ct.record_spatial)\n with self.assertRaises(TypeError):\n ct._set_record_spatial(\"nota bool\")\n ct._set_record_spatial(True)\n self.assertTrue(ct.record_spatial)\n\n def testSetMetacommunityParameters(self):\n \"\"\"Tests that setting the metacommunity parameters works as expected.\"\"\"\n ct = CoalescenceTree(self.dst[0])\n for size, spec in [[-10, 0.1], [10, -0.1], [10, 1.1]]:\n with self.assertRaises(ValueError):\n ct.fragments = \"F\"\n ct._set_record_fragments(False)\n ct._set_record_spatial(False)\n ct.times = [0.0]\n ct._set_metacommunity_parameters(size, spec)\n ct._set_metacommunity_parameters()\n self.assertEqual(0.0, ct.metacommunity_size)\n self.assertEqual(0.0, ct.metacommunity_speciation_rate)\n ct._set_metacommunity_parameters(10, 0.1, \"simulated\")\n self.assertEqual(10, ct.metacommunity_size)\n self.assertEqual(0.1, ct.metacommunity_speciation_rate)\n\n def testSetProtractedParameters(self):\n \"\"\"Tests that setting the protracted parameters works as expected.\"\"\"\n ct = CoalescenceTree(self.dst[0])\n with self.assertRaises(ValueError):\n ct._set_protracted_parameters(0.1, 100)\n ct = CoalescenceTree(self.dst[1])\n ct._set_protracted_parameters(10, 100)\n self.assertEqual((10.0, 100.0), ct.protracted_parameters[0])\n ct.protracted_parameters = []\n for min_proc, max_proc in [[200, 5000], [80, 50], [200, 11000]]:\n with self.assertRaises(ValueError):\n ct._check_protracted_parameters(min_proc, max_proc)\n with self.assertRaises(ValueError):\n ct._set_protracted_parameters(min_proc, max_proc)\n with self.assertRaises(ValueError):\n ct.add_protracted_parameters(min_proc, max_proc)\n ct._set_protracted_parameters(50, 5000)\n self.assertEqual((50.0, 5000.0), ct.protracted_parameters[0])\n ct.protracted_parameters = []\n ct._set_protracted_parameters()\n self.assertEqual((0.0, 0.0), ct.protracted_parameters[0])\n\n def testSetSampleFile(self):\n \"\"\"Tests that the sample file is correctly set.\"\"\"\n ct = CoalescenceTree(self.dst[0])\n for file in [\"notafile.tif\", os.path.join(\"sample\", \"sample.db\")]:\n with self.assertRaises(IOError):\n ct._set_sample_file(file)\n ct._set_sample_file()\n self.assertEqual(\"null\", ct.sample_file)\n expected_file = os.path.join(\"sample\", \"SA_sample_coarse.tif\")\n ct._set_sample_file(expected_file)\n self.assertEqual(expected_file, ct.sample_file)\n\n def testSetTimes(self):\n \"\"\"Tests that times are correctly set.\"\"\"\n ct = CoalescenceTree(self.dst[0])\n ct._set_times(None)\n self.assertEqual(0.0, ct.times[0])\n with self.assertRaises(TypeError):\n ct.add_times(0.5)\n with self.assertRaises(TypeError):\n ct.add_times([0.2, 0.5, \"string\"])\n ct.times = None\n ct.add_times([0.2, 0.5, 10])\n self.assertEqual([0.0, 0.2, 0.5, 10.0], ct.times)\n ct.times = None\n ct._set_times(0.2)\n self.assertEqual([0.0, 0.2], ct.times)\n ct.times = None\n ct._set_times([0.1, 0.5, 10.0])\n self.assertEqual([0.0, 0.1, 0.5, 10.0], ct.times)\n\n\nclass TestCoalescenceTreeParameters(unittest.TestCase):\n \"\"\"Tests that parameters are correctly obtained from the databases and the relevant errors are raised.\"\"\"\n\n def testCommunityParameters1(self):\n \"\"\"Tests the community parameters make sense in a very simple community.\"\"\"\n shutil.copyfile(os.path.join(\"sample\", \"sample3.db\"), os.path.join(\"output\", \"temp_sample3.db\"))\n t = CoalescenceTree(os.path.join(\"output\", \"temp_sample3.db\"), logging_level=50)\n self.assertEqual([], t.get_metacommunity_references())\n self.assertEqual([1], t.get_community_references())\n params = t.get_community_parameters(1)\n expected_dict = {\n \"speciation_rate\": 0.001,\n \"time\": 0.0,\n \"fragments\": 0,\n \"metacommunity_reference\": 0,\n \"min_speciation_gen\": 100.0,\n \"max_speciation_gen\": 10000.0,\n }\n self.assertEqual(expected_dict, params)\n with self.assertRaises(sqlite3.Error):\n t.get_metacommunity_parameters(1)\n with self.assertRaises(KeyError):\n t.get_community_parameters(2)\n with self.assertRaises(KeyError):\n t.get_community_reference(0.1, 0.0, 0, 0, 0.0, min_speciation_gen=100.0, max_speciation_gen=10000.0)\n with self.assertRaises(KeyError):\n _ = t.get_community_reference(speciation_rate=0.001, time=0.0, fragments=False)\n ref = t.get_community_reference(\n speciation_rate=0.001, time=0.0, fragments=False, min_speciation_gen=100.0, max_speciation_gen=10000.0\n )\n self.assertEqual(1, ref)\n self.assertEqual(expected_dict, t.get_community_parameters(ref))\n t.wipe_data()\n with self.assertRaises(IOError):\n t.get_community_parameters_pd()\n\n def testCommunityParameters2(self):\n \"\"\"Tests the community parameters make sense in a very simple community.\"\"\"\n t = CoalescenceTree(os.path.join(\"sample\", \"sample4.db\"))\n self.assertEqual([1, 2, 3, 4, 5], t.get_community_references())\n expected_params1 = {\"speciation_rate\": 0.1, \"time\": 0.0, \"fragments\": 0, \"metacommunity_reference\": 0}\n expected_params2 = {\"speciation_rate\": 0.1, \"time\": 0.0, \"fragments\": 0, \"metacommunity_reference\": 1}\n expected_params3 = {\"speciation_rate\": 0.2, \"time\": 0.0, \"fragments\": 0, \"metacommunity_reference\": 1}\n expected_params4 = {\"speciation_rate\": 0.1, \"time\": 0.0, \"fragments\": 0, \"metacommunity_reference\": 2}\n expected_params5 = {\"speciation_rate\": 0.2, \"time\": 0.0, \"fragments\": 0, \"metacommunity_reference\": 2}\n expected_meta_params1 = {\n \"speciation_rate\": 0.001,\n \"metacommunity_size\": 10000.0,\n \"option\": \"simulated\",\n \"external_reference\": 0,\n }\n expected_meta_params2 = {\n \"speciation_rate\": 0.001,\n \"metacommunity_size\": 10000.0,\n \"option\": \"analytical\",\n \"external_reference\": 0,\n }\n\n params1 = t.get_community_parameters(1)\n params2 = t.get_community_parameters(2)\n params3 = t.get_community_parameters(3)\n params4 = t.get_community_parameters(4)\n params5 = t.get_community_parameters(5)\n params6 = t.get_metacommunity_parameters(1)\n params7 = t.get_metacommunity_parameters(2)\n self.assertEqual([1, 2], t.get_metacommunity_references())\n self.assertEqual(expected_params1, params1)\n self.assertEqual(expected_params2, params2)\n self.assertEqual(expected_params3, params3)\n self.assertEqual(expected_params4, params4)\n self.assertEqual(expected_params5, params5)\n self.assertEqual(expected_meta_params1, params6)\n self.assertEqual(expected_meta_params2, params7)\n with self.assertRaises(KeyError):\n t.get_community_parameters(6)\n with self.assertRaises(KeyError):\n t.get_metacommunity_parameters(3)\n ref1 = t.get_community_reference(speciation_rate=0.1, time=0.0, fragments=False)\n with self.assertRaises(KeyError):\n t.get_community_reference(\n speciation_rate=0.1, time=0.0, fragments=False, min_speciation_gen=0.1, max_speciation_gen=10000.0\n )\n ref2 = t.get_community_reference(\n speciation_rate=0.1,\n time=0.0,\n fragments=False,\n metacommunity_size=10000.0,\n metacommunity_speciation_rate=0.001,\n metacommunity_option=\"simulated\",\n )\n with self.assertRaises(KeyError):\n t.get_community_reference(\n speciation_rate=0.1,\n time=0.0,\n fragments=False,\n metacommunity_size=10000.0,\n metacommunity_speciation_rate=0.01,\n metacommunity_option=\"simulated\",\n )\n ref3 = t.get_community_reference(\n speciation_rate=0.2,\n time=0.0,\n fragments=False,\n metacommunity_size=10000.0,\n metacommunity_speciation_rate=0.001,\n metacommunity_option=\"simulated\",\n )\n ref4 = t.get_community_reference(\n speciation_rate=0.1,\n time=0.0,\n fragments=False,\n metacommunity_size=10000.0,\n metacommunity_speciation_rate=0.001,\n metacommunity_option=\"analytical\",\n )\n ref5 = t.get_community_reference(\n speciation_rate=0.2,\n time=0.0,\n fragments=False,\n metacommunity_size=10000.0,\n metacommunity_speciation_rate=0.001,\n metacommunity_option=\"analytical\",\n )\n self.assertEqual(1, ref1)\n self.assertEqual(2, ref2)\n self.assertEqual(3, ref3)\n self.assertEqual(4, ref4)\n self.assertEqual(5, ref5)\n expected_community_params_list = []\n for reference in t.get_community_references():\n params = t.get_community_parameters(reference)\n params[\"reference\"] = reference\n expected_community_params_list.append(params)\n expected_community_params = pd.DataFrame(expected_community_params_list)\n actual_output = t.get_community_parameters_pd()\n assert_frame_equal(expected_community_params, actual_output, check_like=True)\n\n def testIsComplete(self):\n \"\"\"Tests sims are correctly identified as complete.\"\"\"\n t = CoalescenceTree(os.path.join(\"sample\", \"sample4.db\"))\n self.assertTrue(t.is_complete)\n\n\nclass TestCoalescenceTreeAnalysis(unittest.TestCase):\n \"\"\"Tests analysis is performed correctly\"\"\"\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Sets up the Coalescence object test case.\"\"\"\n dst1 = os.path.join(\"output\", \"sampledb0.db\")\n for i in range(0, 11):\n dst = os.path.join(\"output\", \"sampledb{}.db\".format(i))\n if os.path.exists(dst):\n os.remove(dst)\n shutil.copyfile(os.path.join(\"sample\", \"sample.db\"), dst)\n shutil.copyfile(os.path.join(\"sample\", \"nse_reference.db\"), os.path.join(\"output\", \"nse_reference1.db\"))\n random.seed(2)\n cls.test = CoalescenceTree(dst1, logging_level=50)\n cls.test.clear_calculations()\n cls.test.import_comparison_data(os.path.join(\"sample\", \"PlotBiodiversityMetrics.db\"))\n cls.test.calculate_fragment_richness()\n cls.test.calculate_fragment_octaves()\n cls.test.calculate_octaves_error()\n cls.test.calculate_alpha_diversity()\n cls.test.calculate_beta_diversity()\n cls.test2 = CoalescenceTree()\n cls.test2.set_database(os.path.join(\"sample\", \"sample_nofrag.db\"))\n dstx = os.path.join(\"output\", \"sampledbx.db\")\n shutil.copyfile(dst1, dstx)\n c = CoalescenceTree(dstx)\n c.import_comparison_data(os.path.join(\"sample\", \"PlotBiodiversityMetrics.db\"))\n c.calculate_goodness_of_fit()\n\n @classmethod\n def tearDownClass(cls):\n \"\"\"\n Removes the files from output.\"\n \"\"\"\n cls.test.clear_calculations()\n\n def testComparisonDataNoExistError(self):\n c = CoalescenceTree(os.path.join(\"sample\", \"sample.db\"))\n with self.assertRaises(IOError):\n c.import_comparison_data(os.path.join(\"sample\", \"doesnotexist.db\"))\n\n def testFragmentOctaves(self):\n num = self.test.cursor.execute(\n \"SELECT richness FROM FRAGMENT_OCTAVES WHERE fragment == 'P09' AND octave == 0\"\n \" AND community_reference == 1\"\n ).fetchall()[0][0]\n self.assertEqual(num, 7, msg=\"Fragment octaves not correctly calculated.\")\n num = self.test.cursor.execute(\n \"SELECT richness FROM FRAGMENT_OCTAVES WHERE fragment == 'P09' AND octave == 0 \"\n \" AND community_reference == 2\"\n ).fetchall()[0][0]\n self.assertEqual(num, 7, msg=\"Fragment octaves not correctly calculated.\")\n num = self.test.cursor.execute(\n \"SELECT richness FROM FRAGMENT_OCTAVES WHERE fragment == 'cerrogalera' AND octave == 1 \"\n \" AND community_reference == 1\"\n ).fetchall()[0][0]\n self.assertEqual(num, 3, msg=\"Fragment octaves not correctly calculated.\")\n num = self.test.cursor.execute(\n \"SELECT richness FROM FRAGMENT_OCTAVES WHERE fragment == 'whole' AND octave == 1 \"\n \" AND community_reference == 2\"\n ).fetchall()[0][0]\n self.assertEqual(num, 221, msg=\"Fragment octaves not correctly calculated.\")\n\n def testFragmentAbundances(self):\n \"\"\"\n Tests that fragment abundances are produced properly by the fragment detection functions.\n\n \"\"\"\n num = self.test.cursor.execute(\n \"SELECT COUNT(fragment) FROM FRAGMENT_ABUNDANCES WHERE fragment == 'P09' \" \" AND community_reference == 1\"\n ).fetchall()[0][0]\n self.assertEqual(num, 9, msg=\"Fragment abundances not correctly calculated.\")\n num = self.test.cursor.execute(\n \"SELECT COUNT(fragment) FROM FRAGMENT_ABUNDANCES WHERE fragment == 'P09' \" \" AND community_reference == 2\"\n ).fetchall()[0][0]\n self.assertEqual(num, 9, msg=\"Fragment abundances not correctly calculated.\")\n num = self.test.cursor.execute(\n \"SELECT COUNT(fragment) FROM FRAGMENT_ABUNDANCES WHERE fragment == 'cerrogalera' \"\n \" AND community_reference == 1\"\n ).fetchall()[0][0]\n self.assertEqual(num, 9, msg=\"Fragment abundances not correctly calculated.\")\n\n def testSpeciesAbundances(self):\n \"\"\"Tests that the produced species abundances are correct by comparing species richness.\"\"\"\n num = self.test.cursor.execute(\n \"SELECT COUNT(species_id) FROM SPECIES_ABUNDANCES WHERE community_reference == 2\"\n ).fetchall()[0][0]\n self.assertEqual(num, 1029, msg=\"Species abundances not correctly calculated.\")\n num = self.test.cursor.execute(\n \"SELECT COUNT(species_id) FROM SPECIES_ABUNDANCES WHERE community_reference == 1\"\n ).fetchall()[0][0]\n self.assertEqual(num, 884, msg=\"Species abundances not correctly calculated.\")\n\n def testGetOctaves(self):\n \"\"\"Tests getting the octaves.\"\"\"\n c = CoalescenceTree(os.path.join(\"output\", \"sampledb4.db\"))\n c.clear_calculations()\n c.import_comparison_data(os.path.join(\"sample\", \"PlotBiodiversityMetrics.db\"))\n c.calculate_richness()\n self.assertEqual([[0, 585], [1, 231], [2, 59], [3, 5]], c.get_octaves(1))\n c = CoalescenceTree(os.path.join(\"output\", \"sampledb4.db\"))\n c.clear_calculations()\n c.import_comparison_data(os.path.join(\"sample\", \"PlotBiodiversityMetrics.db\"))\n c.calculate_richness()\n actual = c.get_octaves_pd().head()\n expected = pd.DataFrame(\n [[1, 0, 585], [1, 1, 231], [1, 2, 59], [1, 3, 5], [2, 0, 760]],\n columns=[\"community_reference\", \"octave\", \"richness\"],\n )\n assert_frame_equal(actual, expected, check_like=True)\n\n def testSpeciesLocations(self):\n \"\"\"\n Tests that species locations have been correctly assigned.\n \"\"\"\n num = self.test.cursor.execute(\n \"SELECT species_id FROM SPECIES_LOCATIONS WHERE x==1662 AND y==4359 \" \" AND community_reference == 1\"\n ).fetchall()\n self.assertEqual(len(set(num)), 2, msg=\"Species locations not correctly assigned\")\n all_list = self.test.get_species_locations()\n select_list = self.test.get_species_locations(community_reference=1)\n self.assertListEqual([1, 1662, 4359, 1], all_list[0])\n self.assertListEqual([1, 1662, 4359], select_list[0])\n\n def testAlphaDiversity(self):\n \"\"\"\n Tests that alpha diversity is correctly calculated and fetched for each parameter reference\n \"\"\"\n c = CoalescenceTree(os.path.join(\"sample\", \"sample.db\"))\n with self.assertRaises(IOError):\n c.get_alpha_diversity_pd()\n self.assertEqual(9, self.test.get_alpha_diversity(1))\n self.assertEqual(10, self.test.get_alpha_diversity(2))\n expected_alphas_list = []\n for reference in self.test.get_community_references():\n expected_alphas_list.append(\n {\"community_reference\": reference, \"alpha_diversity\": self.test.get_alpha_diversity(reference)}\n )\n expected_alphas = pd.DataFrame(expected_alphas_list).reset_index(drop=True)\n actual_alphas = self.test.get_alpha_diversity_pd().reset_index(drop=True)\n assert_frame_equal(expected_alphas, actual_alphas, check_like=True)\n\n def testBetaDiversity(self):\n \"\"\"\n Tests that beta diversity is correctly calculated and fetched for the reference\n \"\"\"\n c = CoalescenceTree(os.path.join(\"sample\", \"sample.db\"))\n with self.assertRaises(IOError):\n c.get_beta_diversity_pd()\n self.assertAlmostEqual(98.111111111, self.test.get_beta_diversity(1), places=5)\n self.assertAlmostEqual(102.8, self.test.get_beta_diversity(2), places=5)\n expected_betas_list = []\n for reference in self.test.get_community_references():\n expected_betas_list.append(\n {\"community_reference\": reference, \"beta_diversity\": self.test.get_beta_diversity(reference)}\n )\n expected_betas = pd.DataFrame(expected_betas_list).reset_index(drop=True)\n actual_betas = self.test.get_beta_diversity_pd().reset_index(drop=True)\n assert_frame_equal(expected_betas, actual_betas, check_like=True)\n\n def testGetNumberIndividuals(self):\n \"\"\"Tests that the number of individuals is obtained correctly.\"\"\"\n c = CoalescenceTree(os.path.join(\"output\", \"sampledb7.db\"))\n self.assertEqual(1504, c.get_number_individuals(community_reference=1))\n self.assertEqual(12, c.get_number_individuals(fragment=\"P09\", community_reference=1))\n c.wipe_data()\n c.import_comparison_data(os.path.join(\"sample\", \"PlotBiodiversityMetrics.db\"))\n with self.assertRaises(IOError):\n c.get_number_individuals(fragment=\"none\")\n with self.assertRaises(IOError):\n c.get_number_individuals()\n\n def testGetFragmentAbundances(self):\n \"\"\"Tests that fragment abundances are correctly obtained.\"\"\"\n c = CoalescenceTree(os.path.join(\"sample\", \"sample3.db\"))\n with self.assertRaises(IOError):\n c.get_fragment_abundances(fragment=\"P09\", reference=1)\n with self.assertRaises(IOError):\n c.get_fragment_abundances_pd()\n abundances = self.test.get_fragment_abundances(fragment=\"P09\", reference=1)\n expected_abundances = [[302, 1], [303, 1], [304, 1], [305, 1], [306, 1], [307, 1], [546, 2], [693, 1], [732, 3]]\n self.assertEqual(expected_abundances, abundances[:10])\n all_abundances = self.test.get_all_fragment_abundances()\n expected_abundances2 = [\n [1, \"P09\", 302, 1],\n [1, \"P09\", 303, 1],\n [1, \"P09\", 304, 1],\n [1, \"P09\", 305, 1],\n [1, \"P09\", 306, 1],\n [1, \"P09\", 307, 1],\n [1, \"P09\", 546, 2],\n [1, \"P09\", 693, 1],\n [1, \"P09\", 732, 3],\n [1, \"cerrogalera\", 416, 1],\n ]\n self.assertEqual(expected_abundances2, all_abundances[:10])\n df = pd.DataFrame(\n expected_abundances2, columns=[\"community_reference\", \"fragment\", \"species_id\", \"no_individuals\"]\n )\n actual_df = self.test.get_fragment_abundances_pd().head(n=10)\n assert_frame_equal(df, actual_df, check_like=True)\n\n def testGetFragmentListErrors(self):\n \"\"\"Tests the error is raised when obtaining fragment list.\"\"\"\n c = CoalescenceTree(os.path.join(\"output\", \"sampledb8.db\"))\n c.wipe_data()\n with self.assertRaises(IOError):\n c.get_fragment_list()\n\n def testClearGoodnessFit(self):\n \"\"\"Tests that goodness of fit are correctly cleared.\"\"\"\n c = CoalescenceTree(os.path.join(\"output\", \"sampledbx.db\"))\n exec_command = \"SELECT * FROM BIODIVERSITY_METRICS WHERE metric LIKE 'goodness_%'\"\n self.assertTrue(len(c.cursor.execute(exec_command).fetchall()) >= 1)\n c._clear_goodness_of_fit()\n self.assertFalse(len(c.cursor.execute(exec_command).fetchall()) >= 1)\n\n def testGetBiodiversityMetrics(self):\n \"\"\"Tests that biodiversity metrics are correctly obtained from the database.\"\"\"\n c1 = CoalescenceTree(os.path.join(\"sample\", \"sample.db\"))\n with self.assertRaises(IOError):\n c1.get_biodiversity_metrics()\n c2 = CoalescenceTree(os.path.join(\"sample\", \"sample2.db\"))\n\n expected_biodiversity_metrics = pd.DataFrame(\n [\n [1, \"fragment_richness\", \"fragment2\", 129.0, np.NaN, np.NaN],\n [2, \"fragment_richness\", \"fragment2\", 130.0, np.NAN, np.NaN],\n [1, \"fragment_richness\", \"fragment1\", 174.0, np.NaN, np.NaN],\n [2, \"fragment_richness\", \"fragment1\", 175.0, np.NaN, np.NaN],\n [1, \"fragment_richness\", \"whole\", 1163.0, np.NaN, np.NaN],\n [2, \"fragment_richness\", \"whole\", 1170.0, np.NaN, np.NaN],\n ],\n columns=[\"community_reference\", \"metric\", \"fragment\", \"value\", \"simulated\", \"actual\"],\n ).reset_index(drop=True)\n actual_biodiversity_metrics = c2.get_biodiversity_metrics().reset_index(drop=True).fillna(value=np.nan)\n assert_frame_equal(expected_biodiversity_metrics, actual_biodiversity_metrics)\n\n def testRaisesErrorNoFragmentsAlpha(self):\n \"\"\"\n Tests that an error is raised when alpha diversity is calculated without any fragment abundance data\n \"\"\"\n with self.assertRaises(IOError):\n self.test2.calculate_alpha_diversity()\n\n def testRaisesErrorNoFragmentsBeta(self):\n \"\"\"\n Tests that an error is raised when alpha diversity is calculated without any fragment abundance data\n \"\"\"\n with self.assertRaises(IOError):\n self.test2.calculate_beta_diversity()\n\n def testRaisesErrorNoFragmentsRichness(self):\n \"\"\"\n Tests that an error is raised when fragment richness is calculated without any fragment abundance data\n \"\"\"\n with self.assertRaises(IOError):\n self.test2.calculate_fragment_richness()\n\n def testRaisesErrorNoFragmentsOctaves(self):\n \"\"\"\n Tests that an error is raised when fragment richness is calculated without any fragment abundance data\n \"\"\"\n with self.assertRaises(IOError):\n self.test2.calculate_fragment_octaves()\n\n @unittest.skipIf(sys.version[0] != \"3\", \"Skipping Python 3.x tests\")\n def testModelFitting2(self):\n \"\"\"\n Tests that the goodness-of-fit calculations are correctly performed.\n \"\"\"\n random.seed(2)\n self.test.calculate_goodness_of_fit()\n self.assertAlmostEqual(self.test.get_goodness_of_fit(), 0.30140801329929373, places=6)\n self.assertAlmostEqual(self.test.get_goodness_of_fit_fragment_octaves(), 0.0680205429120108, places=6)\n self.assertAlmostEqual(self.test.get_goodness_of_fit_fragment_richness(), 0.9244977999898334, places=6)\n\n @unittest.skipIf(sys.version[0] == \"3\", \"Skipping Python 2.x tests\")\n def testModelFitting3(self):\n \"\"\"\n Tests that the goodness-of-fit calculations are correctly performed.\n \"\"\"\n random.seed(2)\n self.test.calculate_goodness_of_fit()\n self.assertAlmostEqual(self.test.get_goodness_of_fit(), 0.30140801329929373, places=6)\n self.assertAlmostEqual(self.test.get_goodness_of_fit_fragment_octaves(), 0.0680205429120108, places=6)\n self.assertAlmostEqual(self.test.get_goodness_of_fit_fragment_richness(), 0.9244977999898334, places=6)\n\n def testErrorIfNotApplied(self):\n \"\"\"Tests that an error is raised if outputting is attempted without applying any community parameters.\"\"\"\n c = CoalescenceTree(os.path.join(\"sample\", \"sample.db\"))\n with self.assertRaises(RuntimeError):\n c.output()\n\n def testFragmentNumbersMatching(self):\n \"\"\"Checks behaviour when matching fragment numbers.\"\"\"\n test = CoalescenceTree(os.path.join(\"output\", \"sampledb1.db\"), logging_level=50)\n test.clear_calculations()\n with self.assertRaises(RuntimeError):\n test._check_fragment_numbers_match()\n with self.assertRaises(ValueError):\n test.calculate_fragment_abundances()\n test._check_fragment_numbers_match()\n test.comparison_file = os.path.join(\"sample\", \"PlotBiodiversityMetrics.db\")\n self.assertTrue(test._check_fragment_numbers_match())\n test.fragment_abundances.pop(0)\n self.assertFalse(test._check_fragment_numbers_match())\n\n def testFragmentNumbersEqualisation(self):\n \"\"\"Checks behaviour when equalising fragment numbers.\"\"\"\n test = CoalescenceTree(os.path.join(\"output\", \"sampledb2.db\"), logging_level=50)\n test.clear_calculations()\n test.import_comparison_data(os.path.join(\"sample\", \"PlotBiodiversityMetrics.db\"))\n test.calculate_fragment_richness()\n self.test._equalise_fragment_number(\"notafrag\", 1)\n test.fragment_abundances[0][2] += 1000\n test._equalise_fragment_number(\"P09\", 1)\n self.assertTrue(test._check_fragment_numbers_match())\n\n def testFragmentNumbersErrors(self):\n \"\"\"Checks behaviour when equalising fragment numbers.\"\"\"\n test = CoalescenceTree(os.path.join(\"output\", \"sampledb3.db\"), logging_level=50)\n test.clear_calculations()\n test.import_comparison_data(os.path.join(\"sample\", \"PlotBiodiversityMetrics.db\"))\n test.comparison_abundances = None\n with self.assertRaises(ValueError):\n test._equalise_all_fragment_numbers()\n\n def testAdjustBiodiversityMetrics(self):\n \"\"\"Checks that biodiversity metrics are correctly adjusted.\"\"\"\n test = CoalescenceTree(os.path.join(\"output\", \"sampledb5.db\"), logging_level=50)\n test.clear_calculations()\n test.import_comparison_data(os.path.join(\"sample\", \"PlotBiodiversityMetrics.db\"))\n test.adjust_data()\n\n def testComparisonOctavesModification(self):\n \"\"\"Tests that the comparison database is modified.\"\"\"\n test = CoalescenceTree(os.path.join(\"output\", \"sampledb6.db\"), logging_level=50)\n dst = os.path.join(\"output\", \"PlotBiodiversityMetricsNoAlpha2.db\")\n shutil.copy(os.path.join(\"sample\", \"PlotBiodiversityMetricsNoAlpha.db\"), dst)\n test.import_comparison_data(dst)\n test.calculate_comparison_octaves(store=True)\n self.assertTrue(os.path.exists(dst))\n\n @unittest.skipIf(sys.version[0] == \"2\", \"Skipping Python 3.x tests\")\n def testDownsamplingAndRevert(self):\n \"\"\"Tests that downsampling works as intended and can be reverted.\"\"\"\n c = CoalescenceTree(os.path.join(\"output\", \"sampledb9.db\"))\n random.seed(a=10, version=3)\n original_individuals = c.get_number_individuals()\n original_richness = c.get_species_richness_pd()\n c.wipe_data()\n with self.assertRaises(ValueError):\n c.downsample(sample_proportion=2.0)\n c.downsample(sample_proportion=0.1)\n c.set_speciation_parameters([0.1, 0.2])\n c.apply()\n new_individuals = c.get_number_individuals()\n self.assertEqual(1452, new_individuals)\n self.assertTrue(check_sql_table_exist(c.database, \"SPECIES_LIST\"))\n self.assertTrue(check_sql_table_exist(c.database, \"SPECIES_LIST_ORIGINAL\"))\n c = CoalescenceTree(os.path.join(\"output\", \"sampledb9.db\"))\n c.revert_downsample()\n c.wipe_data()\n c.set_speciation_parameters([0.1, 0.2])\n c.apply()\n final_individuals = c.get_number_individuals()\n assert_frame_equal(original_richness, c.get_species_richness_pd())\n self.assertEqual(original_individuals, final_individuals)\n self.assertTrue(check_sql_table_exist(c.database, \"SPECIES_LIST\"))\n self.assertFalse(check_sql_table_exist(c.database, \"SPECIES_LIST_ORIGINAL\"))\n # Now test with NSE sim to ensure correct sampling\n c = CoalescenceTree(os.path.join(\"output\", \"nse_reference1.db\"))\n nse_richness = c.get_species_richness_pd()\n nse_no_individuals = c.get_number_individuals()\n c.wipe_data()\n c.downsample(sample_proportion=0.1)\n c.set_speciation_parameters([0.000001, 0.999999])\n c.apply()\n new_no_individuals = c.get_number_individuals()\n self.assertAlmostEqual(new_no_individuals / nse_no_individuals, 0.1, 5)\n self.assertEqual(1000, c.get_species_richness(reference=2))\n self.assertTrue(check_sql_table_exist(c.database, \"SPECIES_LIST\"))\n self.assertTrue(check_sql_table_exist(c.database, \"SPECIES_LIST_ORIGINAL\"))\n c = CoalescenceTree(os.path.join(\"output\", \"nse_reference1.db\"))\n c.revert_downsample()\n c.wipe_data()\n c.set_speciation_parameters([0.000001, 0.999999])\n c.apply_incremental()\n c.set_speciation_parameters([0.5])\n c.apply()\n actual_richness = c.get_species_richness_pd()\n assert_frame_equal(nse_richness, actual_richness)\n self.assertEqual(nse_no_individuals, c.get_number_individuals())\n self.assertTrue(check_sql_table_exist(c.database, \"SPECIES_LIST\"))\n self.assertFalse(check_sql_table_exist(c.database, \"SPECIES_LIST_ORIGINAL\"))\n with self.assertRaises(IOError):\n c.revert_downsample()\n\n @unittest.skipIf(sys.version[0] == \"2\", \"Skipping Python 3.x tests\")\n def testDownsamplingByLocationAndRevert(self):\n \"\"\"Tests that downsampling works as intended and can be reverted.\"\"\"\n c = CoalescenceTree(os.path.join(\"output\", \"sampledb10.db\"))\n random.seed(a=10, version=3)\n original_individuals = c.get_number_individuals()\n original_richness = c.get_species_richness_pd()\n c.wipe_data()\n with self.assertRaises(ValueError):\n c.downsample_at_locations(fragment_csv=os.path.join(\"sample\", \"FragmentsTestFail1.csv\"))\n with self.assertRaises(IOError):\n c.downsample_at_locations(fragment_csv=\"not_a_file.csv\")\n c.downsample_at_locations(fragment_csv=os.path.join(\"sample\", \"FragmentsTest3.csv\"))\n c.set_speciation_parameters([0.1, 0.2])\n c.apply()\n new_individuals = c.get_number_individuals()\n self.assertEqual(2, new_individuals)\n self.assertTrue(check_sql_table_exist(c.database, \"SPECIES_LIST\"))\n self.assertTrue(check_sql_table_exist(c.database, \"SPECIES_LIST_ORIGINAL\"))\n c = CoalescenceTree(os.path.join(\"output\", \"sampledb10.db\"))\n c.revert_downsample()\n c.wipe_data()\n c.set_speciation_parameters([0.1, 0.2])\n c.apply()\n final_individuals = c.get_number_individuals()\n assert_frame_equal(original_richness, c.get_species_richness_pd())\n self.assertEqual(original_individuals, final_individuals)\n self.assertTrue(check_sql_table_exist(c.database, \"SPECIES_LIST\"))\n self.assertFalse(check_sql_table_exist(c.database, \"SPECIES_LIST_ORIGINAL\"))\n c = CoalescenceTree(os.path.join(\"output\", \"sampledb10.db\"))\n c.wipe_data()\n c.downsample_at_locations(fragment_csv=os.path.join(\"sample\", \"FragmentsTest4.csv\"), ignore_errors=True)\n c.set_speciation_parameters([0.1, 0.2])\n c.apply()\n new_individuals = c.get_number_individuals()\n self.assertEqual(3, new_individuals)\n\n\nclass TestCoalescenceTreeWriteCsvs(unittest.TestCase):\n \"\"\"Tests that csvs are correctly outputted.\"\"\"\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Creates the CoalescenceTree object.\"\"\"\n cls.c = CoalescenceTree(os.path.join(\"sample\", \"nse_reference.db\"))\n\n def testWriteCommunityParameterToCsv(self):\n \"\"\"Tests that community parameters are correctly written to a csv.\"\"\"\n output_csv = os.path.join(\"output\", \"community_parameters1.csv\")\n self.c.write_to_csv(output_csv, \"COMMUNITY_PARAMETERS\")\n self.assertTrue(os.path.exists(output_csv))\n import csv\n\n if sys.version_info[0] < 3: # pragma: no cover\n infile = open(output_csv, \"rb\")\n else:\n infile = open(output_csv, \"r\")\n expected_output = [\n [\"reference\", \"speciation_rate\", \"time\", \"fragments\", \"metacommunity_reference\"],\n [\"1\", \"1e-06\", \"0.0\", \"0\", \"0\"],\n [\"2\", \"0.99999\", \"0.0\", \"0\", \"0\"],\n [\"3\", \"0.5\", \"0.0\", \"0\", \"0\"],\n ]\n actual_output = []\n with infile as csv_file:\n csv_reader = csv.reader(csv_file)\n for row in csv_reader:\n actual_output.append(row)\n self.assertEqual(expected_output, actual_output)\n with self.assertRaises(IOError):\n self.c.write_to_csv(output_csv, \"COMMUNITY_PARAMETERS\")\n with self.assertRaises(KeyError):\n self.c.write_to_csv(\"notacsv.csv\", \"NOTATABLE\")\n\n def testWritesAllCsvs(self):\n \"\"\"Tests that all csvs write to the output correctly.\"\"\"\n output_dir = os.path.join(\"output\", \"csvdir\")\n if os.path.exists(output_dir):\n os.remove(output_dir)\n self.c.write_all_to_csvs(output_dir, \"out1\")\n expected_tables = [\"COMMUNITY_PARAMETERS\", \"SIMULATION_PARAMETERS\", \"SPECIES_ABUNDANCES\", \"SPECIES_LIST\"]\n for table in expected_tables:\n self.assertTrue(os.path.exists(os.path.join(output_dir, \"out1_{}.csv\".format(table))))\n for file in os.listdir(output_dir):\n if \".csv\" in file:\n self.assertIn(file, [\"out1_{}.csv\".format(x) for x in expected_tables])\n self.c.write_all_to_csvs(output_dir, \"out2.csv\")\n for table in expected_tables:\n self.assertTrue(os.path.exists(os.path.join(output_dir, \"out2_{}.csv\".format(table))))\n self.c.write_all_to_csvs(output_dir, \"out3.\")\n for table in expected_tables:\n self.assertTrue(os.path.exists(os.path.join(output_dir, \"out3_{}.csv\".format(table))))\n\n\nclass TestCoalescenceTreeSpeciesDistances(unittest.TestCase):\n \"\"\"Tests analysis is performed correctly.\"\"\"\n\n @classmethod\n def setUpClass(cls):\n \"\"\"\n Sets up the Coalescence object test case.\n \"\"\"\n dst = os.path.join(\"output\", \"sampledb1.db\")\n if os.path.exists(dst):\n os.remove(dst)\n shutil.copyfile(os.path.join(\"sample\", \"sample.db\"), dst)\n cls.test = CoalescenceTree(dst)\n cls.test.clear_calculations()\n cls.test.import_comparison_data(os.path.join(\"sample\", \"PlotBiodiversityMetrics.db\"))\n cls.test.calculate_species_distance_similarity()\n\n def testSpeciesDistanceSimilarity(self):\n \"\"\"\n Tests that the species distance similarity function works as intended.\n \"\"\"\n mean = self.test.cursor.execute(\n \"SELECT value FROM BIODIVERSITY_METRICS WHERE community_reference == 1 AND \"\n \"metric == 'mean_distance_between_individuals'\"\n ).fetchone()[0]\n self.assertAlmostEqual(mean, 5.423769507803121, places=5)\n species_distances = self.test.get_species_distance_similarity(community_reference=1)\n # for distance, similar in species_distances:\n # \tself.assertLessEqual(similar, dissimilar)\n self.assertListEqual(species_distances[0], [0, 11])\n self.assertListEqual(species_distances[1], [1, 274])\n self.assertListEqual(species_distances[2], [2, 289])\n\n\nclass TestCoalescenceTreeAnalyseIncorrectComparison(unittest.TestCase):\n \"\"\"\n Tests errors are raised correctly for incorrect comparison data.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n \"\"\"\n Sets up the Coalescence object test case.\n \"\"\"\n random.seed(10)\n dst = os.path.join(\"output\", \"sampledb2.db\")\n if os.path.exists(dst):\n os.remove(dst)\n shutil.copyfile(os.path.join(\"sample\", \"sample.db\"), dst)\n cls.test = CoalescenceTree(logging_level=40)\n cls.test.set_database(dst)\n cls.test.import_comparison_data(os.path.join(\"sample\", \"PlotBiodiversityMetricsNoAlpha.db\"))\n cls.test.calculate_comparison_octaves(False)\n cls.test.clear_calculations()\n cls.test.calculate_fragment_richness()\n cls.test.calculate_fragment_octaves()\n cls.test.calculate_octaves_error()\n cls.test.calculate_alpha_diversity()\n cls.test.calculate_alpha_diversity()\n cls.test.calculate_beta_diversity()\n cls.test2 = CoalescenceTree()\n cls.test2.set_database(os.path.join(\"sample\", \"sample_nofrag.db\"))\n\n @classmethod\n def tearDownClass(cls):\n \"\"\"\n Removes the files from output.\"\n \"\"\"\n cls.test.clear_calculations()\n\n def testRaisesErrorMismatchParameters(self):\n \"\"\"\n Tests that an error is raised when there is a parameter mismatch\n \"\"\"\n with self.assertRaises(ValueError):\n self.test.calculate_goodness_of_fit()\n\n\nclass TestSimulationAnalysisTemporal(unittest.TestCase):\n \"\"\"Tests that applying multiple times works as expected.\"\"\"\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Generates the analysis object.\"\"\"\n src = os.path.join(\"sample\", \"sample2.db\")\n dst = os.path.join(\"output\", \"sample2.db\")\n if not os.path.exists(dst):\n shutil.copy(src, dst)\n cls.tree = CoalescenceTree()\n cls.tree.set_database(dst)\n cls.tree.wipe_data()\n\n def testTimesWrongFormatError(self):\n \"\"\"Tests that an error is raised when the times are in the wrong format.\"\"\"\n with self.assertRaises(TypeError):\n self.tree.set_speciation_parameters([0.4, 0.6], times=[0.1, 0.2, \"notafloat\"])\n with self.assertRaises(TypeError):\n # noinspection PyTypeChecker\n self.tree.set_speciation_parameters([0.4, 0.6], times=\"notafloat\")\n self.tree.times = []\n self.tree.set_speciation_parameters([0.4, 0.6], times=[0, 1, 10])\n self.assertEqual([0.0, 1.0, 10.0], self.tree.times)\n\n\nclass TestSimulationAnalysis(unittest.TestCase):\n \"\"\"\n Tests that the simulation can perform all required analyses, and that the correct errors are thrown if the object\n does not exist.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Copies the sample databases and applies a basic set of community parameters.\"\"\"\n src = os.path.join(\"sample\", \"sample2.db\")\n dst = os.path.join(\"output\", \"sample2.db\")\n if os.path.exists(dst):\n os.remove(dst)\n shutil.copy(src, dst)\n cls.tree = CoalescenceTree(logging_level=50)\n cls.tree.set_database(dst)\n cls.tree.wipe_data()\n cls.tree.set_speciation_parameters(\n speciation_rates=[0.5, 0.7],\n record_spatial=\"T\",\n record_fragments=os.path.join(\"sample\", \"FragmentsTest.csv\"),\n sample_file=os.path.join(\"sample\", \"SA_samplemaskINT.tif\"),\n )\n cls.tree.apply()\n cls.tree.calculate_fragment_richness()\n cls.tree.calculate_fragment_octaves()\n np.random.seed(100)\n\n def testSetDatabaseErrors(self):\n \"\"\"Tests that the set database errors are correctly raised.\"\"\"\n sim = Simulation()\n c = CoalescenceTree()\n with self.assertRaises(RuntimeError):\n c.set_database(sim)\n c = CoalescenceTree()\n with self.assertRaises(IOError):\n c.set_database(os.path.join(\"sample\", \"failsampledoesntexist.db\"))\n\n def testFragmentConfigNoExistError(self):\n \"\"\"Tests that an error is raised if the fragment config file does not exist.\"\"\"\n tree = CoalescenceTree(self.tree.file)\n with self.assertRaises(IOError):\n tree.set_speciation_parameters(\n speciation_rates=[0.5, 0.7],\n record_spatial=\"T\",\n record_fragments=os.path.join(\"sample\", \"notafragmentconfig.csv\"),\n sample_file=os.path.join(\"sample\", \"SA_samplemaskINT.tif\"),\n )\n with self.assertRaises(IOError):\n tree.set_speciation_parameters(\n speciation_rates=[0.5, 0.7],\n record_spatial=\"T\",\n record_fragments=os.path.join(\"sample\", \"example_historical_fine.tif\"),\n sample_file=os.path.join(\"sample\", \"SA_samplemaskINT.tif\"),\n )\n\n def testReadsFragmentsRichness(self):\n \"\"\"\n Tests that the fragment richness can be read correctly\n \"\"\"\n sim_params = self.tree.get_simulation_parameters()\n expected_params = dict(\n seed=9,\n task=1,\n output_dir=\"output\",\n speciation_rate=0.5,\n sigma=2.828427,\n tau=2.0,\n deme=1,\n sample_size=0.1,\n max_time=2.0,\n dispersal_relative_cost=1.0,\n min_num_species=1,\n habitat_change_rate=0.0,\n gen_since_historical=200.0,\n time_config_file=\"null\",\n coarse_map_file=\"sample/SA_sample_coarse.tif\",\n coarse_map_x=35,\n coarse_map_y=41,\n coarse_map_x_offset=11,\n coarse_map_y_offset=14,\n coarse_map_scale=1.0,\n fine_map_file=\"sample/SA_sample_fine.tif\",\n fine_map_x=13,\n fine_map_y=13,\n fine_map_x_offset=0,\n fine_map_y_offset=0,\n sample_file=\"sample/SA_samplemaskINT.tif\",\n grid_x=13,\n grid_y=13,\n sample_x=13,\n sample_y=13,\n sample_x_offset=0,\n sample_y_offset=0,\n historical_coarse_map=\"none\",\n historical_fine_map=\"none\",\n sim_complete=1,\n dispersal_method=\"normal\",\n m_probability=0.0,\n cutoff=0.0,\n landscape_type=\"closed\",\n protracted=0,\n min_speciation_gen=0.0,\n max_speciation_gen=0.0,\n dispersal_map=\"none\",\n )\n for key in sim_params.keys():\n self.assertEqual(\n sim_params[key],\n expected_params[key],\n msg=\"Error in {}: {} != {}\".format(key, sim_params[key], expected_params[key]),\n )\n fragment2_richness = [\"fragment2\", 1, 129]\n self.assertEqual(self.tree.get_fragment_richness(fragment=\"fragment2\", reference=1), 129)\n self.assertEqual(self.tree.get_fragment_richness(fragment=\"fragment1\", reference=2), 175)\n octaves = self.tree.get_fragment_richness()\n self.assertListEqual(fragment2_richness, [list(x) for x in octaves if x[0] == \"fragment2\" and x[1] == 1][0])\n expected_fragment_richness = []\n for reference in self.tree.get_community_references():\n for fragment in self.tree.get_fragment_list(reference):\n fragment_richness = self.tree.get_fragment_richness(fragment=fragment, reference=reference)\n expected_fragment_richness.append(\n {\"fragment\": fragment, \"community_reference\": reference, \"fragment_richness\": fragment_richness}\n )\n expected_fragment_richness_df = (\n pd.DataFrame(expected_fragment_richness)\n .sort_values(by=[\"fragment\", \"community_reference\"])\n .reset_index(drop=True)\n )\n actual_fragment_richness = self.tree.get_fragment_richness_pd().reset_index(drop=True)\n assert_frame_equal(expected_fragment_richness_df, actual_fragment_richness, check_like=True)\n\n def testGetsFragmentList(self):\n \"\"\"\n Tests that fetching the list of fragments from FRAGMENT_ABUNDANCES is as expected\n \"\"\"\n fragment_list = self.tree.get_fragment_list()\n expected_list = [\"fragment1\", \"fragment2\"]\n self.assertListEqual(expected_list, fragment_list)\n\n def testReadsFragmentAbundances(self):\n \"\"\"\n Tests that the fragment abundances are correctly read\n \"\"\"\n expected_abundances = [\n [610, 1],\n [611, 1],\n [612, 1],\n [613, 1],\n [614, 1],\n [615, 1],\n [616, 1],\n [617, 1],\n [618, 1],\n [619, 1],\n ]\n actual_abundances = self.tree.get_species_abundances(fragment=\"fragment2\", reference=1)\n for i, each in enumerate(expected_abundances):\n self.assertListEqual(actual_abundances[i], each)\n with self.assertRaises(ValueError):\n self.tree.get_species_abundances(fragment=\"fragment2\")\n expected_fragment_abundances_list = []\n for reference in self.tree.get_community_references():\n for fragment in self.tree.get_fragment_list(reference):\n fragment_abundances = self.tree.get_fragment_abundances(fragment=fragment, reference=reference)\n for species_id, abundance in fragment_abundances:\n expected_fragment_abundances_list.append(\n {\n \"fragment\": fragment,\n \"community_reference\": reference,\n \"species_id\": species_id,\n \"no_individuals\": abundance,\n }\n )\n expected_fragment_abundances = (\n pd.DataFrame(expected_fragment_abundances_list)\n .sort_values(by=[\"fragment\", \"community_reference\", \"species_id\"])\n .reset_index(drop=True)\n )\n actual_fragment_abundances = (\n self.tree.get_fragment_abundances_pd()\n .sort_values(by=[\"fragment\", \"community_reference\", \"species_id\"])\n .reset_index(drop=True)\n )\n assert_frame_equal(expected_fragment_abundances, actual_fragment_abundances, check_like=True)\n\n def testFragmentRichnessRaiseError(self):\n \"\"\"\n Tests that the correct errors are raised when no fragment exists with that name, or with the specified\n speciation rate, or time. Also checks SyntaxErrors and sqlite3.Errors when no FRAGMENT_RICHNESS table\n exists.\n \"\"\"\n failtree = CoalescenceTree()\n failtree.set_database(os.path.join(\"sample\", \"failsample.db\"))\n with self.assertRaises(IOError):\n failtree.get_fragment_richness()\n with self.assertRaises(IOError):\n failtree.get_fragment_richness_pd()\n with self.assertRaises(IOError):\n self.tree.get_fragment_richness(fragment=\"fragment4\", reference=1)\n with self.assertRaises(SyntaxError):\n self.tree.get_fragment_richness(fragment=\"fragment4\")\n with self.assertRaises(SyntaxError):\n self.tree.get_fragment_richness(reference=1)\n\n def testReadsFragmentOctaves(self):\n \"\"\"\n Tests that the fragment octaves can be read correctly.\n \"\"\"\n octaves = self.tree.get_fragment_octaves(fragment=\"fragment2\", reference=1)\n octaves2 = self.tree.get_fragment_octaves(fragment=\"fragment1\", reference=1)\n all_octaves = self.tree.get_fragment_octaves()\n desired = [\"fragment1\", 1, 0, 173]\n self.assertListEqual([0, 128], octaves[0])\n self.assertListEqual([0, 173], octaves2[0])\n self.assertListEqual(desired, [x for x in all_octaves if x[0] == \"fragment1\" and x[1] == 1 and x[2] == 0][0])\n expected_fragment_octaves_list = []\n for reference in self.tree.get_community_references():\n fragment_list = self.tree.get_fragment_list(reference)\n fragment_list.append(\"whole\")\n for fragment in fragment_list:\n try:\n octaves = self.tree.get_fragment_octaves(fragment=fragment, reference=reference)\n for octave, richness in octaves:\n expected_fragment_octaves_list.append(\n {\n \"fragment\": fragment,\n \"community_reference\": reference,\n \"octave\": octave,\n \"richness\": richness,\n }\n )\n except RuntimeError:\n continue\n expected_fragment_octaves = (\n pd.DataFrame(expected_fragment_octaves_list)\n .sort_values([\"fragment\", \"community_reference\", \"octave\"], axis=0)\n .reset_index(drop=True)\n )\n actual_fragment_octaves = (\n self.tree.get_fragment_octaves_pd()\n .sort_values([\"fragment\", \"community_reference\", \"octave\"], axis=0)\n .reset_index(drop=True)\n )\n assert_frame_equal(expected_fragment_octaves, actual_fragment_octaves, check_like=True)\n\n def testFragmentOctavesRaiseError(self):\n \"\"\"\n Tests that the correct errors are raised for different situations for reading fragment octaves\n \"\"\"\n failtree = CoalescenceTree()\n try:\n failtree.set_database(\"sample/failsample.db\")\n except sqlite3.Error:\n pass\n with self.assertRaises(sqlite3.Error):\n failtree.get_fragment_octaves(fragment=\"fragment4\", reference=100)\n with self.assertRaises(RuntimeError):\n self.tree.get_fragment_octaves(fragment=\"fragment4\", reference=100)\n with self.assertRaises(SyntaxError):\n self.tree.get_fragment_octaves(fragment=\"fragment4\")\n with self.assertRaises(SyntaxError):\n self.tree.get_fragment_octaves(reference=100)\n\n def testFragmentSampling(self):\n \"\"\"\n Tests that sampling from fragments is accurate.\n \"\"\"\n self.assertEqual(\n 10,\n self.tree.sample_fragment_richness(\n fragment=\"fragment1\", number_of_individuals=10, n=1, community_reference=2\n ),\n )\n self.assertEqual(\n 10,\n self.tree.sample_fragment_richness(\n fragment=\"fragment2\", number_of_individuals=10, n=10, community_reference=2\n ),\n )\n\n def testLandscapeSampling(self):\n \"\"\"Tests that the sampling from the landscape works as intended.\"\"\"\n number_dict = {\"fragment1\": 3, \"fragment2\": 10}\n np.random.seed(100)\n self.assertEqual(\n 13, self.tree.sample_landscape_richness(number_of_individuals=number_dict, n=1, community_reference=2)\n )\n self.assertAlmostEqual(\n 99.9, self.tree.sample_landscape_richness(number_of_individuals=100, n=10, community_reference=1), places=3\n )\n\n def testRaisesSamplingErrors(self):\n \"\"\"Tests that sampling errors are correctly raised\"\"\"\n number_dict = {\"fragment1\": 3000000, \"fragment2\": 10}\n with self.assertRaises(KeyError):\n self.assertEqual(\n 13, self.tree.sample_landscape_richness(number_of_individuals=number_dict, n=1, community_reference=2)\n )\n number_dict2 = {\"fragment\": 10, \"fragment2\": 10}\n with self.assertRaises(KeyError):\n self.assertEqual(\n 13, self.tree.sample_landscape_richness(number_of_individuals=number_dict2, n=1, community_reference=2)\n )\n\n def testSpeciesRichness(self):\n \"\"\"Tests that the simulation species richness is read correctly.\"\"\"\n actual_species_richness = (\n self.tree.get_species_richness_pd().sort_values(by=[\"community_reference\"]).reset_index(drop=True)\n )\n expected_species_richness_list = []\n for reference in self.tree.get_community_references():\n expected_species_richness_list.append(\n {\"community_reference\": reference, \"richness\": self.tree.get_species_richness(reference=reference)}\n )\n expected_species_richness = pd.DataFrame(expected_species_richness_list)\n assert_frame_equal(actual_species_richness, expected_species_richness, check_like=True)\n\n def testOctaves(self):\n \"\"\"Tests that the simulation octave classes are correctly calculated.\"\"\"\n actual_species_octaves = (\n self.tree.get_octaves_pd().sort_values(by=[\"community_reference\", \"octave\"]).reset_index(drop=True)\n )\n expected_species_octaves_list = []\n for reference in self.tree.get_community_references():\n for octave, richness in self.tree.get_octaves(reference):\n expected_species_octaves_list.append(\n {\"community_reference\": reference, \"octave\": octave, \"richness\": richness}\n )\n expected_species_octaves = pd.DataFrame(expected_species_octaves_list)\n assert_frame_equal(actual_species_octaves, expected_species_octaves, check_like=True)\n\n\nclass TestMetacommunityApplication(unittest.TestCase):\n \"\"\"\n Tests that a metacommunity can be applied correctly under the three different scenarios. Note that this does not\n test edge cases, just that the parameters are correctly stored and the different application methods work as\n intended.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Initialises the three database files to use.\"\"\"\n src = os.path.join(\"sample\", \"sample.db\")\n for i in range(6):\n dst = os.path.join(\"output\", \"sample_{}.db\".format(i))\n if os.path.exists(dst):\n os.remove(dst)\n shutil.copy2(src, dst)\n\n def testMetacommunityAddingInvalidParameters(self):\n \"\"\"Tests that adding invalid parameter for a metacommunity raises the appropriate errors.\"\"\"\n tree = CoalescenceTree(os.path.join(\"output\", \"sample_0.db\"))\n tree.wipe_data()\n with self.assertRaises(IOError):\n tree.get_metacommunity_parameters_pd()\n tree.set_speciation_parameters([0.1, 0.2])\n for size, spec, opt, ref in [\n [0, 0.1, \"simulated\", None],\n [10, 0.0, \"analytical\", None],\n [None, None, \"analytical\", None],\n [10, 0.0, \"path/to/file\", None],\n [0, 0.0, \"path/to/file\", None],\n [0, 0.0, \"path/to/not/a/file.db\", 1],\n ]:\n with self.assertRaises(ValueError):\n tree.add_metacommunity_parameters(\n metacommunity_size=size,\n metacommunity_speciation_rate=spec,\n metacommunity_option=opt,\n metacommunity_reference=ref,\n )\n with self.assertRaises(IOError):\n tree.add_metacommunity_parameters(metacommunity_option=\"not/a/file/db.db\", metacommunity_reference=1)\n\n def testMetacommunitySimulation(self):\n \"\"\"Tests that a simulated metacommunity works as intended.\"\"\"\n tree = CoalescenceTree(os.path.join(\"output\", \"sample_1.db\"))\n tree.wipe_data()\n tree.set_speciation_parameters(\n [0.1, 0.2], metacommunity_size=10000, metacommunity_speciation_rate=0.001, metacommunity_option=\"simulated\"\n )\n tree.add_metacommunity_parameters(\n metacommunity_size=15000, metacommunity_speciation_rate=0.1, metacommunity_option=\"simulated\"\n )\n tree.add_metacommunity_parameters(\n metacommunity_size=100000, metacommunity_speciation_rate=0.001, metacommunity_option=\"simulated\"\n )\n tree.apply()\n params_1 = tree.get_metacommunity_parameters(1)\n params_2 = tree.get_metacommunity_parameters(2)\n params_3 = tree.get_metacommunity_parameters(3)\n self.assertEqual(10000, params_1[\"metacommunity_size\"])\n self.assertEqual(0.001, params_1[\"speciation_rate\"])\n self.assertEqual(\"simulated\", params_1[\"option\"])\n self.assertEqual(0, params_1[\"external_reference\"])\n self.assertEqual(15000, params_2[\"metacommunity_size\"])\n self.assertEqual(0.1, params_2[\"speciation_rate\"])\n self.assertEqual(\"simulated\", params_2[\"option\"])\n self.assertEqual(0, params_2[\"external_reference\"])\n self.assertEqual(100000, params_3[\"metacommunity_size\"])\n self.assertEqual(0.001, params_3[\"speciation_rate\"])\n self.assertEqual(\"simulated\", params_3[\"option\"])\n self.assertEqual(0, params_3[\"external_reference\"])\n self.assertEqual(51, tree.get_species_richness(1))\n self.assertEqual(47, tree.get_species_richness(2))\n self.assertEqual(681, tree.get_species_richness(3))\n self.assertEqual(783, tree.get_species_richness(4))\n self.assertEqual(247, tree.get_species_richness(5))\n self.assertEqual(241, tree.get_species_richness(6))\n expected_metacommunity_parameters_list = []\n for reference in tree.get_community_references():\n try:\n params = tree.get_metacommunity_parameters(reference)\n params[\"reference\"] = reference\n expected_metacommunity_parameters_list.append(params)\n except KeyError:\n continue\n expected_metacommunity_parameters = pd.DataFrame(expected_metacommunity_parameters_list).sort_values(\n [\"reference\"]\n )\n actual_metacommunity_parameters = tree.get_metacommunity_parameters_pd().sort_values([\"reference\"])\n assert_frame_equal(expected_metacommunity_parameters, actual_metacommunity_parameters, check_like=True)\n\n def testMetacommunityAnalytical(self):\n \"\"\"Tests that an analytical metacommunity works as intended.\"\"\"\n tree = CoalescenceTree(os.path.join(\"output\", \"sample_2.db\"))\n tree.wipe_data()\n tree.set_speciation_parameters(\n [0.1, 0.2], metacommunity_size=10000, metacommunity_speciation_rate=0.001, metacommunity_option=\"analytical\"\n )\n tree.add_metacommunity_parameters(\n metacommunity_size=15000, metacommunity_speciation_rate=0.1, metacommunity_option=\"analytical\"\n )\n tree.add_metacommunity_parameters(\n metacommunity_size=100000, metacommunity_speciation_rate=0.001, metacommunity_option=\"analytical\"\n )\n tree.apply()\n params_1 = tree.get_metacommunity_parameters(1)\n params_2 = tree.get_metacommunity_parameters(2)\n params_3 = tree.get_metacommunity_parameters(3)\n self.assertEqual(10000, params_1[\"metacommunity_size\"])\n self.assertEqual(0.001, params_1[\"speciation_rate\"])\n self.assertEqual(\"analytical\", params_1[\"option\"])\n self.assertEqual(0, params_1[\"external_reference\"])\n self.assertEqual(15000, params_2[\"metacommunity_size\"])\n self.assertEqual(0.1, params_2[\"speciation_rate\"])\n self.assertEqual(\"analytical\", params_2[\"option\"])\n self.assertEqual(0, params_2[\"external_reference\"])\n self.assertEqual(100000, params_3[\"metacommunity_size\"])\n self.assertEqual(0.001, params_3[\"speciation_rate\"])\n self.assertEqual(\"analytical\", params_3[\"option\"])\n self.assertEqual(0, params_3[\"external_reference\"])\n self.assertEqual(51, tree.get_species_richness(1))\n self.assertEqual(57, tree.get_species_richness(2))\n self.assertEqual(694, tree.get_species_richness(3))\n self.assertEqual(760, tree.get_species_richness(4))\n self.assertEqual(222, tree.get_species_richness(5))\n self.assertEqual(234, tree.get_species_richness(6))\n\n def testMetacommunityExternal(self):\n \"\"\"Tests that an external metacommunity works as intended.\"\"\"\n tree = CoalescenceTree(os.path.join(\"output\", \"sample_3.db\"))\n tree.wipe_data()\n tree.set_speciation_parameters([0.1, 0.2], metacommunity_option=os.path.join(\"sample\", \"nse_reference.db\"))\n tree.add_metacommunity_parameters(\n metacommunity_option=os.path.join(\"sample\", \"nse_reference.db\"), metacommunity_reference=2\n )\n tree.apply()\n params_1 = tree.get_metacommunity_parameters(1)\n params_2 = tree.get_metacommunity_parameters(2)\n self.assertEqual(0, params_1[\"metacommunity_size\"])\n self.assertEqual(0.0, params_1[\"speciation_rate\"])\n self.assertEqual(os.path.join(\"sample\", \"nse_reference.db\"), params_1[\"option\"])\n self.assertEqual(1, params_1[\"external_reference\"])\n self.assertEqual(0, params_2[\"metacommunity_size\"])\n self.assertEqual(0.0, params_2[\"speciation_rate\"])\n self.assertEqual(os.path.join(\"sample\", \"nse_reference.db\"), params_2[\"option\"])\n self.assertEqual(2, params_2[\"external_reference\"])\n self.assertEqual(1, tree.get_species_richness(1))\n self.assertEqual(1, tree.get_species_richness(2))\n self.assertEqual(850, tree.get_species_richness(3))\n self.assertEqual(975, tree.get_species_richness(4))\n\n def testMetacommunityAnalyticalMethodDetection(self):\n \"\"\"Tests that the analytical method detection works correctly.\"\"\"\n tree = CoalescenceTree(os.path.join(\"output\", \"sample_4.db\"))\n tree.wipe_data()\n tree.set_speciation_parameters(\n [0.1, 0.2], metacommunity_size=110000, metacommunity_speciation_rate=0.5, metacommunity_option=\"none\"\n )\n tree.add_metacommunity_parameters(\n metacommunity_speciation_rate=0.5, metacommunity_size=120000, metacommunity_option=\"none\"\n )\n tree.apply()\n params_1 = tree.get_metacommunity_parameters(1)\n params_2 = tree.get_metacommunity_parameters(2)\n self.assertEqual(110000, params_1[\"metacommunity_size\"])\n self.assertEqual(0.5, params_1[\"speciation_rate\"])\n self.assertEqual(\"analytical\", params_1[\"option\"])\n self.assertEqual(120000, params_2[\"metacommunity_size\"])\n self.assertEqual(0.5, params_2[\"speciation_rate\"])\n self.assertEqual(\"analytical\", params_2[\"option\"])\n\n def testMetacommunitySimulatedMethodDetection(self):\n \"\"\"Tests that the simulated method detection works correctly.\"\"\"\n tree = CoalescenceTree(os.path.join(\"output\", \"sample_5.db\"))\n tree.wipe_data()\n tree.set_speciation_parameters(\n [0.1, 0.2], metacommunity_size=1000, metacommunity_speciation_rate=0.5, metacommunity_option=\"none\"\n )\n tree.add_metacommunity_parameters(\n metacommunity_speciation_rate=0.5, metacommunity_size=2000, metacommunity_option=\"none\"\n )\n tree.apply()\n params_1 = tree.get_metacommunity_parameters(1)\n params_2 = tree.get_metacommunity_parameters(2)\n self.assertEqual(1000, params_1[\"metacommunity_size\"])\n self.assertEqual(0.5, params_1[\"speciation_rate\"])\n self.assertEqual(\"simulated\", params_1[\"option\"])\n self.assertEqual(2000, params_2[\"metacommunity_size\"])\n self.assertEqual(0.5, params_2[\"speciation_rate\"])\n self.assertEqual(\"simulated\", params_2[\"option\"])\n\n\n@skipLongTest\nclass TestMetacommunityApplicationSpeciesAbundances(unittest.TestCase):\n \"\"\"Tests that the metacommunity application produces the expected species abundance distribution.\"\"\"\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Run a non-spatial sim and apply a metacommunity.\"\"\"\n cls.sim = Simulation()\n cls.sim.set_simulation_parameters(\n seed=11, task=110, output_directory=\"output\", min_speciation_rate=0.1, spatial=False, deme=20541\n )\n cls.sim.run()\n cls.ct = CoalescenceTree(cls.sim)\n cls.ct.wipe_data()\n cls.ct.set_speciation_parameters(speciation_rates=0.1)\n cls.ct.add_metacommunity_parameters(\n metacommunity_option=\"analytical\", metacommunity_size=1000000, metacommunity_speciation_rate=0.00005\n )\n cls.ct.add_metacommunity_parameters(\n metacommunity_option=\"simulated\", metacommunity_size=1000000, metacommunity_speciation_rate=0.00005\n )\n # This just tests that it doesn't take forever and produces a sensible output\n cls.ct.add_metacommunity_parameters(\n metacommunity_option=\"analytical\", metacommunity_size=1000000000, metacommunity_speciation_rate=0.1\n )\n cls.ct.apply()\n\n def testRichnessMatchness(self):\n \"\"\"Tests that the species richness is roughly equivalent between the two methods.\"\"\"\n self.assertAlmostEqual(244, self.ct.get_species_richness(2), delta=10)\n self.assertAlmostEqual(self.ct.get_species_richness(1), self.ct.get_species_richness(2), delta=30)\n self.assertEqual(5212, self.ct.get_species_richness(3))\n\n def testSpeciesAbundances(self):\n \"\"\"Tests the species abundance distribution is roughly equivalent between the two methods.\"\"\"\n sad_1 = [x[1] for x in self.ct.get_species_abundances(reference=1)]\n sad_2 = [x[1] for x in self.ct.get_species_abundances(reference=2)]\n mean_1 = sum(sad_1) / len(sad_1)\n mean_2 = sum(sad_2) / len(sad_2)\n # Check the mean abundance is roughly equivalent\n self.assertAlmostEqual(mean_1, mean_2, delta=10)\n # Check that the variances are roughly equivalent\n var_list_1 = [abs(x - mean_1) for x in sad_1]\n var_list_2 = [abs(x - mean_2) for x in sad_2]\n var_1 = sum(var_list_1) / len(var_list_1)\n var_2 = sum(var_list_2) / len(var_list_2)\n self.assertAlmostEqual(var_1, var_2, delta=5)\n expected_abundances_list = []\n for reference in self.ct.get_community_references():\n for species_id, abundance in self.ct.get_species_abundances(reference=reference):\n expected_abundances_list.append(\n {\"community_reference\": reference, \"species_id\": species_id, \"no_individuals\": abundance}\n )\n expected_abundances = pd.DataFrame(expected_abundances_list)\n actual_abundances = self.ct.get_species_abundances_pd()\n assert_frame_equal(actual_abundances, expected_abundances, check_like=True)\n\n\nclass TestMetacommunityApplicationOrdering(unittest.TestCase):\n \"\"\"Tests that the ordering of adding parameters to the metacommunity does not matter.\"\"\"\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Generates the test databases.\"\"\"\n src = os.path.join(\"sample\", \"sample3.db\")\n for i in [1, 2]:\n dst = os.path.join(\"output\", \"sample_order_{}.db\".format(i))\n if os.path.exists(dst):\n os.remove(dst)\n shutil.copy(src, dst)\n src = os.path.join(\"sample\", \"sample5.db\")\n for i in range(3, 6):\n dst = os.path.join(\"output\", \"sample_order_{}.db\".format(i))\n if os.path.exists(dst):\n os.remove(dst)\n shutil.copy(src, dst)\n cls.c1 = CoalescenceTree(os.path.join(\"output\", \"sample_order_1.db\"))\n cls.c2 = CoalescenceTree(os.path.join(\"output\", \"sample_order_2.db\"))\n cls.proc1 = CoalescenceTree(os.path.join(\"output\", \"sample_order_3.db\"))\n cls.proc2 = CoalescenceTree(os.path.join(\"output\", \"sample_order_4.db\"))\n cls.proc3 = CoalescenceTree(os.path.join(\"output\", \"sample_order_5.db\"))\n cls.c1.set_speciation_parameters(\n [0.1, 0.5, 0.9],\n metacommunity_speciation_rate=0.001,\n metacommunity_option=\"simulated\",\n metacommunity_size=10000,\n )\n cls.c1.apply()\n cls.c2.set_speciation_parameters([0.1, 0.5, 0.9])\n cls.c2.add_metacommunity_parameters(\n metacommunity_size=10000, metacommunity_speciation_rate=0.001, metacommunity_option=\"simulated\"\n )\n cls.c2.apply()\n cls.proc1.set_speciation_parameters(\n [0.1, 0.5, 0.9],\n protracted_speciation_min=5,\n protracted_speciation_max=1000,\n metacommunity_option=\"simulated\",\n metacommunity_speciation_rate=0.001,\n metacommunity_size=10000,\n )\n cls.proc1.apply()\n cls.proc2.set_speciation_parameters([0.1, 0.5, 0.9])\n cls.proc2.add_metacommunity_parameters(\n metacommunity_size=10000, metacommunity_speciation_rate=0.001, metacommunity_option=\"simulated\"\n )\n cls.proc2.add_protracted_parameters(min_speciation_gen=5, max_speciation_gen=1000)\n cls.proc2.apply()\n cls.proc3.set_speciation_parameters([0.1, 0.5, 0.9])\n cls.proc3.add_protracted_parameters(min_speciation_gen=5, max_speciation_gen=1000)\n cls.proc3.add_metacommunity_parameters(\n metacommunity_size=10000, metacommunity_speciation_rate=0.001, metacommunity_option=\"simulated\"\n )\n cls.proc3.apply()\n\n def testEquivalentMethodsMatch(self):\n \"\"\"Tests that equivalent methods of applying metacommunities produce equivalent results.\"\"\"\n for i in range(1, 4):\n self.assertEqual(self.c1.get_species_richness(i), self.c2.get_species_richness(i))\n self.assertEqual(self.proc1.get_species_richness(i), self.proc2.get_species_richness(i))\n self.assertEqual(self.proc2.get_species_richness(i), self.proc3.get_species_richness(i))\n\n def testMultipleProtractedError(self):\n \"\"\"Tests that adding multiple protracted speciation parameters raises the correct error.\"\"\"\n with self.assertRaises(ValueError):\n self.proc2.add_multiple_protracted_parameters()\n\n\nclass TestProtractedSpeciationEquality(unittest.TestCase):\n \"\"\"Tests that analysis performs as expected when protracted speciation parameters match the minimums.\"\"\"\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Copy the sample database.\"\"\"\n dst = os.path.join(\"output\", \"sample_protracted3.db\")\n shutil.copy(os.path.join(\"sample\", \"sample3.db\"), dst)\n cls.ct = CoalescenceTree(dst)\n cls.ct.wipe_data()\n\n def testApplyEqualParameters(self):\n \"\"\"Tests that equal protracted parameters can be applied\"\"\"\n self.ct.set_speciation_parameters(\n [0.001, 0.1], protracted_speciation_min=100.0, protracted_speciation_max=10000.0\n )\n self.ct.apply()\n self.assertEqual(1, self.ct.get_species_richness(1))\n self.assertEqual(3, self.ct.get_species_richness(2))\n\n\nclass TestSpeciesAgesCalculations(unittest.TestCase):\n \"\"\"Tests that operations associated with the species ages operate as expected\"\"\"\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Copies the sample databases and applies a basic set of community parameters.\"\"\"\n src = os.path.join(\"sample\", \"sample6.db\")\n dst = os.path.join(\"output\", \"sample6.db\")\n if os.path.exists(dst):\n os.remove(dst)\n shutil.copy(src, dst)\n cls.dst_file = dst\n\n def testSmallSimulation(self):\n tree = CoalescenceTree(logging_level=50)\n tree.set_database(self.dst_file)\n with self.assertRaises(IOError):\n _ = tree.get_species_ages()\n with self.assertRaises(IOError):\n _ = tree.get_species_ages_pd()\n tree.wipe_data()\n with self.assertRaises(IOError):\n _ = tree.get_species_ages()\n with self.assertRaises(IOError):\n _ = tree.get_species_ages_pd()\n tree.set_speciation_parameters(\n speciation_rates=[0.000001, 0.0001],\n record_spatial=False,\n record_ages=True,\n )\n tree.apply()\n self.assertTrue(check_sql_table_exist(tree.database, \"SPECIES_AGES\"))\n expected_df = pd.read_csv(os.path.join(\"sample\", \"expected_species_ages.csv\"))\n actual_df = tree.get_species_ages_pd().reset_index(drop=True)\n assert_frame_equal(expected_df, actual_df)\n for community_ref, group in expected_df.groupby([\"community_reference\"]):\n actual_output = sorted(tree.get_species_ages(community_ref), key=lambda x: x[0])\n expected_output = group.drop(columns=[\"community_reference\"]).sort_values(by=[\"species_id\"]).values.tolist()\n for ex, act in zip(expected_output, actual_output):\n self.assertEqual(ex[0], act[0])\n self.assertAlmostEqual(ex[1], act[1], delta=0.0000001)\n" ]
[ [ "pandas.testing.assert_frame_equal", "numpy.random.seed", "pandas.DataFrame" ] ]
[ { "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": [] } ]
cmougan/OODBenchmark
[ "e5d7b9540840afe64f6a00139cbc41a44ed01a80" ]
[ "xAIbenchmark.py" ]
[ "# %%\nfrom pmlb import fetch_data\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import cross_val_predict, KFold\nfrom sklearn.metrics import mean_squared_error, roc_auc_score\nfrom tqdm import tqdm\nimport pandas as pd\nimport numpy as np\nfrom collections import defaultdict\nimport warnings\nimport re\nimport traceback\nfrom pmlb import classification_dataset_names, regression_dataset_names\nfrom benchmark import benchmark_experiment\nfrom sklearn.linear_model import Lasso, LinearRegression\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\nfrom sklearn.tree import DecisionTreeRegressor\nimport warnings\nfrom fairtools.xaiUtils import ShapEstimator\nimport xgboost\n\n\nwarnings.filterwarnings(\"ignore\")\n\n# %%\ndef benchmark_experiment(datasets: list, model, classification: str = \"classification\"):\n\n assert classification in [\n \"classification\",\n \"regression\",\n \"explainableAI\",\n ], \"Classification type introduced --{}-- does not match: classification,regression,explainableAI\".format(\n classification\n )\n\n if classification == \"classification\":\n extension = \"_clas\"\n elif classification == \"regression\":\n extension = \"_reg\"\n elif classification == \"explainableAI\":\n extension = \"_explain\"\n else:\n raise \"Classification type not contained\"\n\n results = defaultdict()\n for i, dataset in enumerate(datasets):\n try:\n # Initialise the scaler\n standard_scaler = StandardScaler()\n\n # Load the dataset and split it\n X, y = fetch_data(dataset, return_X_y=True, local_cache_dir=\"data/\")\n\n # Scale the dataset\n X = standard_scaler.fit_transform(X)\n if classification == False:\n y = standard_scaler.fit_transform(y.reshape(-1, 1))\n\n # Back to dataframe\n X = pd.DataFrame(X, columns=[\"Var %d\" % (i + 1) for i in range(X.shape[1])])\n data = X.copy()\n data[\"target\"] = y\n\n # Min and max data limits for the experiment\n if X.shape[0] < 100:\n continue\n if X.shape[0] > 100_000:\n continue\n # Train test splitting points\n fracc = 0.33\n oneThird = int(data.shape[0] * fracc)\n twoThird = data.shape[0] - int(data.shape[0] * fracc)\n\n for idx, col in tqdm(enumerate(X.columns), total=len(X.columns)):\n\n # Sort data on the column\n data = data.sort_values(col).reset_index(drop=True).copy()\n\n # Train Test Split\n data_sub = data.iloc[:oneThird]\n data_train = data.iloc[oneThird:twoThird]\n data_up = data.iloc[twoThird:]\n\n X_tot = data.drop(columns=\"target\")\n X_tr = data_train.drop(columns=\"target\")\n X_sub = data_sub.drop(columns=\"target\")\n X_up = data_up.drop(columns=\"target\")\n\n y_tot = data[[\"target\"]].target.values\n y_tr = data_train[[\"target\"]].target.values\n y_sub = data_sub[[\"target\"]].target.values\n y_up = data_up[[\"target\"]].target.values\n\n # Error Calculation\n if classification == \"classification\":\n ## Test predictions\n pred_test = cross_val_predict(\n estimator=model,\n X=X_tr,\n y=y_tr,\n cv=KFold(n_splits=5, shuffle=True, random_state=0),\n method=\"predict_proba\",\n )[:, 1]\n\n ## Train\n model.fit(X_tr, y_tr)\n pred_train = model.predict_proba(X_tr)[:, 1]\n\n ## OOD\n X_ood = X_sub.append(X_up)\n y_ood = np.concatenate((y_sub, y_up))\n pred_ood = model.predict_proba(X_ood)[:, 1]\n\n train_error = roc_auc_score(y_tr, pred_train)\n test_error = roc_auc_score(y_tr, pred_test)\n ood_error = roc_auc_score(y_ood, pred_ood)\n generalizationError = test_error - train_error\n ood_performance = ood_error - test_error\n elif classification == \"regression\":\n ## Test predictions\n pred_test = cross_val_predict(\n estimator=model,\n X=X_tr,\n y=y_tr,\n cv=KFold(n_splits=5, shuffle=True, random_state=0),\n )\n\n ## Train\n model.fit(X_tr, y_tr)\n pred_train = model.predict(X_tr)\n\n ## OOD\n X_ood = X_sub.append(X_up)\n y_ood = np.concatenate((y_sub, y_up))\n pred_ood = model.predict(X_ood)\n\n train_error = mean_squared_error(pred_train, y_tr)\n test_error = mean_squared_error(pred_test, y_tr)\n ood_error = mean_squared_error(pred_ood, y_ood)\n\n generalizationError = test_error - train_error\n ood_performance = ood_error - test_error\n elif classification == \"explainableAI\":\n # Explainer predictor\n se = ShapEstimator(model=xgboost.XGBRegressor())\n shap_pred_tr = cross_val_predict(se, X_tr, y_tr, cv=3)\n ## Test predictions\n\n pred_test = cross_val_predict(\n estimator=model,\n X=shap_pred_tr,\n y=y_tr,\n cv=KFold(n_splits=5, shuffle=True, random_state=0),\n )\n\n ## Train\n se.fit(X_tr, y_tr)\n model.fit(shap_pred_tr, y_tr)\n pred_train = model.predict(shap_pred_tr)\n\n ## Generate OOD Shap data\n X_ood = X_sub.append(X_up)\n y_ood = np.concatenate((y_sub, y_up))\n shap_pred_ood = se.predict(X_ood)\n\n ## OOD\n pred_ood = model.predict(shap_pred_ood)\n\n train_error = mean_squared_error(pred_train, y_tr)\n test_error = mean_squared_error(pred_test, y_tr)\n ood_error = mean_squared_error(pred_ood, y_ood)\n\n generalizationError = test_error - train_error\n ood_performance = ood_error - test_error\n\n # Append Results\n model_name = str(type(model)).split(\".\")[-1]\n model_name = re.sub(\"[^A-Za-z0-9]+\", \"\", model_name)\n name = dataset + \"_column_\" + col\n results[name] = [\n train_error,\n test_error,\n ood_error,\n generalizationError,\n ood_performance,\n model_name,\n ]\n\n except Exception:\n print(traceback.format_exc())\n print(\"Not Working:\", dataset)\n print(\"Dataset shape:\", len(dataset))\n pass\n\n df = pd.DataFrame(data=results).T\n df.columns = [\n \"trainError\",\n \"testError\",\n \"oodError\",\n \"generalizationError\",\n \"oodPerformance\",\n \"model\",\n ]\n df.to_csv(\"results/\" + model_name + extension + \".csv\")\n\n\n# %%\nregression_dataset_names_sample = regression_dataset_names[:10]\n# %%\n\nmodelitos = [\n GradientBoostingRegressor(),\n]\nfor m in modelitos:\n benchmark_experiment(\n datasets=regression_dataset_names_sample,\n model=m,\n classification=\"explainableAI\",\n )\n\n# %%\n" ]
[ [ "sklearn.metrics.roc_auc_score", "sklearn.model_selection.cross_val_predict", "pandas.DataFrame", "sklearn.ensemble.GradientBoostingRegressor", "numpy.concatenate", "sklearn.metrics.mean_squared_error", "sklearn.model_selection.KFold", "sklearn.preprocessing.StandardScaler" ] ]
[ { "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": [] } ]
andresmasegosa/PRML-CoreSets
[ "fb768debb15e3ff6f5b65b7224915a41c1493f3d", "fb768debb15e3ff6f5b65b7224915a41c1493f3d", "fb768debb15e3ff6f5b65b7224915a41c1493f3d", "fb768debb15e3ff6f5b65b7224915a41c1493f3d", "fb768debb15e3ff6f5b65b7224915a41c1493f3d" ]
[ "[email protected]/bayesian_pca_DR.py", "[email protected]/evaluatePCA.py", "[email protected]/evaluateMoG.py", "datareduction/using.py", "datareduction/evaluateMoG.py" ]
[ "import numpy as np\nfrom prml.feature_extractions.pca import PCA\nfrom sklearn.cluster import KMeans, MiniBatchKMeans\nfrom sklearn.preprocessing import StandardScaler\n\n\nclass BayesianPCA_DR(PCA):\n\n def _clusteringError(self, X, kmeans):\n sum = 0\n for i in range(0, kmeans.cluster_centers_.shape[0]):\n a = X[kmeans.labels_ == i, :] - kmeans.cluster_centers_[i, :]\n sum += np.sqrt((a * a).sum(axis=1)).sum(axis=0)\n return sum\n\n def _random(self, X, n_clusters):\n\n centers_X = X[np.random.choice(X.shape[0], n_clusters, replace=False),:]\n centers_XX = centers_X**2\n weights = np.repeat(X.shape[0]/n_clusters,n_clusters)\n\n self.X_dr = {'X': centers_X, 'XX': centers_XX,\n 'W': weights}\n\n def _clusterSS(self, X, n_clusters):\n XX = X ** 2\n XJoin = np.concatenate((X, XX), axis=1)\n self.kmeans = MiniBatchKMeans(n_clusters=n_clusters).fit(XJoin)\n weights = np.asarray([sum(self.kmeans.labels_ == x) for x in range(0, n_clusters)])\n D=X.shape[1]\n self.X_dr = {'X': self.kmeans.cluster_centers_[:, 0:D], 'XX': self.kmeans.cluster_centers_[:, D:2 * D], 'W': weights}\n self.clusterError = self._clusteringError(XJoin,self.kmeans)\n\n def _cluster(self, X, n_clusters):\n self.kmeans = MiniBatchKMeans(n_clusters=n_clusters).fit(X)\n weights = np.asarray([sum(self.kmeans.labels_ == x) for x in range(0, n_clusters)])\n self.X_dr = {'X': self.kmeans.cluster_centers_, 'XX': self.kmeans.cluster_centers_ ** 2, 'W': weights}\n\n # def _clusterSS(self, X, n_clusters):\n # scaler = StandardScaler()\n # XX = X ** 2\n # XJoin = np.concatenate((X, XX), axis=1)\n # self.kmeans = MiniBatchKMeans(n_clusters=n_clusters).fit(scaler.fit_transform(XJoin))\n # weights = np.asarray([sum(self.kmeans.labels_ == x) for x in range(0, n_clusters)])\n # D=X.shape[1]\n # self.kmeans.cluster_centers_=scaler.inverse_transform(self.kmeans.cluster_centers_)\n # self.X_dr = {'X': self.kmeans.cluster_centers_[:, 0:D], 'XX': self.kmeans.cluster_centers_[:, D:2 * D], 'W': weights}\n #\n # def _cluster(self, X, n_clusters):\n # scaler = StandardScaler()\n # self.kmeans = MiniBatchKMeans(n_clusters=n_clusters).fit(scaler.fit_transform(X))\n # weights = np.asarray([sum(self.kmeans.labels_ == x) for x in range(0, n_clusters)])\n # self.kmeans.cluster_centers_=scaler.inverse_transform(self.kmeans.cluster_centers_)\n # self.X_dr = {'X': self.kmeans.cluster_centers_, 'XX': self.kmeans.cluster_centers_ ** 2, 'W': weights}\n\n def eigen(self, X_dr, *arg):\n sample_size = np.sum(X_dr['W'])\n X = self.X_dr['W'][:,None]*self.X_dr['X']\n n_features = X.shape[1]\n if sample_size >= n_features:\n cov = np.cov(X, rowvar=False)\n values, vectors = np.linalg.eigh(cov)\n index = n_features - self.n_components\n else:\n cov = np.cov(X)\n values, vectors = np.linalg.eigh(cov)\n vectors = (X.T @ vectors) / np.sqrt(sample_size * values)\n index = sample_size - self.n_components\n self.I = np.eye(self.n_components)\n if index == 0:\n self.var = 0\n else:\n self.var = np.mean(values[:index])\n\n self.W = vectors[:, index:].dot(np.sqrt(np.diag(values[index:]) - self.var * self.I))\n self.__M = self.W.T @ self.W + self.var * self.I\n self.C = self.W @ self.W.T + self.var * np.eye(n_features)\n if index == 0:\n self.Cinv = np.linalg.inv(self.C)\n else:\n self.Cinv = np.eye(n_features) / np.sqrt(self.var) - self.W @ np.linalg.inv(self.__M) @ self.W.T / self.var\n\n def fit(self, X, iter_max=100, initial=\"random\", n_clusters=10, cluster_method=\"SS\"):\n \"\"\"\n empirical bayes estimation of pca parameters\n\n Parameters\n ----------\n X : (sample_size, n_features) ndarray\n input data\n iter_max : int\n maximum number of em steps\n\n Returns\n -------\n mean : (n_features,) ndarray\n sample mean fo the input data\n W : (n_features, n_components) ndarray\n projection matrix\n var : float\n variance of observation noise\n \"\"\"\n if cluster_method== \"SS\":\n self._clusterSS(X,n_clusters)\n elif cluster_method== \"NoSS\":\n self._cluster(X,n_clusters)\n elif cluster_method == \"random\":\n self._random(X,n_clusters)\n\n initial_list = [\"random\", \"eigen\"]\n self.mean = np.sum(self.X_dr['W'][:,None]*self.X_dr['X'], axis=0)/sum(self.X_dr['W'])\n self.I = np.eye(self.n_components)\n if initial not in initial_list:\n print(\"availabel initializations are {}\".format(initial_list))\n if initial == \"random\":\n self.W = np.eye(np.size(self.X_dr['X'], 1), self.n_components)\n self.var = 1.\n elif initial == \"eigen\":\n self.eigen(self.X_dr)\n self.alpha = len(self.mean) / np.sum(self.W ** 2, axis=0).clip(min=1e-10)\n\n\n for i in range(iter_max):\n W = np.copy(self.W)\n Ez, Ezz = self._expectation(self.X_dr['X']-self.mean)\n self._maximization(self.X_dr, Ez, Ezz)\n #self.alpha = len(self.mean) / np.sum(self.W ** 2, axis=0).clip(min=1e-10)\n if np.allclose(W, self.W):\n break\n self.n_iter = i + 1\n self.C = self.W @ self.W.T + self.var * np.eye(np.size(self.X_dr['X'], 1))\n self.Cinv = np.linalg.inv(self.C)\n\n def _maximization(self, X_dr, Ez, Ezz):\n X_mean = (X_dr['X']-self.mean)\n self.W = (X_mean*X_dr['W'][:,None]).T @ Ez @ np.linalg.inv(np.sum(Ezz*X_dr['W'][:,None,None], axis=0) + self.var * np.diag(self.alpha))\n self.var = np.sum(\n (np.mean((X_dr['XX'] - 2*X_dr['X']*self.mean + self.mean ** 2), axis=-1)\n #(np.mean((X_mean** 2), axis=-1)\n - 2 * np.mean(Ez @ self.W.T * X_mean, axis=-1)\n + np.trace((Ezz @ self.W.T @ self.W).T)/ len(self.mean))*X_dr['W'])/sum(X_dr['W'])\n self.var=max(self.var,0.000001)\n\n def maximize(self, D, Ez, Ezz):\n self.W = D.T.dot(Ez).dot(np.linalg.inv(np.sum(Ezz, axis=0) + self.var * np.diag(self.alpha)))\n self.var = np.mean(\n np.mean(D ** 2, axis=-1)\n - 2 * np.mean(Ez.dot(self.W.T) * D, axis=-1)\n + np.trace(Ezz.dot(self.W.T).dot(self.W).T) / self.ndim)\n", "import matplotlib.animation as animation\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.cluster import KMeans\nimport inferpy as inf\n\nfrom datareduction.bayesian_pca_DR import BayesianPCA_DR\nfrom datareduction.variational_gaussian_mixture_DR import VariationalGaussianMixture_DR\nfrom prml.feature_extractions import BayesianPCA\nfrom prml.rv import VariationalGaussianMixture\nfrom prml.features import PolynomialFeatures\nfrom prml.linear import (\n VariationalLinearRegressor,\n VariationalLogisticRegressor\n)\n\nnp.random.seed(0)\n\n############## GENERATE DATA ########################\nN=200\nK=10\nM=10\nD=10\n\ndef create_toy_data(sample_size=100, ndim_hidden=1, ndim_observe=2, std=1.):\n Z = np.random.normal(size=(sample_size, ndim_hidden))\n mu = np.random.uniform(-5, 5, size=(ndim_observe))\n W = np.random.uniform(-5, 5, (ndim_hidden, ndim_observe))\n #print(W.T)\n X = Z.dot(W) + mu + np.random.normal(scale=std, size=(sample_size, ndim_observe))\n return X\n\ndata = create_toy_data(sample_size=N, ndim_hidden=K, ndim_observe=D, std=1.)\n\n#data = datasets.load_iris().data\n#data = datasets.fetch_california_housing().data\n#data = datasets.load_digits().data\n\n\nnp.take(data,np.random.permutation(data.shape[0]),axis=0,out=data)\nN=data.shape[0]\nD=data.shape[1]\n\nx_train=data[0:int(2.0*N/3),:]\nx_test=data[int(N/3.0):N,:]\n\n######################################################\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets(\"MNIST_data/\")\n\n#data = data[np.random.choice(np.where(target == 3)[0], 10000)]\nnp.take(mnist.train.images,np.random.permutation(mnist.train.images.shape[0]),axis=0,out=mnist.train.images)\nnp.take(mnist.test.images,np.random.permutation(mnist.test.images.shape[0]),axis=0,out=mnist.test.images)\n\nD=data.shape[1]\n\nx_train = mnist.train.images#[0:2000,:]\nx_test = mnist.test.images#[0:2000,:]\n\n\n\n#####################################################\n\n#bpca = BayesianPCA(n_components=K)\n#bpca.fit(x_train, initial=\"eigen\")\n#print(np.sum(bpca.log_proba(x_test)))\n#test_ll[0,:] = np.repeat(np.sum(bpca.log_proba(x_test)),10)\n######################################################\n\nsamples = np.zeros(10)\n\nsamples = np.array([int(x_train.shape[0]*(m+1)/100) for m in range(0,10) ])\nsamples = np.array([25, 50, 100, 250, 500, 750, 1000])\n#samples = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])\n#samples = np.array([20, 50, 100, 250, 500, 1000])\n\nclusterError = np.zeros(samples.shape[0])\n\ntest_ll = np.zeros((4,samples.shape[0]))\ntest_ll[0,:]=samples\n\nfor m in range(0,samples.shape[0]):\n print(samples[m])\n M=samples[m]\n np.random.seed(1234)\n bpca_dr = BayesianPCA_DR(n_components=K)\n bpca_dr.fit(x_train, initial=\"eigen\", n_clusters=M, cluster_method=\"SS\")\n test_ll[1,m]=np.sum(bpca_dr.log_proba(x_test))\n clusterError[m]=bpca_dr.clusterError\n print(test_ll[1,m])\n print(clusterError[m])\n print(np.sum(bpca_dr.log_proba(x_test)))\n #distance_ss[m]=np.linalg.norm(bpca.W - bpca_dr.W)\n np.random.seed(1234)\n bpca_dr = BayesianPCA_DR(n_components=K)\n bpca_dr.fit(x_train, initial=\"eigen\", n_clusters=M, cluster_method=\"NoSS\")\n test_ll[2,m]= np.sum(bpca_dr.log_proba(x_test))\n print(np.sum(bpca_dr.log_proba(x_test)))\n #distance_noss[m]=np.linalg.norm(bpca.W - bpca_dr.W)\n np.random.seed(1234)\n bpca_dr = BayesianPCA_DR(n_components=K)\n bpca_dr.fit(x_train, initial=\"eigen\", n_clusters=M, cluster_method=\"random\")\n test_ll[3,m]= np.sum(bpca_dr.log_proba(x_test))\n print(np.sum(bpca_dr.log_proba(x_test)))\n #distance_noss[m]=np.linalg.norm(bpca.W - bpca_dr.W)\n\n\nnp.savetxt('./figs/PCA_MINST_clustererror.txt', clusterError)\nnp.savetxt('./figs/PCA_MINST_data.txt',test_ll)\n\ntest_ll = np.loadtxt('./datareduction/figs/PCA_MINST_data.txt')\nclusterError = np.loadtxt('./datareduction/figs/PCA_MINST_clustererror.txt')\n\nx = [m for m in range(0,test_ll.shape[1])]\n\nplt.figure(0)\nplt.plot(x,test_ll[1,:], c='b', label='DR-SS')\nplt.plot(x,test_ll[2,:], c='g', label='DR-NoSS')\nplt.plot(x,test_ll[3,:], c='y', label='DR-Random')\nplt.legend(loc='lower right', shadow=True)\nplt.xticks(x, test_ll[0,:])\nplt.ylim(-0.5e07, 0.2e07, 100)\nplt.savefig(\"./datareduction/figs/PCA_MINST_LL.pdf\",bbox_inches='tight')\n\nplt.figure(1)\nplt.plot(x,test_ll[1,:], c='b', label='Log-Likelihood')\nplt.plot(x,clusterError, c='k', label='ClusterError')\nplt.legend(loc='center right', shadow=True)\nplt.xticks(x, test_ll[0,:])\nplt.ylim(2e05, 2e06, 100)\nplt.savefig(\"./datareduction/figs/PCA_MINST_ClusterError.pdf\",bbox_inches='tight')\nplt.show()\n\n\nfrom tabulate import tabulate\nprint(tabulate(test_ll, tablefmt=\"latex\", floatfmt=\".2f\"))\nprint(tabulate(clusterError[None,:], tablefmt=\"latex\", floatfmt=\".2f\"))\n", "import numpy as np\nimport inferpy as inf\nfrom skimage.transform import resize\nimport matplotlib.pyplot as plt\n\nfrom datareduction.variational_gaussian_mixture_DR import VariationalGaussianMixture_DR\nfrom prml.rv import VariationalGaussianMixture\n\n############## GENERATE DATA ########################\n\nN=10000\nK=10\nM=10\nD=10\n\nx_train = inf.models.Normal(0,0.1, dim = D).sample(int(N/K))\nx_test = inf.models.Normal(0,0.1, dim = D).sample(1000)\ny_test = np.repeat(0,int(N/K))\n\nfor i in range(1,K):\n x_train=np.append(x_train, inf.models.Normal(i,0.1, dim = D).sample(int(N/K)),axis=0)\n x_test=np.append(x_test, inf.models.Normal(i,0.1, dim = D).sample(1000),axis=0)\n y_test = np.append(y_test, np.repeat(i, int(N / K)))\n\n\nnp.random.seed(10)\n\ncov = np.random.rand(D,D)\ncov = np.dot(cov,cov.transpose())\n\nx_train = np.random.multivariate_normal(np.repeat(0,D),cov,int(N/K))\nx_test = np.random.multivariate_normal(np.repeat(0,D),cov,int(N/K))\ny_test = np.repeat(0,int(N/K))\n\nfor i in range(1,K):\n x_train=np.append(x_train, np.random.multivariate_normal(np.repeat(10*i,D),cov,int(N/K)),axis=0)\n x_test=np.append(x_test, np.random.multivariate_normal(np.repeat(10*i,D),cov,int(N/K)),axis=0)\n y_test = np.append(y_test, np.repeat(i, int(N / K)))\n\n\n\nnp.take(x_train,np.random.permutation(x_train.shape[0]),axis=0,out=x_train)\n\n\n######################################################\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets(\"MNIST_data/\")\n\n#data = data[np.random.choice(np.where(target == 3)[0], 10000)]\nnp.take(mnist.train.images,np.random.permutation(mnist.train.images.shape[0]),axis=0,out=mnist.train.images)\nnp.take(mnist.test.images,np.random.permutation(mnist.test.images.shape[0]),axis=0,out=mnist.test.images)\n\nD=mnist.train.images.shape[1]\n\nx_train = mnist.train.images#[0:1000,:]\nx_test = mnist.test.images#[0:1000,:]\ny_test =mnist.test.labels#[0:1000]\n\nx_train2 = np.zeros((x_train.shape[0],100))\nx_test2 = np.zeros((x_test.shape[0],100))\n\nfor i in range(0, x_train.shape[0]):\n x_train2[i,:]=np.resize(resize(np.resize(x_train[i],(28,28)), (10, 10)),(1,100))\n\nfor i in range(0, x_test.shape[0]):\n x_test2[i,:]=np.resize(resize(np.resize(x_test[i],(28,28)), (10, 10)),(1,100))\n\nx_train = x_train2\nx_test = x_test2\n\n######################################################\nnp.random.seed(1234)\n\n#\n# vgmm = VariationalGaussianMixture(n_components=K)\n# vgmm.fit(x_train)\n#\n# test_ll[0,:] = np.repeat(np.sum(vgmm.logpdf(x_test)),10)\n# similarty[0,:] = np.repeat(metrics.adjusted_mutual_info_score(y_test,vgmm.classify(x_test)),10)\n# #print(test_ll[0, 0])\n# #print(similarty[0, 0])\n# print(np.sum([np.linalg.det(vgmm.W[k]) for k in range(i, K)]))\n# params = np.hstack([p.flatten() for p in vgmm.get_params()])\n######################################################\n\nsamples = np.zeros(10)\n\nsamples = [int(x_train.shape[0]*(m+1)/1000) for m in range(0,10) ]\nsamples = np.array([25, 50, 100, 250, 500, 750, 1000])\n#samples = np.array([25, 50])\n\nclusterError = np.zeros(samples.shape[0])\n\ntest_ll = np.zeros((4,samples.shape[0]))\ntest_ll[0,:]=samples\n\nfor m in range(0,samples.shape[0]):\n print(samples[m])\n M=samples[m]\n np.random.seed(1234)\n vgmm_dr = VariationalGaussianMixture_DR(n_components=K)\n vgmm_dr.fit(x_train, n_clusters=M, cluster_method=\"SS\")\n #print(np.sum([np.linalg.det(vgmm_dr.W[k]) for k in range(i,K)]))\n test_ll[1,m]=np.sum(vgmm_dr.logpdf(x_test))\n clusterError[m]=vgmm_dr.clusterError\n #similarty[1,m] = metrics.adjusted_rand_score(y_test, vgmm_dr.classify(x_test))\n print(test_ll[1,m])\n #print(similarty[1,m])\n #distance_ss[m]=np.linalg.norm(params-np.hstack([p.flatten() for p in vgmm_dr.get_params()]))\n np.random.seed(1234)\n vgmm_dr = VariationalGaussianMixture_DR(n_components=K)\n vgmm_dr.fit(x_train, n_clusters=M, cluster_method=\"NoSS\")\n #print(np.sum([np.linalg.det(vgmm_dr.W[k]) for k in range(i,K)]))\n test_ll[2,m]= np.sum(vgmm_dr.logpdf(x_test))\n #similarty[2,m] = metrics.adjusted_rand_score(y_test, vgmm_dr.classify(x_test))\n print(test_ll[2,m])\n #print(similarty[2,m])\n #distance_noss[m]=np.linalg.norm(params-np.hstack([p.flatten() for p in vgmm_dr.get_params()]))\n np.random.seed(1234)\n vgmm_dr = VariationalGaussianMixture_DR(n_components=K)\n vgmm_dr.fit(x_train, n_clusters=M, cluster_method=\"random\")\n #print(np.sum([np.linalg.det(vgmm_dr.W[k]) for k in range(i,K)]))\n test_ll[3,m]= np.sum(vgmm_dr.logpdf(x_test))\n #similarty[3,m] = metrics.adjusted_rand_score(y_test, vgmm_dr.classify(x_test))\n print(test_ll[3,m])\n #print(similarty[3,m])\n #distance_noss[m]=np.linalg.norm(params-np.hstack([p.flatten() for p in vgmm_dr.get_params()]))\n\n\nnp.savetxt('./figs/MoG_MINST_clustererror.txt', clusterError)\nnp.savetxt('./figs/MoG_MINST_data.txt',test_ll)\n\nclusterError = np.loadtxt('./datareduction/figs/MoG_MINST_clustererror.txt')\ntest_ll = np.loadtxt('./datareduction/figs/MoG_MINST_data.txt')\n\n\nx = [m for m in range(0,test_ll.shape[1])]\n\nplt.figure(0)\nplt.plot(x,test_ll[1,:], c='b', label='DR-SS')\nplt.plot(x,test_ll[2,:], c='g', label='DR-NoSS')\nplt.plot(x,test_ll[3,:], c='y', label='DR-Random')\nplt.legend(loc='lower right', shadow=True)\nplt.xticks(x, test_ll[0,:])\nplt.ylim(-0.5e07, 0.2e07, 100)\nplt.savefig(\"./datareduction/figs/MoG_MINST_LL.pdf\",bbox_inches='tight')\n\nplt.figure(1)\nplt.plot(x,test_ll[1,:], c='b', label='Log-Likelihood')\nplt.plot(x,clusterError, c='k', label='ClusterError')\nplt.legend(loc='center right', shadow=True)\nplt.xticks(x, test_ll[0,:])\nplt.ylim(2e05, 2e06, 100)\nplt.savefig(\"./datareduction/figs/MoG_MINST_ClusterError.pdf\",bbox_inches='tight')\nplt.show()\n\n\nfrom tabulate import tabulate\nprint(tabulate(test_ll, tablefmt=\"latex\", floatfmt=\".2f\"))\nprint(tabulate(clusterError[None,:], tablefmt=\"latex\", floatfmt=\".2f\"))\n", "import matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.cluster import KMeans, MiniBatchKMeans, SpectralClustering\nimport inferpy as inf\nfrom sklearn import metrics\nfrom sklearn.preprocessing import StandardScaler\nfrom datareduction.variational_gaussian_mixture_DR import VariationalGaussianMixture_DR\n\nfrom datareduction.bayesian_pca_DR import BayesianPCA_DR\nfrom prml.feature_extractions import BayesianPCA, PCA\n#\n# ############## GENERATE DATA ########################\n# ############################################\n\nnp.random.seed(1234)\n\nN=2000\nK=1\nM=3\nD=2\n\n\ndef create_toy_data(sample_size=100, ndim_hidden=1, ndim_observe=2, std=1.):\n Z = np.random.normal(size=(sample_size, ndim_hidden))\n mu = np.random.uniform(-5, 5, size=(ndim_observe))\n W = np.random.uniform(-5, 5, (ndim_hidden, ndim_observe))\n print(W.T)\n X = Z.dot(W) + mu + np.random.normal(scale=std, size=(sample_size, ndim_observe))\n return X\n\ndata = create_toy_data(sample_size=N, ndim_hidden=K, ndim_observe=D, std=1)\n\n\nnp.take(data,np.random.permutation(data.shape[0]),axis=0,out=data)\nN=data.shape[0]\nD=data.shape[1]\n\nX=data[0:int(2.0*N/3),:]\nx_test=data[int(N/3.0):N,:]\nn_clusters = M\n\nnp.random.seed(14)\n\nXX = X ** 2\nXJoin = np.concatenate((X, XX), axis=1)\nscaler = StandardScaler()\nXJoin_scaled=scaler.fit_transform(XJoin)\nkmeans = MiniBatchKMeans(n_clusters=n_clusters).fit(XJoin_scaled)\nweights = np.asarray([sum(kmeans.labels_ == x) for x in range(0, n_clusters)])\nD = X.shape[1]\nX_dr = {'X': kmeans.cluster_centers_[:, 0:D], 'XX': kmeans.cluster_centers_[:, D:2 * D], 'W': weights}\n\nplt.scatter(X[:, 0], X[:, 1], c = kmeans.labels_)\n\nnp.random.seed(1)\nX= np.linspace(-10,10,100)[:,None]\nXX = X ** 2\nXJoin = np.concatenate((X, XX), axis=1)\nfrom sklearn import preprocessing\nXJoin = preprocessing.scale(XJoin)\nkmeans = MiniBatchKMeans(n_clusters=5).fit(XJoin)\nplt.scatter(XJoin[:, 0], XJoin[:, 1], c = kmeans.labels_)\nplt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], marker='+', s=100, c = np.arange(0,5))\n\nsum = 0\nfor i in range(0,5):\n a = XJoin[kmeans.labels_ == i, :] - kmeans.cluster_centers_[i, :]\n sum += np.sqrt((a*a).sum(axis=1)).sum(axis=0)\n\nprint(sum)\n\n\nkmeans = MiniBatchKMeans(n_clusters=20).fit(XJoin)\nplt.scatter(XJoin[:, 0], XJoin[:, 1], c = kmeans.labels_)\nplt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], marker='+', s=100)\n\nsum = 0\nfor i in range(0,20):\n a = XJoin[kmeans.labels_ == i, :] - kmeans.cluster_centers_[i, :]\n sum += np.sqrt((a*a).sum(axis=1)).sum(axis=0)\n\nprint(sum)\n\n#\n#\n#\n#\n# ######################################################\n# from tensorflow.examples.tutorials.mnist import input_data\n#\n# mnist = input_data.read_data_sets(\"MNIST_data/\")\n#\n# #data = data[np.random.choice(np.where(target == 3)[0], 10000)]\n# np.take(mnist.train.images,np.random.permutation(mnist.train.images.shape[0]),axis=0,out=mnist.train.images)\n# np.take(mnist.test.images,np.random.permutation(mnist.test.images.shape[0]),axis=0,out=mnist.test.images)\n#\n# D=mnist.train.images.shape[1]\n#\n# x_train = mnist.train.images[0:1000,:]\n# x_test = mnist.test.images[0:1000,:]\n# y_test =mnist.test.labels#[0:1000]\n#\n# x_train2 = np.zeros((1000,100))\n#\n# from skimage.transform import resize\n# for i in range(0,x_train.shape[0]):\n# x_train2[i,:]=np.resize(resize(np.resize(x_train[i],(28,28)), (10, 10)),(1,100))\n#\n#\n#\n# ############## GENERATE DATA ########################\n#\n# N=1000\n# K=2\n# M=10\n# D=2\n#\n#\n#\n# np.random.seed(10)\n#\n# cov = np.random.rand(D,D)\n# cov = np.dot(cov,cov.transpose())\n#\n# x_train = np.random.multivariate_normal(np.repeat(5,D),cov,int(N/K))\n# x_test = np.random.multivariate_normal(np.repeat(5,D),cov,int(N/K))\n# y_test = np.repeat(0,int(N/K))\n#\n# for i in range(1,K):\n# x_train=np.append(x_train, np.random.multivariate_normal(np.repeat(10*i,D),cov,int(N/K)),axis=0)\n# x_test=np.append(x_test, np.random.multivariate_normal(np.repeat(10*i,D),cov,int(N/K)),axis=0)\n# y_test = np.append(y_test, np.repeat(i, int(N / K)))\n#\n#\n# np.take(x_train,np.random.permutation(x_train.shape[0]),axis=0,out=x_train)\n# a=0\n# b=15\n# c=0\n# d=15\n# np.random.seed(123456)\n# vgmm_dr = VariationalGaussianMixture_DR(n_components=K)\n# vgmm_dr.fit(x_train, n_clusters=10, cluster_method=\"random\")\n# vgmm_dr.mu\n#\n# plt.scatter(x_train[:, 0], x_train[:, 1], c=vgmm_dr.classify(x_train))\n# x0, x1 = np.meshgrid(np.linspace(a, b, 1000), np.linspace(c, d, 1000))\n# x = np.array([x0, x1]).reshape(2, -1).T\n# plt.contour(x0, x1, np.exp(vgmm_dr.logpdf(x)).reshape(1000, 1000))\n# plt.scatter(vgmm_dr.X_dr['X'][:,0],vgmm_dr.X_dr['X'][:,1], c='k', s=100.0, marker='+')\n# plt.xlim(a, b, 100)\n# plt.ylim(c, d, 100)\n# plt.gca().set_aspect('equal', adjustable='box')\n#\n#\n#\n#\n#\n#\n# import matplotlib.pyplot as plt\n# import numpy as np\n#\n# # fake up some data\n# spread = np.random.rand(50) * 100\n# center = np.ones(25) * 50\n# flier_high = np.random.rand(10) * 100 + 100\n# flier_low = np.random.rand(10) * -100\n# data = np.concatenate((spread, center, flier_high, flier_low), 0)\n#\n# # basic plot\n# plt.boxplot(data)\n#\n# # notched plot\n# plt.figure()\n# plt.boxplot(data, 1)\n#\n# # change outlier point symbols\n# plt.figure()\n# plt.boxplot(data, 0, 'gD')\n#\n# # don't show outlier points\n# plt.figure()\n# plt.boxplot(data, 0, '')\n#\n# # horizontal boxes\n# plt.figure()\n# plt.boxplot(data, 0, 'rs', 0)\n#\n# # change whisker length\n# plt.figure()\n# plt.boxplot(data, 0, 'rs', 0, 0.75)\n#\n# # fake up some more data\n# spread = np.random.rand(50) * 100\n# center = np.ones(25) * 40\n# flier_high = np.random.rand(10) * 100 + 100\n# flier_low = np.random.rand(10) * -100\n# d2 = np.concatenate((spread, center, flier_high, flier_low), 0)\n# data.shape = (-1, 1)\n# d2.shape = (-1, 1)\n# # data = concatenate( (data, d2), 1 )\n# # Making a 2-D array only works if all the columns are the\n# # same length. If they are not, then use a list instead.\n# # This is actually more efficient because boxplot converts\n# # a 2-D array into a list of vectors internally anyway.\n# data = [data, d2, d2[::2, 0]]\n# # multiple box plots on one figure\n# plt.figure()\n# plt.boxplot(data)\n#\n# plt.show()\n#\n#\nimport numpy as np\nimport matplotlib.pyplot as plt\nnp.random.seed(10)\ncollectn_1 = np.random.normal(100, 10, 200)\ncollectn_2 = np.random.normal(80, 30, 200)\ncollectn_3 = np.random.normal(90, 20, 200)\ncollectn_4 = np.random.normal(70, 25, 200)\n\ndata_to_plot = [collectn_1, collectn_2, collectn_3, collectn_4]\n\na = np.stack(data_to_plot, axis=0)\n\nplt.boxplot(data_to_plot)\n\nnp.random.seed(1220)\ncollectn_1 = np.random.normal(100, 10, 200)\ncollectn_2 = np.random.normal(80, 30, 200)\ncollectn_3 = np.random.normal(90, 20, 200)\ncollectn_4 = np.random.normal(70, 25, 200)\n\ndata_to_plot = [collectn_1, collectn_2, collectn_3, collectn_4]\n\na = np.stack(data_to_plot, axis=0)\n\nplt.boxplot(data_to_plot)\n#\n#\n#\n#\n\n#############\n\n# Author: Olivier Grisel <[email protected]>\n# Lars Buitinck\n# Chyi-Kwei Yau <[email protected]>\n# License: BSD 3 clause\n\nfrom __future__ import print_function\nfrom time import time\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn.decomposition import NMF, LatentDirichletAllocation\nfrom sklearn.datasets import fetch_20newsgroups\n\nfrom datareduction.online_lda_full import LatentDirichletAllocationFULL\n\nn_samples = 2000\nn_features = 1000\nn_components = 10\nn_top_words = 20\n\n\ndef print_top_words(model, feature_names, n_top_words):\n for topic_idx, topic in enumerate(model.components_):\n message = \"Topic #%d: \" % topic_idx\n message += \" \".join([feature_names[i]\n for i in topic.argsort()[:-n_top_words - 1:-1]])\n print(message)\n print()\n\n\n# Load the 20 newsgroups dataset and vectorize it. We use a few heuristics\n# to filter out useless terms early on: the posts are stripped of headers,\n# footers and quoted replies, and common English words, words occurring in\n# only one document or in at least 95% of the documents are removed.\n\nprint(\"Loading dataset...\")\nt0 = time()\ndataset = fetch_20newsgroups(shuffle=True, random_state=1,\n remove=('headers', 'footers', 'quotes'))\ndata_samples = dataset.data[:n_samples]\nprint(\"done in %0.3fs.\" % (time() - t0))\n\n# Use tf-idf features for NMF.\nprint(\"Extracting tf-idf features for NMF...\")\ntfidf_vectorizer = TfidfVectorizer(max_df=0.95, min_df=2,\n max_features=n_features,\n stop_words='english')\nt0 = time()\ntfidf = tfidf_vectorizer.fit_transform(data_samples)\nprint(\"done in %0.3fs.\" % (time() - t0))\n\n# Use tf (raw term count) features for LDA.\nprint(\"Extracting tf features for LDA...\")\ntf_vectorizer = CountVectorizer(max_df=0.95, min_df=2,\n max_features=n_features,\n stop_words='english')\nt0 = time()\ntf = tf_vectorizer.fit_transform(data_samples)\nprint(\"done in %0.3fs.\" % (time() - t0))\nprint()\n\n# # Fit the NMF model\n# print(\"Fitting the NMF model (Frobenius norm) with tf-idf features, \"\n# \"n_samples=%d and n_features=%d...\"\n# % (n_samples, n_features))\n# t0 = time()\n# nmf = NMF(n_components=n_components, random_state=1,\n# alpha=.1, l1_ratio=.5).fit(tfidf)\n# print(\"done in %0.3fs.\" % (time() - t0))\n#\n# print(\"\\nTopics in NMF model (Frobenius norm):\")\n# tfidf_feature_names = tfidf_vectorizer.get_feature_names()\n# print_top_words(nmf, tfidf_feature_names, n_top_words)\n#\n# # Fit the NMF model\n# print(\"Fitting the NMF model (generalized Kullback-Leibler divergence) with \"\n# \"tf-idf features, n_samples=%d and n_features=%d...\"\n# % (n_samples, n_features))\n# t0 = time()\n# nmf = NMF(n_components=n_components, random_state=1,\n# beta_loss='kullback-leibler', solver='mu', max_iter=1000, alpha=.1,\n# l1_ratio=.5).fit(tfidf)\n# print(\"done in %0.3fs.\" % (time() - t0))\n#\n# print(\"\\nTopics in NMF model (generalized Kullback-Leibler divergence):\")\n# tfidf_feature_names = tfidf_vectorizer.get_feature_names()\n# print_top_words(nmf, tfidf_feature_names, n_top_words)\n#\n# print(\"Fitting LDA models with tf features, \"\n# \"n_samples=%d and n_features=%d...\"\n# % (n_samples, n_features))\n# lda = LatentDirichletAllocation(n_components=n_components,\n# learning_method='batch',\n# random_state=0)\n# t0 = time()\n# lda.fit(tf)\n# print(\"done in %0.3fs.\" % (time() - t0))\n#\n# print(\"\\nTopics in LDA model:\")\n# tf_feature_names = tf_vectorizer.get_feature_names()\n# print_top_words(lda, tf_feature_names, n_top_words)\n#\n\nlda = LatentDirichletAllocationFULL(n_components=n_components,\n learning_method='batch',\n random_state=0)\nt0 = time()\nlda.fit(tf)\nprint(\"done in %0.3fs.\" % (time() - t0))\n\nprint(\"\\nTopics in LDA model:\")\ntf_feature_names = tf_vectorizer.get_feature_names()\nprint_top_words(lda, tf_feature_names, n_top_words)\n\n\n# from kmodes.kmodes import KModes\n#\n# km = KModes(n_clusters=4, init='random', n_init=1)\n#\n# clusters = km.fit_predict(tf.toarray())\n#\nimport numpy as np\nid = np.array([1, 3])\nw = np.array([3, 1])\n\nm = np.array([[0, 1, 2, 3, 4, 5],[6, 7, 8, 9, 10,11]])\n\nm[:,id]\n\nnp.repeat(m[:,id],w, axis = 1).shape\n\n\n\n\n######################################################\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport numpy as np\nmnist = input_data.read_data_sets(\"MNIST_data/\")\n\n#data = data[np.random.choice(np.where(target == 3)[0], 10000)]\nnp.take(mnist.train.images,np.random.permutation(mnist.train.images.shape[0]),axis=0,out=mnist.train.images)\nnp.take(mnist.test.images,np.random.permutation(mnist.test.images.shape[0]),axis=0,out=mnist.test.images)\n\nD=mnist.train.images.shape[1]\n\nX = mnist.train.images[0:1000,:]\nx_test = mnist.test.images[0:1000,:]\ny_test =mnist.test.labels#[0:1000]\n\n\n\na = np.array_split(X,10, axis=0)\n\nX_slide = a[0]\nXX_slide = np.multiply(X_slide[:, :, None], X_slide[:, None, :])\nXX_slide = XX_slide.reshape((XX_slide.shape[0], -1))\nXJoin_slide = np.concatenate((X_slide, XX_slide), axis=1)\nXJoin_slide.shape\n\nfrom sklearn import random_projection\ntransformer = random_projection.GaussianRandomProjection(n_components=28*28)\n#transformer = random_projection.SparseRandomProjection(n_components=28*28)\nX_proyected = transformer.fit_transform(XJoin_slide)\nX_proyected.shape\n\nfor i in range(1,len(a)):\n X_slide = a[i]\n XX_slide = np.multiply(X_slide[:, :, None], X_slide[:, None, :])\n XX_slide = XX_slide.reshape((XX_slide.shape[0], -1))\n XJoin_slide = np.concatenate((X_slide, XX_slide), axis=1)\n X_proyected=np.append(X_proyected, transformer.transform(XJoin_slide),axis=0)\n\n\nkmeans = MiniBatchKMeans(n_clusters=5).fit(X_proyected)\n\nclusters = np.zeros((5,28**2+28**4))\nfor i in range(0,5):\n XCluster = X[kmeans.labels_ == i]\n XXCluster = np.multiply(XCluster[:, :, None], XCluster[:, None, :])\n XXCluster = XXCluster.reshape((XXCluster.shape[0], -1))\n XCluster_Join = np.concatenate((XCluster, XXCluster), axis=1)\n clusters[i,:]=np.mean(XCluster_Join,axis=0)\n\n\n\nfrom slackclient import SlackClient\n\nsc = SlackClient('xoxp-157419655798-161969456967-412895555920-73008d912fdc1999899080b1d1bc44eb')\n\ntext = \"Hola\"+str(4)\nsc.api_call(\n \"chat.postMessage\",\n channel=\"@andresmasegosa\",\n text=text\n)\n\nweights = np.array([3,4,5,0,6])\nfor i in range(0, weights.shape[0]):\n if (weights[i] == 0):\n continue\n print(weights[i])\n", "import numpy as np\nimport inferpy as inf\nfrom skimage.transform import resize\n\nfrom datareduction.variational_gaussian_mixture_DR import VariationalGaussianMixture_DR\nfrom prml.rv import VariationalGaussianMixture\n\n############## GENERATE DATA ########################\n\nN=10000\nK=10\nM=10\nD=10\n\nx_train = inf.models.Normal(0,0.1, dim = D).sample(int(N/K))\nx_test = inf.models.Normal(0,0.1, dim = D).sample(1000)\ny_test = np.repeat(0,int(N/K))\n\nfor i in range(1,K):\n x_train=np.append(x_train, inf.models.Normal(i,0.1, dim = D).sample(int(N/K)),axis=0)\n x_test=np.append(x_test, inf.models.Normal(i,0.1, dim = D).sample(1000),axis=0)\n y_test = np.append(y_test, np.repeat(i, int(N / K)))\n\n\nnp.random.seed(10)\n\ncov = np.random.rand(D,D)\ncov = np.dot(cov,cov.transpose())\n\nx_train = np.random.multivariate_normal(np.repeat(0,D),cov,int(N/K))\nx_test = np.random.multivariate_normal(np.repeat(0,D),cov,int(N/K))\ny_test = np.repeat(0,int(N/K))\n\nfor i in range(1,K):\n x_train=np.append(x_train, np.random.multivariate_normal(np.repeat(10*i,D),cov,int(N/K)),axis=0)\n x_test=np.append(x_test, np.random.multivariate_normal(np.repeat(10*i,D),cov,int(N/K)),axis=0)\n y_test = np.append(y_test, np.repeat(i, int(N / K)))\n\n\n\nnp.take(x_train,np.random.permutation(x_train.shape[0]),axis=0,out=x_train)\n\n\n######################################################\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets(\"MNIST_data/\")\n\n#data = data[np.random.choice(np.where(target == 3)[0], 10000)]\nnp.take(mnist.train.images,np.random.permutation(mnist.train.images.shape[0]),axis=0,out=mnist.train.images)\nnp.take(mnist.test.images,np.random.permutation(mnist.test.images.shape[0]),axis=0,out=mnist.test.images)\n\nD=mnist.train.images.shape[1]\n\nx_train = mnist.train.images#[0:2000,:]\nx_test = mnist.test.images#[0:2000,:]\ny_test =mnist.test.labels#[0:2000]\n\n# x_train2 = np.zeros((x_train.shape[0],100))\n# x_test2 = np.zeros((x_test.shape[0],100))\n#\n# for i in range(0, x_train.shape[0]):\n# x_train2[i,:]=np.resize(resize(np.resize(x_train[i],(28,28)), (10, 10)),(1,100))\n#\n# for i in range(0, x_test.shape[0]):\n# x_test2[i,:]=np.resize(resize(np.resize(x_test[i],(28,28)), (10, 10)),(1,100))\n#\n# x_train = x_train2\n# x_test = x_test2\n\n######################################################\nnp.random.seed(1234)\n\n#\n# vgmm = VariationalGaussianMixture(n_components=K)\n# vgmm.fit(x_train)\n#\n# test_ll[0,:] = np.repeat(np.sum(vgmm.logpdf(x_test)),10)\n# similarty[0,:] = np.repeat(metrics.adjusted_mutual_info_score(y_test,vgmm.classify(x_test)),10)\n# #print(test_ll[0, 0])\n# #print(similarty[0, 0])\n# print(np.sum([np.linalg.det(vgmm.W[k]) for k in range(i, K)]))\n# params = np.hstack([p.flatten() for p in vgmm.get_params()])\n######################################################\nX=x_train\na = np.array_split(X, int(X.shape[0] / 1000), axis=0)\nX_slide = a[0]\nXX_slide = np.multiply(X_slide[:, :, None], X_slide[:, None, :])\nXX_slide = XX_slide.reshape((XX_slide.shape[0], -1))\nXJoin_slide = np.concatenate((X_slide, XX_slide), axis=1)\n\nfrom sklearn import random_projection\n\ntransformer = random_projection.GaussianRandomProjection(n_components=X.shape[1])\n# transformer = random_projection.SparseRandomProjection(n_components=100)\nX_proyected = transformer.fit_transform(XJoin_slide)\nfor i in range(1, len(a)):\n X_slide = a[i]\n XX_slide = np.multiply(X_slide[:, :, None], X_slide[:, None, :])\n XX_slide = XX_slide.reshape((XX_slide.shape[0], -1))\n XJoin_slide = np.concatenate((X_slide, XX_slide), axis=1)\n X_proyected = np.append(X_proyected, transformer.transform(XJoin_slide), axis=0)\n\nprint(\"Proyection\")\n######################################################\nsamples = np.zeros(10)\n\nsamples = [int(x_train.shape[0]*(m+1)/1000) for m in range(0,10) ]\nsamples = np.array([25, 50, 100, 250, 500, 750, 1000])\n#samples = np.array([25, 50])\n\nclusterError = np.zeros(samples.shape[0])\n\ntest_ll = np.zeros((4,samples.shape[0]))\ntest_ll[0,:]=samples\n\nfrom slackclient import SlackClient\nsc = SlackClient('xoxp-157419655798-161969456967-412895555920-73008d912fdc1999899080b1d1bc44eb')\n\nfor m in range(0,samples.shape[0]):\n print(samples[m])\n M = samples[m]\n\n text = \"MoG\" + str(M)\n sc.api_call(\n \"chat.postMessage\",\n channel=\"@andresmasegosa\",\n text=text\n )\n\n np.random.seed(1234)\n vgmm_dr = VariationalGaussianMixture_DR(n_components=K)\n vgmm_dr.fit(x_train, n_clusters=M, cluster_method=\"SSProyection\", transformer=transformer, X_proyected=X_proyected)\n #print(np.sum([np.linalg.det(vgmm_dr.W[k]) for k in range(i,K)]))\n test_ll[1,m]=np.sum(vgmm_dr.logpdf(x_test))\n clusterError[m]=vgmm_dr.clusterError\n #similarty[1,m] = metrics.adjusted_rand_score(y_test, vgmm_dr.classify(x_test))\n print(test_ll[1,m])\n #print(similarty[1,m])\n #distance_ss[m]=np.linalg.norm(params-np.hstack([p.flatten() for p in vgmm_dr.get_params()]))\n np.random.seed(1234)\n vgmm_dr = VariationalGaussianMixture_DR(n_components=K)\n vgmm_dr.fit(x_train, n_clusters=M, cluster_method=\"NoSS\")\n #print(np.sum([np.linalg.det(vgmm_dr.W[k]) for k in range(i,K)]))\n test_ll[2,m]= np.sum(vgmm_dr.logpdf(x_test))\n #similarty[2,m] = metrics.adjusted_rand_score(y_test, vgmm_dr.classify(x_test))\n print(test_ll[2,m])\n #print(similarty[2,m])\n #distance_noss[m]=np.linalg.norm(params-np.hstack([p.flatten() for p in vgmm_dr.get_params()]))\n np.random.seed(1234)\n vgmm_dr = VariationalGaussianMixture_DR(n_components=K)\n vgmm_dr.fit(x_train, n_clusters=M, cluster_method=\"random\")\n #print(np.sum([np.linalg.det(vgmm_dr.W[k]) for k in range(i,K)]))\n test_ll[3,m]= np.sum(vgmm_dr.logpdf(x_test))\n #similarty[3,m] = metrics.adjusted_rand_score(y_test, vgmm_dr.classify(x_test))\n print(test_ll[3,m])\n #print(similarty[3,m])\n #distance_noss[m]=np.linalg.norm(params-np.hstack([p.flatten() for p in vgmm_dr.get_params()]))\n\n\nnp.savetxt('./figs/MoG_MINST_clustererror.txt', clusterError)\nnp.savetxt('./figs/MoG_MINST_data.txt',test_ll)\n\n# import matplotlib.pyplot as plt\n# clusterError = np.loadtxt('./datareduction/figs/MoG_MINST_clustererror.txt')\n# test_ll = np.loadtxt('./datareduction/figs/MoG_MINST_data.txt')\n#\n#\n# x = [m for m in range(0,test_ll.shape[1])]\n#\n# plt.figure(0)\n# plt.plot(x,test_ll[1,:], c='b', label='DR-SS')\n# plt.plot(x,test_ll[2,:], c='g', label='DR-NoSS')\n# plt.plot(x,test_ll[3,:], c='y', label='DR-Random')\n# plt.legend(loc='lower right', shadow=True)\n# plt.xticks(x, test_ll[0,:])\n# plt.ylim(-0.5e07, 0.2e07, 100)\n# plt.savefig(\"./datareduction/figs/MoG_MINST_LL.pdf\",bbox_inches='tight')\n#\n# plt.figure(1)\n# plt.plot(x,test_ll[1,:], c='b', label='Log-Likelihood')\n# plt.plot(x,clusterError, c='k', label='ClusterError')\n# plt.legend(loc='center right', shadow=True)\n# plt.xticks(x, test_ll[0,:])\n# plt.ylim(2e05, 2e06, 100)\n# plt.savefig(\"./datareduction/figs/MoG_MINST_ClusterError.pdf\",bbox_inches='tight')\n# plt.show()\n#\n#\n# from tabulate import tabulate\n# print(tabulate(test_ll, tablefmt=\"latex\", floatfmt=\".2f\"))\n# print(tabulate(clusterError[None,:], tablefmt=\"latex\", floatfmt=\".2f\"))\n" ]
[ [ "numpy.diag", "numpy.allclose", "sklearn.cluster.MiniBatchKMeans", "numpy.sqrt", "numpy.linalg.inv", "numpy.random.choice", "numpy.eye", "numpy.trace", "numpy.concatenate", "numpy.copy", "numpy.cov", "numpy.linalg.eigh", "numpy.mean", "numpy.size", "numpy.repeat", "numpy.sum" ], [ "matplotlib.pyplot.legend", "numpy.random.seed", "matplotlib.pyplot.ylim", "matplotlib.pyplot.show", "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "tensorflow.examples.tutorials.mnist.input_data.read_data_sets", "numpy.random.normal", "numpy.random.permutation", "numpy.savetxt", "numpy.random.uniform", "matplotlib.pyplot.xticks", "numpy.array", "numpy.zeros", "numpy.loadtxt", "matplotlib.pyplot.figure" ], [ "matplotlib.pyplot.legend", "numpy.resize", "numpy.random.seed", "matplotlib.pyplot.ylim", "numpy.repeat", "matplotlib.pyplot.show", "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "tensorflow.examples.tutorials.mnist.input_data.read_data_sets", "numpy.random.permutation", "numpy.random.rand", "numpy.savetxt", "matplotlib.pyplot.xticks", "numpy.array", "numpy.zeros", "numpy.loadtxt", "matplotlib.pyplot.figure" ], [ "numpy.linspace", "sklearn.cluster.MiniBatchKMeans", "numpy.concatenate", "numpy.mean", "sklearn.datasets.fetch_20newsgroups", "numpy.arange", "numpy.stack", "sklearn.feature_extraction.text.CountVectorizer", "numpy.repeat", "tensorflow.examples.tutorials.mnist.input_data.read_data_sets", "numpy.zeros", "sklearn.feature_extraction.text.TfidfVectorizer", "numpy.multiply", "numpy.array", "sklearn.preprocessing.scale", "matplotlib.pyplot.boxplot", "matplotlib.pyplot.scatter", "numpy.random.seed", "sklearn.random_projection.GaussianRandomProjection", "numpy.random.normal", "numpy.random.permutation", "numpy.random.uniform", "sklearn.preprocessing.StandardScaler", "numpy.array_split" ], [ "numpy.multiply", "numpy.random.seed", "sklearn.random_projection.GaussianRandomProjection", "numpy.repeat", "numpy.concatenate", "numpy.random.permutation", "numpy.random.rand", "numpy.savetxt", "numpy.array", "tensorflow.examples.tutorials.mnist.input_data.read_data_sets", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
WERimagin/transformers
[ "cc7d14511c647f8147494df72f8b0575015e37ab", "cc7d14511c647f8147494df72f8b0575015e37ab", "cc7d14511c647f8147494df72f8b0575015e37ab", "cc7d14511c647f8147494df72f8b0575015e37ab", "cc7d14511c647f8147494df72f8b0575015e37ab", "cc7d14511c647f8147494df72f8b0575015e37ab" ]
[ "tests/test_data_collator.py", "examples/adversarial/utils_hans.py", "src/transformers/tokenization_deberta.py", "tests/test_benchmark_tf.py", "tests/test_modeling_tf_xlnet.py", "tests/test_tokenization_bert_generation.py" ]
[ "import unittest\n\nfrom transformers import AutoTokenizer, is_torch_available\nfrom transformers.testing_utils import require_torch, slow\n\n\nif is_torch_available():\n import torch\n\n from transformers import (\n DataCollatorForLanguageModeling,\n DataCollatorForNextSentencePrediction,\n DataCollatorForPermutationLanguageModeling,\n DataCollatorForSOP,\n GlueDataset,\n GlueDataTrainingArguments,\n LineByLineTextDataset,\n LineByLineWithSOPTextDataset,\n TextDataset,\n TextDatasetForNextSentencePrediction,\n default_data_collator,\n )\n\n\nPATH_SAMPLE_TEXT = \"./tests/fixtures/sample_text.txt\"\nPATH_SAMPLE_TEXT_DIR = \"./tests/fixtures/tests_samples/wiki_text\"\n\n\n@require_torch\nclass DataCollatorIntegrationTest(unittest.TestCase):\n def test_default_with_dict(self):\n features = [{\"label\": i, \"inputs\": [0, 1, 2, 3, 4, 5]} for i in range(8)]\n batch = default_data_collator(features)\n self.assertTrue(batch[\"labels\"].equal(torch.tensor(list(range(8)))))\n self.assertEqual(batch[\"labels\"].dtype, torch.long)\n self.assertEqual(batch[\"inputs\"].shape, torch.Size([8, 6]))\n\n # With label_ids\n features = [{\"label_ids\": [0, 1, 2], \"inputs\": [0, 1, 2, 3, 4, 5]} for i in range(8)]\n batch = default_data_collator(features)\n self.assertTrue(batch[\"labels\"].equal(torch.tensor([[0, 1, 2]] * 8)))\n self.assertEqual(batch[\"labels\"].dtype, torch.long)\n self.assertEqual(batch[\"inputs\"].shape, torch.Size([8, 6]))\n\n # Features can already be tensors\n features = [{\"label\": i, \"inputs\": torch.randint(10, [10])} for i in range(8)]\n batch = default_data_collator(features)\n self.assertTrue(batch[\"labels\"].equal(torch.tensor(list(range(8)))))\n self.assertEqual(batch[\"labels\"].dtype, torch.long)\n self.assertEqual(batch[\"inputs\"].shape, torch.Size([8, 10]))\n\n # Labels can already be tensors\n features = [{\"label\": torch.tensor(i), \"inputs\": torch.randint(10, [10])} for i in range(8)]\n batch = default_data_collator(features)\n self.assertEqual(batch[\"labels\"].dtype, torch.long)\n self.assertTrue(batch[\"labels\"].equal(torch.tensor(list(range(8)))))\n self.assertEqual(batch[\"labels\"].dtype, torch.long)\n self.assertEqual(batch[\"inputs\"].shape, torch.Size([8, 10]))\n\n def test_default_with_no_labels(self):\n features = [{\"label\": None, \"inputs\": [0, 1, 2, 3, 4, 5]} for i in range(8)]\n batch = default_data_collator(features)\n self.assertTrue(\"labels\" not in batch)\n self.assertEqual(batch[\"inputs\"].shape, torch.Size([8, 6]))\n\n # With label_ids\n features = [{\"label_ids\": None, \"inputs\": [0, 1, 2, 3, 4, 5]} for i in range(8)]\n batch = default_data_collator(features)\n self.assertTrue(\"labels\" not in batch)\n self.assertEqual(batch[\"inputs\"].shape, torch.Size([8, 6]))\n\n @slow\n def test_default_classification(self):\n MODEL_ID = \"bert-base-cased-finetuned-mrpc\"\n tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)\n data_args = GlueDataTrainingArguments(\n task_name=\"mrpc\", data_dir=\"./tests/fixtures/tests_samples/MRPC\", overwrite_cache=True\n )\n dataset = GlueDataset(data_args, tokenizer=tokenizer, mode=\"dev\")\n data_collator = default_data_collator\n batch = data_collator(dataset.features)\n self.assertEqual(batch[\"labels\"].dtype, torch.long)\n\n @slow\n def test_default_regression(self):\n MODEL_ID = \"distilroberta-base\"\n tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)\n data_args = GlueDataTrainingArguments(\n task_name=\"sts-b\", data_dir=\"./tests/fixtures/tests_samples/STS-B\", overwrite_cache=True\n )\n dataset = GlueDataset(data_args, tokenizer=tokenizer, mode=\"dev\")\n data_collator = default_data_collator\n batch = data_collator(dataset.features)\n self.assertEqual(batch[\"labels\"].dtype, torch.float)\n\n @slow\n def test_lm_tokenizer_without_padding(self):\n tokenizer = AutoTokenizer.from_pretrained(\"gpt2\")\n data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False)\n # ^ causal lm\n\n dataset = LineByLineTextDataset(tokenizer, file_path=PATH_SAMPLE_TEXT, block_size=512)\n examples = [dataset[i] for i in range(len(dataset))]\n with self.assertRaises(ValueError):\n # Expect error due to padding token missing on gpt2:\n data_collator(examples)\n\n dataset = TextDataset(tokenizer, file_path=PATH_SAMPLE_TEXT, block_size=512, overwrite_cache=True)\n examples = [dataset[i] for i in range(len(dataset))]\n batch = data_collator(examples)\n self.assertIsInstance(batch, dict)\n self.assertEqual(batch[\"input_ids\"].shape, torch.Size((2, 512)))\n self.assertEqual(batch[\"labels\"].shape, torch.Size((2, 512)))\n\n @slow\n def test_lm_tokenizer_with_padding(self):\n tokenizer = AutoTokenizer.from_pretrained(\"distilroberta-base\")\n data_collator = DataCollatorForLanguageModeling(tokenizer)\n # ^ masked lm\n\n dataset = LineByLineTextDataset(tokenizer, file_path=PATH_SAMPLE_TEXT, block_size=512)\n examples = [dataset[i] for i in range(len(dataset))]\n batch = data_collator(examples)\n self.assertIsInstance(batch, dict)\n self.assertEqual(batch[\"input_ids\"].shape, torch.Size((31, 107)))\n self.assertEqual(batch[\"labels\"].shape, torch.Size((31, 107)))\n\n dataset = TextDataset(tokenizer, file_path=PATH_SAMPLE_TEXT, block_size=512, overwrite_cache=True)\n examples = [dataset[i] for i in range(len(dataset))]\n batch = data_collator(examples)\n self.assertIsInstance(batch, dict)\n self.assertEqual(batch[\"input_ids\"].shape, torch.Size((2, 512)))\n self.assertEqual(batch[\"labels\"].shape, torch.Size((2, 512)))\n\n @slow\n def test_plm(self):\n tokenizer = AutoTokenizer.from_pretrained(\"xlnet-base-cased\")\n data_collator = DataCollatorForPermutationLanguageModeling(tokenizer)\n # ^ permutation lm\n\n dataset = LineByLineTextDataset(tokenizer, file_path=PATH_SAMPLE_TEXT, block_size=512)\n examples = [dataset[i] for i in range(len(dataset))]\n batch = data_collator(examples)\n self.assertIsInstance(batch, dict)\n self.assertEqual(batch[\"input_ids\"].shape, torch.Size((31, 112)))\n self.assertEqual(batch[\"perm_mask\"].shape, torch.Size((31, 112, 112)))\n self.assertEqual(batch[\"target_mapping\"].shape, torch.Size((31, 112, 112)))\n self.assertEqual(batch[\"labels\"].shape, torch.Size((31, 112)))\n\n dataset = TextDataset(tokenizer, file_path=PATH_SAMPLE_TEXT, block_size=512, overwrite_cache=True)\n examples = [dataset[i] for i in range(len(dataset))]\n batch = data_collator(examples)\n self.assertIsInstance(batch, dict)\n self.assertEqual(batch[\"input_ids\"].shape, torch.Size((2, 512)))\n self.assertEqual(batch[\"perm_mask\"].shape, torch.Size((2, 512, 512)))\n self.assertEqual(batch[\"target_mapping\"].shape, torch.Size((2, 512, 512)))\n self.assertEqual(batch[\"labels\"].shape, torch.Size((2, 512)))\n\n example = [torch.randint(5, [5])]\n with self.assertRaises(ValueError):\n # Expect error due to odd sequence length\n data_collator(example)\n\n @slow\n def test_nsp(self):\n tokenizer = AutoTokenizer.from_pretrained(\"bert-base-cased\")\n data_collator = DataCollatorForNextSentencePrediction(tokenizer)\n\n dataset = TextDatasetForNextSentencePrediction(tokenizer, file_path=PATH_SAMPLE_TEXT, block_size=512)\n examples = [dataset[i] for i in range(len(dataset))]\n batch = data_collator(examples)\n self.assertIsInstance(batch, dict)\n\n # Since there are randomly generated false samples, the total number of samples is not fixed.\n total_samples = batch[\"input_ids\"].shape[0]\n self.assertEqual(batch[\"input_ids\"].shape, torch.Size((total_samples, 512)))\n self.assertEqual(batch[\"token_type_ids\"].shape, torch.Size((total_samples, 512)))\n self.assertEqual(batch[\"masked_lm_labels\"].shape, torch.Size((total_samples, 512)))\n self.assertEqual(batch[\"next_sentence_label\"].shape, torch.Size((total_samples,)))\n\n @slow\n def test_sop(self):\n tokenizer = AutoTokenizer.from_pretrained(\"albert-base-v2\")\n data_collator = DataCollatorForSOP(tokenizer)\n\n dataset = LineByLineWithSOPTextDataset(tokenizer, file_dir=PATH_SAMPLE_TEXT_DIR, block_size=512)\n examples = [dataset[i] for i in range(len(dataset))]\n batch = data_collator(examples)\n self.assertIsInstance(batch, dict)\n\n # Since there are randomly generated false samples, the total number of samples is not fixed.\n total_samples = batch[\"input_ids\"].shape[0]\n self.assertEqual(batch[\"input_ids\"].shape, torch.Size((total_samples, 512)))\n self.assertEqual(batch[\"token_type_ids\"].shape, torch.Size((total_samples, 512)))\n self.assertEqual(batch[\"labels\"].shape, torch.Size((total_samples, 512)))\n self.assertEqual(batch[\"sentence_order_label\"].shape, torch.Size((total_samples,)))\n", "# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.\n# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\nimport os\nfrom dataclasses import dataclass\nfrom typing import List, Optional, Union\n\nimport tqdm\n\nfrom filelock import FileLock\nfrom transformers import (\n BartTokenizer,\n BartTokenizerFast,\n DataProcessor,\n PreTrainedTokenizer,\n RobertaTokenizer,\n RobertaTokenizerFast,\n XLMRobertaTokenizer,\n is_tf_available,\n is_torch_available,\n)\n\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclass(frozen=True)\nclass InputExample:\n \"\"\"\n A single training/test example for simple sequence classification.\n\n Args:\n guid: Unique id for the example.\n text_a: string. The untokenized text of the first sequence. For single\n sequence tasks, only this sequence must be specified.\n text_b: (Optional) string. The untokenized text of the second sequence.\n Only must be specified for sequence pair tasks.\n label: (Optional) string. The label of the example. This should be\n specified for train and dev examples, but not for test examples.\n pairID: (Optional) string. Unique identifier for the pair of sentences.\n \"\"\"\n\n guid: str\n text_a: str\n text_b: Optional[str] = None\n label: Optional[str] = None\n pairID: Optional[str] = None\n\n\n@dataclass(frozen=True)\nclass InputFeatures:\n \"\"\"\n A single set of features of data.\n Property names are the same names as the corresponding inputs to a model.\n\n Args:\n input_ids: Indices of input sequence tokens in the vocabulary.\n attention_mask: Mask to avoid performing attention on padding token indices.\n Mask values selected in ``[0, 1]``:\n Usually ``1`` for tokens that are NOT MASKED, ``0`` for MASKED (padded) tokens.\n token_type_ids: (Optional) Segment token indices to indicate first and second\n portions of the inputs. Only some models use them.\n label: (Optional) Label corresponding to the input. Int for classification problems,\n float for regression problems.\n pairID: (Optional) Unique identifier for the pair of sentences.\n \"\"\"\n\n input_ids: List[int]\n attention_mask: Optional[List[int]] = None\n token_type_ids: Optional[List[int]] = None\n label: Optional[Union[int, float]] = None\n pairID: Optional[int] = None\n\n\nif is_torch_available():\n import torch\n from torch.utils.data.dataset import Dataset\n\n class HansDataset(Dataset):\n \"\"\"\n This will be superseded by a framework-agnostic approach\n soon.\n \"\"\"\n\n features: List[InputFeatures]\n\n def __init__(\n self,\n data_dir: str,\n tokenizer: PreTrainedTokenizer,\n task: str,\n max_seq_length: Optional[int] = None,\n overwrite_cache=False,\n evaluate: bool = False,\n ):\n processor = hans_processors[task]()\n\n cached_features_file = os.path.join(\n data_dir,\n \"cached_{}_{}_{}_{}\".format(\n \"dev\" if evaluate else \"train\",\n tokenizer.__class__.__name__,\n str(max_seq_length),\n task,\n ),\n )\n label_list = processor.get_labels()\n if tokenizer.__class__ in (\n RobertaTokenizer,\n RobertaTokenizerFast,\n XLMRobertaTokenizer,\n BartTokenizer,\n BartTokenizerFast,\n ):\n # HACK(label indices are swapped in RoBERTa pretrained model)\n label_list[1], label_list[2] = label_list[2], label_list[1]\n self.label_list = label_list\n\n # Make sure only the first process in distributed training processes the dataset,\n # and the others will use the cache.\n lock_path = cached_features_file + \".lock\"\n with FileLock(lock_path):\n\n if os.path.exists(cached_features_file) and not overwrite_cache:\n logger.info(f\"Loading features from cached file {cached_features_file}\")\n self.features = torch.load(cached_features_file)\n else:\n logger.info(f\"Creating features from dataset file at {data_dir}\")\n\n examples = (\n processor.get_dev_examples(data_dir) if evaluate else processor.get_train_examples(data_dir)\n )\n\n logger.info(\"Training examples: %s\", len(examples))\n self.features = hans_convert_examples_to_features(examples, label_list, max_seq_length, tokenizer)\n logger.info(\"Saving features into cached file %s\", cached_features_file)\n torch.save(self.features, cached_features_file)\n\n def __len__(self):\n return len(self.features)\n\n def __getitem__(self, i) -> InputFeatures:\n return self.features[i]\n\n def get_labels(self):\n return self.label_list\n\n\nif is_tf_available():\n import tensorflow as tf\n\n class TFHansDataset:\n \"\"\"\n This will be superseded by a framework-agnostic approach\n soon.\n \"\"\"\n\n features: List[InputFeatures]\n\n def __init__(\n self,\n data_dir: str,\n tokenizer: PreTrainedTokenizer,\n task: str,\n max_seq_length: Optional[int] = 128,\n overwrite_cache=False,\n evaluate: bool = False,\n ):\n processor = hans_processors[task]()\n label_list = processor.get_labels()\n if tokenizer.__class__ in (\n RobertaTokenizer,\n RobertaTokenizerFast,\n XLMRobertaTokenizer,\n BartTokenizer,\n BartTokenizerFast,\n ):\n # HACK(label indices are swapped in RoBERTa pretrained model)\n label_list[1], label_list[2] = label_list[2], label_list[1]\n self.label_list = label_list\n\n examples = processor.get_dev_examples(data_dir) if evaluate else processor.get_train_examples(data_dir)\n self.features = hans_convert_examples_to_features(examples, label_list, max_seq_length, tokenizer)\n\n def gen():\n for (ex_index, ex) in tqdm.tqdm(enumerate(self.features), desc=\"convert examples to features\"):\n if ex_index % 10000 == 0:\n logger.info(\"Writing example %d of %d\" % (ex_index, len(examples)))\n\n yield (\n {\n \"example_id\": 0,\n \"input_ids\": ex.input_ids,\n \"attention_mask\": ex.attention_mask,\n \"token_type_ids\": ex.token_type_ids,\n },\n ex.label,\n )\n\n self.dataset = tf.data.Dataset.from_generator(\n gen,\n (\n {\n \"example_id\": tf.int32,\n \"input_ids\": tf.int32,\n \"attention_mask\": tf.int32,\n \"token_type_ids\": tf.int32,\n },\n tf.int64,\n ),\n (\n {\n \"example_id\": tf.TensorShape([]),\n \"input_ids\": tf.TensorShape([None, None]),\n \"attention_mask\": tf.TensorShape([None, None]),\n \"token_type_ids\": tf.TensorShape([None, None]),\n },\n tf.TensorShape([]),\n ),\n )\n\n def get_dataset(self):\n return self.dataset\n\n def __len__(self):\n return len(self.features)\n\n def __getitem__(self, i) -> InputFeatures:\n return self.features[i]\n\n def get_labels(self):\n return self.label_list\n\n\nclass HansProcessor(DataProcessor):\n \"\"\"Processor for the HANS data set.\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(self._read_tsv(os.path.join(data_dir, \"heuristics_train_set.txt\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(self._read_tsv(os.path.join(data_dir, \"heuristics_evaluation_set.txt\")), \"dev\")\n\n def get_labels(self):\n \"\"\"See base class.\n Note that we follow the standard three labels for MNLI\n (see :class:`~transformers.data.processors.utils.MnliProcessor`)\n but the HANS evaluation groups `contradiction` and `neutral` into `non-entailment` (label 0) while\n `entailment` is label 1.\"\"\"\n return [\"contradiction\", \"entailment\", \"neutral\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n text_a = line[5]\n text_b = line[6]\n pairID = line[7][2:] if line[7].startswith(\"ex\") else line[7]\n label = line[0]\n examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label, pairID=pairID))\n return examples\n\n\ndef hans_convert_examples_to_features(\n examples: List[InputExample],\n label_list: List[str],\n max_length: int,\n tokenizer: PreTrainedTokenizer,\n):\n \"\"\"\n Loads a data file into a list of ``InputFeatures``\n\n Args:\n examples: List of ``InputExamples`` containing the examples.\n tokenizer: Instance of a tokenizer that will tokenize the examples.\n max_length: Maximum example length.\n label_list: List of labels. Can be obtained from the processor using the ``processor.get_labels()`` method.\n output_mode: String indicating the output mode. Either ``regression`` or ``classification``.\n\n Returns:\n A list of task-specific ``InputFeatures`` which can be fed to the model.\n\n \"\"\"\n\n label_map = {label: i for i, label in enumerate(label_list)}\n\n features = []\n for (ex_index, example) in tqdm.tqdm(enumerate(examples), desc=\"convert examples to features\"):\n if ex_index % 10000 == 0:\n logger.info(\"Writing example %d\" % (ex_index))\n\n inputs = tokenizer(\n example.text_a,\n example.text_b,\n add_special_tokens=True,\n max_length=max_length,\n padding=\"max_length\",\n truncation=True,\n return_overflowing_tokens=True,\n )\n\n label = label_map[example.label] if example.label in label_map else 0\n\n pairID = int(example.pairID)\n\n features.append(InputFeatures(**inputs, label=label, pairID=pairID))\n\n for i, example in enumerate(examples[:5]):\n logger.info(\"*** Example ***\")\n logger.info(f\"guid: {example}\")\n logger.info(f\"features: {features[i]}\")\n\n return features\n\n\nhans_tasks_num_labels = {\n \"hans\": 3,\n}\n\nhans_processors = {\n \"hans\": HansProcessor,\n}\n", "# coding=utf-8\n# Copyright 2020 Microsoft and the HuggingFace Inc. team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\" Tokenization class for model DeBERTa.\"\"\"\n\nimport logging\nimport os\nimport pathlib\nimport random\nimport unicodedata\nfrom functools import lru_cache\nfrom zipfile import ZipFile\n\nimport tqdm\n\nimport requests\n\nfrom .tokenization_utils import PreTrainedTokenizer\n\n\ntry:\n import regex as re\nexcept ImportError:\n raise ImportError(\"Please install regex with: pip install regex\")\n\n\nlogger = logging.getLogger(__name__)\n\nVOCAB_FILES_NAMES = {\"vocab_file\": \"bpe_encoder.bin\"}\n\nPRETRAINED_VOCAB_FILES_MAP = {\n \"vocab_file\": {\n \"microsoft/deberta-base\": \"https://s3.amazonaws.com/models.huggingface.co/bert/microsoft/deberta-base/bpe_encoder.bin\",\n \"microsoft/deberta-large\": \"https://s3.amazonaws.com/models.huggingface.co/bert/microsoft/deberta-large/bpe_encoder.bin\",\n }\n}\n\nPRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {\n \"microsoft/deberta-base\": 512,\n \"microsoft/deberta-large\": 512,\n}\n\nPRETRAINED_INIT_CONFIGURATION = {\n \"microsoft/deberta-base\": {\"do_lower_case\": False},\n \"microsoft/deberta-large\": {\"do_lower_case\": False},\n}\n\n__all__ = [\"DebertaTokenizer\"]\n\n\n@lru_cache()\ndef bytes_to_unicode():\n \"\"\"\n Returns list of utf-8 byte and a corresponding list of unicode strings.\n The reversible bpe codes work on unicode strings.\n This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.\n When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.\n This is a signficant percentage of your normal, say, 32K bpe vocab.\n To avoid that, we want lookup tables between utf-8 bytes and unicode strings.\n And avoids mapping to whitespace/control characters the bpe code barfs on.\n \"\"\"\n bs = (\n list(range(ord(\"!\"), ord(\"~\") + 1)) + list(range(ord(\"¡\"), ord(\"¬\") + 1)) + list(range(ord(\"®\"), ord(\"ÿ\") + 1))\n )\n cs = bs[:]\n n = 0\n for b in range(2 ** 8):\n if b not in bs:\n bs.append(b)\n cs.append(2 ** 8 + n)\n n += 1\n cs = [chr(n) for n in cs]\n return dict(zip(bs, cs))\n\n\ndef get_pairs(word):\n \"\"\"Return set of symbol pairs in a word.\n Word is represented as tuple of symbols (symbols being variable-length strings).\n \"\"\"\n pairs = set()\n prev_char = word[0]\n for char in word[1:]:\n pairs.add((prev_char, char))\n prev_char = char\n return pairs\n\n\nclass Encoder:\n def __init__(self, encoder, bpe_merges, errors=\"replace\"):\n self.encoder = encoder\n self.decoder = {v: k for k, v in self.encoder.items()}\n self.errors = errors # how to handle errors in decoding\n self.byte_encoder = bytes_to_unicode()\n self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}\n self.bpe_ranks = dict(zip([tuple(k) for k in bpe_merges], range(len(bpe_merges))))\n self.cache = {}\n self.random = random.Random(0)\n\n # Should haved added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions\n self.pat = re.compile(r\"\"\"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+\"\"\")\n\n def bpe(self, token):\n if token in self.cache:\n return self.cache[token]\n word = tuple(token)\n pairs = get_pairs(word)\n\n if not pairs:\n return token\n\n while True:\n bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float(\"inf\")))\n if bigram not in self.bpe_ranks:\n break\n first, second = bigram\n new_word = []\n i = 0\n while i < len(word):\n try:\n j = word.index(first, i)\n new_word.extend(word[i:j])\n i = j\n except Exception:\n new_word.extend(word[i:])\n break\n\n if word[i] == first and i < len(word) - 1 and word[i + 1] == second:\n new_word.append(first + second)\n i += 2\n else:\n new_word.append(word[i])\n i += 1\n new_word = tuple(new_word)\n word = new_word\n if len(word) == 1:\n break\n else:\n pairs = get_pairs(word)\n word = \" \".join(word)\n self.cache[token] = word\n return word\n\n def split_to_words(self, text):\n return list(re.findall(self.pat, text))\n\n def encode(self, text):\n bpe_tokens = []\n for token in self.split_to_words(text):\n token = \"\".join(self.byte_encoder[b] for b in token.encode(\"utf-8\"))\n bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(\" \"))\n return bpe_tokens\n\n def decode(self, tokens):\n text = \"\".join([self.decoder[token] for token in tokens])\n text = bytearray([self.byte_decoder[c] for c in text]).decode(\"utf-8\", errors=self.errors)\n return text\n\n\ndef get_encoder(encoder, vocab):\n return Encoder(\n encoder=encoder,\n bpe_merges=vocab,\n )\n\n\ndef _is_whitespace(char):\n \"\"\"Checks whether `chars` is a whitespace character.\"\"\"\n # \\t, \\n, and \\r are technically contorl characters but we treat them\n # as whitespace since they are generally considered as such.\n if char == \" \" or char == \"\\t\" or char == \"\\n\" or char == \"\\r\":\n return True\n cat = unicodedata.category(char)\n if cat == \"Zs\":\n return True\n return False\n\n\ndef _is_control(char):\n \"\"\"Checks whether `chars` is a control character.\"\"\"\n # These are technically control characters but we count them as whitespace\n # characters.\n if char == \"\\t\" or char == \"\\n\" or char == \"\\r\":\n return False\n cat = unicodedata.category(char)\n if cat.startswith(\"C\"):\n return True\n return False\n\n\ndef _is_punctuation(char):\n \"\"\"Checks whether `chars` is a punctuation character.\"\"\"\n cp = ord(char)\n # We treat all non-letter/number ASCII as punctuation.\n # Characters such as \"^\", \"$\", and \"`\" are not in the Unicode\n # Punctuation class but we treat them as punctuation anyways, for\n # consistency.\n if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126):\n return True\n cat = unicodedata.category(char)\n if cat.startswith(\"P\"):\n return True\n return False\n\n\ndef download_asset(name, tag=None, no_cache=False, cache_dir=None):\n _tag = tag\n if _tag is None:\n _tag = \"latest\"\n if not cache_dir:\n cache_dir = os.path.join(pathlib.Path.home(), f\".~DeBERTa/assets/{_tag}/\")\n os.makedirs(cache_dir, exist_ok=True)\n output = os.path.join(cache_dir, name)\n if os.path.exists(output) and (not no_cache):\n return output\n\n repo = \"https://api.github.com/repos/microsoft/DeBERTa/releases\"\n releases = requests.get(repo).json()\n if tag and tag != \"latest\":\n release = [r for r in releases if r[\"name\"].lower() == tag.lower()]\n if len(release) != 1:\n raise Exception(f\"{tag} can't be found in the repository.\")\n else:\n release = releases[0]\n asset = [s for s in release[\"assets\"] if s[\"name\"].lower() == name.lower()]\n if len(asset) != 1:\n raise Exception(f\"{name} can't be found in the release.\")\n url = asset[0][\"url\"]\n headers = {}\n headers[\"Accept\"] = \"application/octet-stream\"\n resp = requests.get(url, stream=True, headers=headers)\n if resp.status_code != 200:\n raise Exception(f\"Request for {url} return {resp.status_code}, {resp.text}\")\n try:\n with open(output, \"wb\") as fs:\n progress = tqdm(\n total=int(resp.headers[\"Content-Length\"]) if \"Content-Length\" in resp.headers else -1,\n ncols=80,\n desc=f\"Downloading {name}\",\n )\n for c in resp.iter_content(chunk_size=1024 * 1024):\n fs.write(c)\n progress.update(len(c))\n progress.close()\n except Exception:\n os.remove(output)\n raise\n\n return output\n\n\ndef load_vocab(name=None, tag=None, no_cache=False, cache_dir=None):\n import torch\n\n if name is None:\n name = \"bpe_encoder\"\n\n model_path = name\n if model_path and (not os.path.exists(model_path)) and not ((\"/\" in model_path) or (\"\\\\\" in model_path)):\n _tag = tag\n if _tag is None:\n _tag = \"latest\"\n if not cache_dir:\n cache_dir = os.path.join(pathlib.Path.home(), f\".~DeBERTa/assets/{_tag}/\")\n os.makedirs(cache_dir, exist_ok=True)\n out_dir = os.path.join(cache_dir, name)\n model_path = os.path.join(out_dir, \"bpe_encoder.bin\")\n if (not os.path.exists(model_path)) or no_cache:\n asset = download_asset(name + \".zip\", tag=tag, no_cache=no_cache, cache_dir=cache_dir)\n with ZipFile(asset, \"r\") as zipf:\n for zip_info in zipf.infolist():\n if zip_info.filename[-1] == \"/\":\n continue\n zip_info.filename = os.path.basename(zip_info.filename)\n zipf.extract(zip_info, out_dir)\n elif not model_path:\n return None, None\n\n encoder_state = torch.load(model_path)\n return encoder_state\n\n\nclass GPT2Tokenizer(object):\n \"\"\" A wrapper of GPT2 tokenizer with similar interface as BERT tokenizer\n\n Args:\n vocab_file (:obj:`str`, optional):\n The local path of vocabulary package or the release name of vocabulary in `DeBERTa GitHub releases <https://github.com/microsoft/DeBERTa/releases>`_, \\\n e.g. \"bpe_encoder\", default: `None`.\n\n If it's `None`, then it will download the vocabulary in the latest release from GitHub. The vocabulary file is a \\\n state dictionary with three items, \"dict_map\", \"vocab\", \"encoder\" which correspond to three files used in `RoBERTa`, i.e. `dict.txt`, `vocab.txt` and `encoder.json`. \\\n The difference between our wrapped GPT2 tokenizer and RoBERTa wrapped tokenizer are,\n\n - Special tokens, unlike `RoBERTa` which use `<s>`, `</s>` as the `start` token and `end` token of a sentence. We use `[CLS]` and `[SEP]` as the `start` and `end`\\\n token of input sentence which is the same as `BERT`.\n\n - We remapped the token ids in our dictionary with regarding to the new special tokens, `[PAD]` => 0, `[CLS]` => 1, `[SEP]` => 2, `[UNK]` => 3, `[MASK]` => 50264\n\n do_lower_case (:obj:`bool`, optional):\n Whether to convert inputs to lower case. **Not used in GPT2 tokenizer**.\n\n special_tokens (:obj:`list`, optional):\n List of special tokens to be added to the end of the vocabulary.\n\n\n \"\"\"\n\n def __init__(self, vocab_file=None, do_lower_case=True, special_tokens=None):\n self.pad_token = \"[PAD]\"\n self.sep_token = \"[SEP]\"\n self.unk_token = \"[UNK]\"\n self.cls_token = \"[CLS]\"\n\n self.symbols = []\n self.count = []\n self.indices = {}\n self.pad_token_id = self.add_symbol(self.pad_token)\n self.cls_token_id = self.add_symbol(self.cls_token)\n self.sep_token_id = self.add_symbol(self.sep_token)\n self.unk_token_id = self.add_symbol(self.unk_token)\n\n self.gpt2_encoder = load_vocab(vocab_file)\n self.bpe = get_encoder(self.gpt2_encoder[\"encoder\"], self.gpt2_encoder[\"vocab\"])\n for w, n in self.gpt2_encoder[\"dict_map\"]:\n self.add_symbol(w, n)\n\n self.mask_token = \"[MASK]\"\n self.mask_id = self.add_symbol(self.mask_token)\n self.special_tokens = [\"[MASK]\", \"[SEP]\", \"[PAD]\", \"[UNK]\", \"[CLS]\"]\n if special_tokens is not None:\n for t in special_tokens:\n self.add_special_token(t)\n\n self.vocab = self.indices\n self.ids_to_tokens = self.symbols\n\n def tokenize(self, text):\n \"\"\"Convert an input text to tokens.\n\n Args:\n text (:obj:`str`): input text to be tokenized.\n\n Returns:\n A list of byte tokens where each token represent the byte id in GPT2 byte dictionary\n\n Example::\n >>> tokenizer = GPT2Tokenizer()\n >>> text = \"Hello world!\"\n >>> tokens = tokenizer.tokenize(text)\n >>> print(tokens)\n ['15496', '995', '0']\n \"\"\"\n bpe = self._encode(text)\n\n return [t for t in bpe.split(\" \") if t]\n\n def convert_tokens_to_ids(self, tokens):\n \"\"\"Convert list of tokens to ids.\n Args:\n tokens (:obj:`list<str>`): list of tokens\n\n Returns:\n List of ids\n \"\"\"\n\n return [self.vocab[t] for t in tokens]\n\n def convert_ids_to_tokens(self, ids):\n \"\"\"Convert list of ids to tokens.\n Args:\n ids (:obj:`list<int>`): list of ids\n\n Returns:\n List of tokens\n \"\"\"\n\n tokens = []\n for i in ids:\n tokens.append(self.ids_to_tokens[i])\n return tokens\n\n def split_to_words(self, text):\n return self.bpe.split_to_words(text)\n\n def decode(self, tokens):\n \"\"\"Decode list of tokens to text strings.\n Args:\n tokens (:obj:`list<str>`): list of tokens.\n\n Returns:\n Text string corresponds to the input tokens.\n\n Example::\n >>> tokenizer = GPT2Tokenizer()\n >>> text = \"Hello world!\"\n >>> tokens = tokenizer.tokenize(text)\n >>> print(tokens)\n ['15496', '995', '0']\n >>> tokenizer.decode(tokens)\n 'Hello world!'\n \"\"\"\n return self.bpe.decode([int(t) for t in tokens if t not in self.special_tokens])\n\n def add_special_token(self, token):\n \"\"\"Adds a special token to the dictionary.\n Args:\n token (:obj:`str`): Tthe new token/word to be added to the vocabulary.\n\n Returns:\n The id of new token in the vocabulary.\n\n \"\"\"\n self.special_tokens.append(token)\n return self.add_symbol(token)\n\n def part_of_whole_word(self, token, is_bos=False):\n if is_bos:\n return True\n s = self._decode(token)\n if len(s) == 1 and (_is_whitespace(list(s)[0]) or _is_control(list(s)[0]) or _is_punctuation(list(s)[0])):\n return False\n\n return not s.startswith(\" \")\n\n def sym(self, id):\n return self.ids_to_tokens[id]\n\n def id(self, sym):\n return self.vocab[sym]\n\n def _encode(self, x: str) -> str:\n return \" \".join(map(str, self.bpe.encode(x)))\n\n def _decode(self, x: str) -> str:\n return self.bpe.decode(map(int, x.split()))\n\n def add_symbol(self, word, n=1):\n \"\"\"Adds a word to the dictionary.\n Args:\n word (:obj:`str`): Tthe new token/word to be added to the vocabulary.\n n (int, optional): The frequency of the word.\n\n Returns:\n The id of the new word.\n\n \"\"\"\n if word in self.indices:\n idx = self.indices[word]\n self.count[idx] = self.count[idx] + n\n return idx\n else:\n idx = len(self.symbols)\n self.indices[word] = idx\n self.symbols.append(word)\n self.count.append(n)\n return idx\n\n def save_pretrained(self, path: str):\n import torch\n\n torch.save(self.gpt2_encoder, path)\n\n\nclass DebertaTokenizer(PreTrainedTokenizer):\n r\"\"\"\n Constructs a DeBERTa tokenizer, which runs end-to-end tokenization: punctuation\n splitting + wordpiece\n\n Args:\n vocab_file (:obj:`str`):\n File containing the vocabulary.\n do_lower_case (:obj:`bool`, `optional`, defaults to :obj:`True`):\n Whether or not to lowercase the input when tokenizing.\n unk_token (:obj:`str`, `optional`, defaults to :obj:`\"[UNK]\"`):\n The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this\n token instead.\n sep_token (:obj:`str`, `optional`, defaults to :obj:`\"[SEP]\"`):\n The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences\n for sequence classification or for a text and a question for question answering.\n It is also used as the last token of a sequence built with special tokens.\n pad_token (:obj:`str`, `optional`, defaults to :obj:`\"[PAD]\"`):\n The token used for padding, for example when batching sequences of different lengths.\n cls_token (:obj:`str`, `optional`, defaults to :obj:`\"[CLS]\"`):\n The classifier token which is used when doing sequence classification (classification of the whole\n sequence instead of per-token classification). It is the first token of the sequence when built with\n special tokens.\n mask_token (:obj:`str`, `optional`, defaults to :obj:`\"[MASK]\"`):\n The token used for masking values. This is the token used when training this model with masked language\n modeling. This is the token which the model will try to predict.\n \"\"\"\n\n vocab_files_names = VOCAB_FILES_NAMES\n pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP\n pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION\n max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES\n\n def __init__(\n self,\n vocab_file,\n do_lower_case=False,\n unk_token=\"[UNK]\",\n sep_token=\"[SEP]\",\n pad_token=\"[PAD]\",\n cls_token=\"[CLS]\",\n mask_token=\"[MASK]\",\n **kwargs\n ):\n super().__init__(\n unk_token=unk_token,\n sep_token=sep_token,\n pad_token=pad_token,\n cls_token=cls_token,\n mask_token=mask_token,\n **kwargs,\n )\n\n if not os.path.isfile(vocab_file):\n raise ValueError(\n \"Can't find a vocabulary file at path '{}'. To load the vocabulary from a Google pretrained \"\n \"model use `tokenizer = XxxTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`\".format(vocab_file)\n )\n self.do_lower_case = do_lower_case\n self.gpt2_tokenizer = GPT2Tokenizer(vocab_file)\n\n @property\n def vocab_size(self):\n return len(self.vocab)\n\n @property\n def vocab(self):\n return self.gpt2_tokenizer.vocab\n\n def get_vocab(self):\n vocab = self.vocab.copy()\n vocab.update(self.get_added_vocab())\n return vocab\n\n def _tokenize(self, text):\n \"\"\"Take as input a string and return a list of strings (tokens) for words/sub-words\"\"\"\n if self.do_lower_case:\n text = text.lower()\n return self.gpt2_tokenizer.tokenize(text)\n\n def _convert_token_to_id(self, token):\n \"\"\" Converts a token (str) in an id using the vocab. \"\"\"\n return self.vocab.get(token, self.vocab.get(self.unk_token))\n\n def _convert_id_to_token(self, index):\n \"\"\"Converts an index (integer) in a token (str) using the vocab.\"\"\"\n return self.gpt2_tokenizer.sym(index) if index < self.vocab_size else self.unk_token\n\n def convert_tokens_to_string(self, tokens):\n \"\"\" Converts a sequence of tokens (string) in a single string. \"\"\"\n return self.gpt2_tokenizer.decode(tokens)\n\n def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):\n \"\"\"\n Build model inputs from a sequence or a pair of sequence for sequence classification tasks\n by concatenating and adding special tokens.\n A BERT sequence has the following format:\n\n - single sequence: [CLS] X [SEP]\n - pair of sequences: [CLS] A [SEP] B [SEP]\n\n Args:\n token_ids_0 (:obj:`List[int]`):\n List of IDs to which the special tokens will be added.\n token_ids_1 (:obj:`List[int]`, `optional`):\n Optional second list of IDs for sequence pairs.\n\n Returns:\n :obj:`List[int]`: List of `input IDs <../glossary.html#input-ids>`__ with the appropriate special tokens.\n \"\"\"\n\n if token_ids_1 is None:\n return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]\n cls = [self.cls_token_id]\n sep = [self.sep_token_id]\n return cls + token_ids_0 + sep + token_ids_1 + sep\n\n def get_special_tokens_mask(self, token_ids_0, token_ids_1=None, already_has_special_tokens=False):\n \"\"\"\n Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding\n special tokens using the tokenizer ``prepare_for_model`` or ``encode_plus`` methods.\n\n Args:\n token_ids_0: list of ids (must not contain special tokens)\n token_ids_1: Optional list of ids (must not contain special tokens), necessary when fetching sequence ids\n for sequence pairs\n already_has_special_tokens: (default False) Set to True if the token list is already formated with\n special tokens for the model\n\n Returns:\n A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.\n \"\"\"\n\n if already_has_special_tokens:\n if token_ids_1 is not None:\n raise ValueError(\n \"You should not supply a second sequence if the provided sequence of \"\n \"ids is already formated with special tokens for the model.\"\n )\n return list(\n map(\n lambda x: 1 if x in [self.sep_token_id, self.cls_token_id] else 0,\n token_ids_0,\n )\n )\n\n if token_ids_1 is not None:\n return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]\n return [1] + ([0] * len(token_ids_0)) + [1]\n\n def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None):\n \"\"\"\n Creates a mask from the two sequences passed to be used in a sequence-pair classification task.\n A BERT sequence pair mask has the following format:\n 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1\n | first sequence | second sequence\n\n if token_ids_1 is None, only returns the first portion of the mask (0's).\n ~\n Args:\n token_ids_0 (:obj:`List[int]`):\n List of IDs.\n token_ids_1 (:obj:`List[int]`, `optional`):\n Optional second list of IDs for sequence pairs.\n\n Returns:\n :obj:`List[int]`: List of `token type IDs <../glossary.html#token-type-ids>`_ according to the given\n sequence(s).\n \"\"\"\n sep = [self.sep_token_id]\n cls = [self.cls_token_id]\n if token_ids_1 is None:\n return len(cls + token_ids_0 + sep) * [0]\n return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]\n\n def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):\n add_prefix_space = kwargs.pop(\"add_prefix_space\", False)\n if is_split_into_words or add_prefix_space:\n text = \" \" + text\n return (text, kwargs)\n\n def save_vocabulary(self, vocab_path):\n \"\"\"Save the tokenizer vocabulary to a directory or file.\"\"\"\n if os.path.isdir(vocab_path):\n vocab_file = os.path.join(vocab_path, VOCAB_FILES_NAMES[\"vocab_file\"])\n else:\n vocab_file = vocab_path\n self.gpt2_tokenizer.save_pretrained(vocab_file)\n return (vocab_file,)\n", "import os\nimport tempfile\nimport unittest\nfrom pathlib import Path\n\nfrom transformers import AutoConfig, is_tf_available\nfrom transformers.testing_utils import require_tf\n\n\nif is_tf_available():\n import tensorflow as tf\n\n from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments\n\n\n@require_tf\nclass TFBenchmarkTest(unittest.TestCase):\n def check_results_dict_not_empty(self, results):\n for model_result in results.values():\n for batch_size, sequence_length in zip(model_result[\"bs\"], model_result[\"ss\"]):\n result = model_result[\"result\"][batch_size][sequence_length]\n self.assertIsNotNone(result)\n\n def test_inference_no_configs_eager(self):\n MODEL_ID = \"sshleifer/tiny-gpt2\"\n benchmark_args = TensorFlowBenchmarkArguments(\n models=[MODEL_ID],\n training=False,\n inference=True,\n sequence_lengths=[8],\n batch_sizes=[1],\n eager_mode=True,\n multi_process=False,\n )\n benchmark = TensorFlowBenchmark(benchmark_args)\n results = benchmark.run()\n self.check_results_dict_not_empty(results.time_inference_result)\n self.check_results_dict_not_empty(results.memory_inference_result)\n\n def test_inference_no_configs_only_pretrain(self):\n MODEL_ID = \"sshleifer/tiny-distilbert-base-uncased-finetuned-sst-2-english\"\n benchmark_args = TensorFlowBenchmarkArguments(\n models=[MODEL_ID],\n training=False,\n inference=True,\n sequence_lengths=[8],\n batch_sizes=[1],\n multi_process=False,\n only_pretrain_model=True,\n )\n benchmark = TensorFlowBenchmark(benchmark_args)\n results = benchmark.run()\n self.check_results_dict_not_empty(results.time_inference_result)\n self.check_results_dict_not_empty(results.memory_inference_result)\n\n def test_inference_no_configs_graph(self):\n MODEL_ID = \"sshleifer/tiny-gpt2\"\n benchmark_args = TensorFlowBenchmarkArguments(\n models=[MODEL_ID],\n training=False,\n inference=True,\n sequence_lengths=[8],\n batch_sizes=[1],\n multi_process=False,\n )\n benchmark = TensorFlowBenchmark(benchmark_args)\n results = benchmark.run()\n self.check_results_dict_not_empty(results.time_inference_result)\n self.check_results_dict_not_empty(results.memory_inference_result)\n\n def test_inference_with_configs_eager(self):\n MODEL_ID = \"sshleifer/tiny-gpt2\"\n config = AutoConfig.from_pretrained(MODEL_ID)\n benchmark_args = TensorFlowBenchmarkArguments(\n models=[MODEL_ID],\n training=False,\n inference=True,\n sequence_lengths=[8],\n batch_sizes=[1],\n eager_mode=True,\n multi_process=False,\n )\n benchmark = TensorFlowBenchmark(benchmark_args, [config])\n results = benchmark.run()\n self.check_results_dict_not_empty(results.time_inference_result)\n self.check_results_dict_not_empty(results.memory_inference_result)\n\n def test_inference_with_configs_graph(self):\n MODEL_ID = \"sshleifer/tiny-gpt2\"\n config = AutoConfig.from_pretrained(MODEL_ID)\n benchmark_args = TensorFlowBenchmarkArguments(\n models=[MODEL_ID],\n training=False,\n inference=True,\n sequence_lengths=[8],\n batch_sizes=[1],\n multi_process=False,\n )\n benchmark = TensorFlowBenchmark(benchmark_args, [config])\n results = benchmark.run()\n self.check_results_dict_not_empty(results.time_inference_result)\n self.check_results_dict_not_empty(results.memory_inference_result)\n\n def test_train_no_configs(self):\n MODEL_ID = \"sshleifer/tiny-gpt2\"\n benchmark_args = TensorFlowBenchmarkArguments(\n models=[MODEL_ID],\n training=True,\n inference=False,\n sequence_lengths=[8],\n batch_sizes=[1],\n multi_process=False,\n )\n benchmark = TensorFlowBenchmark(benchmark_args)\n results = benchmark.run()\n self.check_results_dict_not_empty(results.time_train_result)\n self.check_results_dict_not_empty(results.memory_train_result)\n\n def test_train_with_configs(self):\n MODEL_ID = \"sshleifer/tiny-gpt2\"\n config = AutoConfig.from_pretrained(MODEL_ID)\n benchmark_args = TensorFlowBenchmarkArguments(\n models=[MODEL_ID],\n training=True,\n inference=False,\n sequence_lengths=[8],\n batch_sizes=[1],\n multi_process=False,\n )\n benchmark = TensorFlowBenchmark(benchmark_args, [config])\n results = benchmark.run()\n self.check_results_dict_not_empty(results.time_train_result)\n self.check_results_dict_not_empty(results.memory_train_result)\n\n def test_inference_encoder_decoder_with_configs(self):\n MODEL_ID = \"patrickvonplaten/t5-tiny-random\"\n config = AutoConfig.from_pretrained(MODEL_ID)\n benchmark_args = TensorFlowBenchmarkArguments(\n models=[MODEL_ID],\n training=False,\n inference=True,\n sequence_lengths=[8],\n batch_sizes=[1],\n multi_process=False,\n )\n benchmark = TensorFlowBenchmark(benchmark_args, configs=[config])\n results = benchmark.run()\n self.check_results_dict_not_empty(results.time_inference_result)\n self.check_results_dict_not_empty(results.memory_inference_result)\n\n @unittest.skipIf(is_tf_available() and len(tf.config.list_physical_devices(\"GPU\")) == 0, \"Cannot do xla on CPU.\")\n def test_inference_no_configs_xla(self):\n MODEL_ID = \"sshleifer/tiny-gpt2\"\n benchmark_args = TensorFlowBenchmarkArguments(\n models=[MODEL_ID],\n training=False,\n inference=True,\n sequence_lengths=[8],\n batch_sizes=[1],\n use_xla=True,\n multi_process=False,\n )\n benchmark = TensorFlowBenchmark(benchmark_args)\n results = benchmark.run()\n self.check_results_dict_not_empty(results.time_inference_result)\n self.check_results_dict_not_empty(results.memory_inference_result)\n\n def test_save_csv_files(self):\n MODEL_ID = \"sshleifer/tiny-gpt2\"\n with tempfile.TemporaryDirectory() as tmp_dir:\n benchmark_args = TensorFlowBenchmarkArguments(\n models=[MODEL_ID],\n inference=True,\n save_to_csv=True,\n sequence_lengths=[8],\n batch_sizes=[1],\n inference_time_csv_file=os.path.join(tmp_dir, \"inf_time.csv\"),\n inference_memory_csv_file=os.path.join(tmp_dir, \"inf_mem.csv\"),\n env_info_csv_file=os.path.join(tmp_dir, \"env.csv\"),\n multi_process=False,\n )\n benchmark = TensorFlowBenchmark(benchmark_args)\n benchmark.run()\n self.assertTrue(Path(os.path.join(tmp_dir, \"inf_time.csv\")).exists())\n self.assertTrue(Path(os.path.join(tmp_dir, \"inf_mem.csv\")).exists())\n self.assertTrue(Path(os.path.join(tmp_dir, \"env.csv\")).exists())\n\n def test_trace_memory(self):\n MODEL_ID = \"sshleifer/tiny-gpt2\"\n\n def _check_summary_is_not_empty(summary):\n self.assertTrue(hasattr(summary, \"sequential\"))\n self.assertTrue(hasattr(summary, \"cumulative\"))\n self.assertTrue(hasattr(summary, \"current\"))\n self.assertTrue(hasattr(summary, \"total\"))\n\n with tempfile.TemporaryDirectory() as tmp_dir:\n benchmark_args = TensorFlowBenchmarkArguments(\n models=[MODEL_ID],\n inference=True,\n sequence_lengths=[8],\n batch_sizes=[1],\n log_filename=os.path.join(tmp_dir, \"log.txt\"),\n log_print=True,\n trace_memory_line_by_line=True,\n eager_mode=True,\n multi_process=False,\n )\n benchmark = TensorFlowBenchmark(benchmark_args)\n result = benchmark.run()\n _check_summary_is_not_empty(result.inference_summary)\n self.assertTrue(Path(os.path.join(tmp_dir, \"log.txt\")).exists())\n", "# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport random\nimport unittest\n\nfrom transformers import XLNetConfig, is_tf_available\nfrom transformers.testing_utils import require_tf, slow\n\nfrom .test_configuration_common import ConfigTester\nfrom .test_modeling_tf_common import TFModelTesterMixin, ids_tensor\n\n\nif is_tf_available():\n import tensorflow as tf\n\n from transformers.modeling_tf_xlnet import (\n TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST,\n TFXLNetForMultipleChoice,\n TFXLNetForQuestionAnsweringSimple,\n TFXLNetForSequenceClassification,\n TFXLNetForTokenClassification,\n TFXLNetLMHeadModel,\n TFXLNetModel,\n )\n\n\nclass TFXLNetModelTester:\n def __init__(\n self,\n parent,\n ):\n self.parent = parent\n self.batch_size = 13\n self.seq_length = 7\n self.mem_len = 10\n # self.key_len = seq_length + mem_len\n self.clamp_len = -1\n self.reuse_len = 15\n self.is_training = True\n self.use_labels = True\n self.vocab_size = 99\n self.cutoffs = [10, 50, 80]\n self.hidden_size = 32\n self.num_attention_heads = 4\n self.d_inner = 128\n self.num_hidden_layers = 5\n self.type_sequence_label_size = 2\n self.untie_r = True\n self.bi_data = False\n self.same_length = False\n self.initializer_range = 0.05\n self.seed = 1\n self.type_vocab_size = 2\n self.bos_token_id = 1\n self.eos_token_id = 2\n self.pad_token_id = 5\n self.num_choices = 4\n\n def prepare_config_and_inputs(self):\n input_ids_1 = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)\n input_ids_2 = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)\n segment_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)\n input_mask = ids_tensor([self.batch_size, self.seq_length], 2, dtype=tf.float32)\n\n input_ids_q = ids_tensor([self.batch_size, self.seq_length + 1], self.vocab_size)\n perm_mask = tf.zeros((self.batch_size, self.seq_length + 1, self.seq_length), dtype=tf.float32)\n perm_mask_last = tf.ones((self.batch_size, self.seq_length + 1, 1), dtype=tf.float32)\n perm_mask = tf.concat([perm_mask, perm_mask_last], axis=-1)\n # perm_mask[:, :, -1] = 1.0 # Previous tokens don't see last token\n target_mapping = tf.zeros((self.batch_size, 1, self.seq_length), dtype=tf.float32)\n target_mapping_last = tf.ones((self.batch_size, 1, 1), dtype=tf.float32)\n target_mapping = tf.concat([target_mapping, target_mapping_last], axis=-1)\n # target_mapping[:, 0, -1] = 1.0 # predict last token\n\n sequence_labels = None\n lm_labels = None\n is_impossible_labels = None\n if self.use_labels:\n lm_labels = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)\n sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)\n is_impossible_labels = ids_tensor([self.batch_size], 2, dtype=tf.float32)\n\n config = XLNetConfig(\n vocab_size=self.vocab_size,\n d_model=self.hidden_size,\n n_head=self.num_attention_heads,\n d_inner=self.d_inner,\n n_layer=self.num_hidden_layers,\n untie_r=self.untie_r,\n mem_len=self.mem_len,\n clamp_len=self.clamp_len,\n same_length=self.same_length,\n reuse_len=self.reuse_len,\n bi_data=self.bi_data,\n initializer_range=self.initializer_range,\n num_labels=self.type_sequence_label_size,\n bos_token_id=self.bos_token_id,\n pad_token_id=self.pad_token_id,\n eos_token_id=self.eos_token_id,\n return_dict=True,\n )\n\n return (\n config,\n input_ids_1,\n input_ids_2,\n input_ids_q,\n perm_mask,\n input_mask,\n target_mapping,\n segment_ids,\n lm_labels,\n sequence_labels,\n is_impossible_labels,\n )\n\n def set_seed(self):\n random.seed(self.seed)\n tf.random.set_seed(self.seed)\n\n def create_and_check_xlnet_base_model(\n self,\n config,\n input_ids_1,\n input_ids_2,\n input_ids_q,\n perm_mask,\n input_mask,\n target_mapping,\n segment_ids,\n lm_labels,\n sequence_labels,\n is_impossible_labels,\n ):\n model = TFXLNetModel(config)\n\n inputs = {\"input_ids\": input_ids_1, \"input_mask\": input_mask, \"token_type_ids\": segment_ids}\n result = model(inputs)\n\n inputs = [input_ids_1, input_mask]\n result = model(inputs)\n\n config.mem_len = 0\n model = TFXLNetModel(config)\n no_mems_outputs = model(inputs)\n self.parent.assertEqual(len(no_mems_outputs), 1)\n\n self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))\n self.parent.assertListEqual(\n [mem.shape for mem in result.mems],\n [(self.seq_length, self.batch_size, self.hidden_size)] * self.num_hidden_layers,\n )\n\n def create_and_check_xlnet_lm_head(\n self,\n config,\n input_ids_1,\n input_ids_2,\n input_ids_q,\n perm_mask,\n input_mask,\n target_mapping,\n segment_ids,\n lm_labels,\n sequence_labels,\n is_impossible_labels,\n ):\n model = TFXLNetLMHeadModel(config)\n\n inputs_1 = {\"input_ids\": input_ids_1, \"token_type_ids\": segment_ids}\n all_logits_1, mems_1 = model(inputs_1).to_tuple()\n\n inputs_2 = {\"input_ids\": input_ids_2, \"mems\": mems_1, \"token_type_ids\": segment_ids}\n all_logits_2, mems_2 = model(inputs_2).to_tuple()\n\n inputs_3 = {\"input_ids\": input_ids_q, \"perm_mask\": perm_mask, \"target_mapping\": target_mapping}\n logits, _ = model(inputs_3).to_tuple()\n\n self.parent.assertEqual(all_logits_1.shape, (self.batch_size, self.seq_length, self.vocab_size))\n self.parent.assertListEqual(\n [mem.shape for mem in mems_1],\n [(self.seq_length, self.batch_size, self.hidden_size)] * self.num_hidden_layers,\n )\n self.parent.assertEqual(all_logits_2.shape, (self.batch_size, self.seq_length, self.vocab_size))\n self.parent.assertListEqual(\n [mem.shape for mem in mems_2],\n [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers,\n )\n\n def create_and_check_xlnet_qa(\n self,\n config,\n input_ids_1,\n input_ids_2,\n input_ids_q,\n perm_mask,\n input_mask,\n target_mapping,\n segment_ids,\n lm_labels,\n sequence_labels,\n is_impossible_labels,\n ):\n model = TFXLNetForQuestionAnsweringSimple(config)\n\n inputs = {\"input_ids\": input_ids_1, \"attention_mask\": input_mask, \"token_type_ids\": segment_ids}\n result = model(inputs)\n\n self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))\n self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))\n self.parent.assertListEqual(\n [mem.shape for mem in result.mems],\n [(self.seq_length, self.batch_size, self.hidden_size)] * self.num_hidden_layers,\n )\n\n def create_and_check_xlnet_sequence_classif(\n self,\n config,\n input_ids_1,\n input_ids_2,\n input_ids_q,\n perm_mask,\n input_mask,\n target_mapping,\n segment_ids,\n lm_labels,\n sequence_labels,\n is_impossible_labels,\n ):\n model = TFXLNetForSequenceClassification(config)\n\n result = model(input_ids_1)\n\n self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))\n self.parent.assertListEqual(\n [mem.shape for mem in result.mems],\n [(self.seq_length, self.batch_size, self.hidden_size)] * self.num_hidden_layers,\n )\n\n def create_and_check_xlnet_for_token_classification(\n self,\n config,\n input_ids_1,\n input_ids_2,\n input_ids_q,\n perm_mask,\n input_mask,\n target_mapping,\n segment_ids,\n lm_labels,\n sequence_labels,\n is_impossible_labels,\n ):\n config.num_labels = input_ids_1.shape[1]\n model = TFXLNetForTokenClassification(config)\n inputs = {\n \"input_ids\": input_ids_1,\n \"attention_mask\": input_mask,\n # 'token_type_ids': token_type_ids\n }\n result = model(inputs)\n self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, config.num_labels))\n self.parent.assertListEqual(\n [mem.shape for mem in result.mems],\n [(self.seq_length, self.batch_size, self.hidden_size)] * self.num_hidden_layers,\n )\n\n def create_and_check_xlnet_for_multiple_choice(\n self,\n config,\n input_ids_1,\n input_ids_2,\n input_ids_q,\n perm_mask,\n input_mask,\n target_mapping,\n segment_ids,\n lm_labels,\n sequence_labels,\n is_impossible_labels,\n ):\n config.num_choices = self.num_choices\n model = TFXLNetForMultipleChoice(config=config)\n multiple_choice_inputs_ids = tf.tile(tf.expand_dims(input_ids_1, 1), (1, self.num_choices, 1))\n multiple_choice_input_mask = tf.tile(tf.expand_dims(input_mask, 1), (1, self.num_choices, 1))\n multiple_choice_token_type_ids = tf.tile(tf.expand_dims(segment_ids, 1), (1, self.num_choices, 1))\n inputs = {\n \"input_ids\": multiple_choice_inputs_ids,\n \"attention_mask\": multiple_choice_input_mask,\n \"token_type_ids\": multiple_choice_token_type_ids,\n }\n result = model(inputs)\n\n self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))\n self.parent.assertListEqual(\n [mem.shape for mem in result.mems],\n [(self.seq_length, self.batch_size * self.num_choices, self.hidden_size)] * self.num_hidden_layers,\n )\n\n def prepare_config_and_inputs_for_common(self):\n config_and_inputs = self.prepare_config_and_inputs()\n (\n config,\n input_ids_1,\n input_ids_2,\n input_ids_q,\n perm_mask,\n input_mask,\n target_mapping,\n segment_ids,\n lm_labels,\n sequence_labels,\n is_impossible_labels,\n ) = config_and_inputs\n inputs_dict = {\"input_ids\": input_ids_1}\n return config, inputs_dict\n\n\n@require_tf\nclass TFXLNetModelTest(TFModelTesterMixin, unittest.TestCase):\n\n all_model_classes = (\n (\n TFXLNetModel,\n TFXLNetLMHeadModel,\n TFXLNetForSequenceClassification,\n TFXLNetForTokenClassification,\n TFXLNetForQuestionAnsweringSimple,\n TFXLNetForMultipleChoice,\n )\n if is_tf_available()\n else ()\n )\n all_generative_model_classes = (\n (TFXLNetLMHeadModel,) if is_tf_available() else ()\n ) # TODO (PVP): Check other models whether language generation is also applicable\n\n def setUp(self):\n self.model_tester = TFXLNetModelTester(self)\n self.config_tester = ConfigTester(self, config_class=XLNetConfig, d_inner=37)\n\n def test_config(self):\n self.config_tester.run_common_tests()\n\n def test_xlnet_base_model(self):\n self.model_tester.set_seed()\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_xlnet_base_model(*config_and_inputs)\n\n def test_xlnet_lm_head(self):\n self.model_tester.set_seed()\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_xlnet_lm_head(*config_and_inputs)\n\n def test_xlnet_sequence_classif(self):\n self.model_tester.set_seed()\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_xlnet_sequence_classif(*config_and_inputs)\n\n def test_xlnet_token_classification(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_xlnet_for_token_classification(*config_and_inputs)\n\n def test_xlnet_qa(self):\n self.model_tester.set_seed()\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_xlnet_qa(*config_and_inputs)\n\n def test_xlnet_for_multiple_choice(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_xlnet_for_multiple_choice(*config_and_inputs)\n\n @slow\n def test_model_from_pretrained(self):\n for model_name in TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:\n model = TFXLNetModel.from_pretrained(model_name)\n self.assertIsNotNone(model)\n\n\n@require_tf\nclass TFXLNetModelLanguageGenerationTest(unittest.TestCase):\n @slow\n def test_lm_generate_xlnet_base_cased(self):\n model = TFXLNetLMHeadModel.from_pretrained(\"xlnet-base-cased\")\n input_ids = tf.convert_to_tensor(\n [\n [\n 67,\n 2840,\n 19,\n 18,\n 1484,\n 20,\n 965,\n 29077,\n 8719,\n 1273,\n 21,\n 45,\n 273,\n 17,\n 10,\n 15048,\n 28,\n 27511,\n 21,\n 4185,\n 11,\n 41,\n 2444,\n 9,\n 32,\n 1025,\n 20,\n 8719,\n 26,\n 23,\n 673,\n 966,\n 19,\n 29077,\n 20643,\n 27511,\n 20822,\n 20643,\n 19,\n 17,\n 6616,\n 17511,\n 18,\n 8978,\n 20,\n 18,\n 777,\n 9,\n 19233,\n 1527,\n 17669,\n 19,\n 24,\n 673,\n 17,\n 28756,\n 150,\n 12943,\n 4354,\n 153,\n 27,\n 442,\n 37,\n 45,\n 668,\n 21,\n 24,\n 256,\n 20,\n 416,\n 22,\n 2771,\n 4901,\n 9,\n 12943,\n 4354,\n 153,\n 51,\n 24,\n 3004,\n 21,\n 28142,\n 23,\n 65,\n 20,\n 18,\n 416,\n 34,\n 24,\n 2958,\n 22947,\n 9,\n 1177,\n 45,\n 668,\n 3097,\n 13768,\n 23,\n 103,\n 28,\n 441,\n 148,\n 48,\n 20522,\n 19,\n 12943,\n 4354,\n 153,\n 12860,\n 34,\n 18,\n 326,\n 27,\n 17492,\n 684,\n 21,\n 6709,\n 9,\n 8585,\n 123,\n 266,\n 19,\n 12943,\n 4354,\n 153,\n 6872,\n 24,\n 3004,\n 20,\n 18,\n 9225,\n 2198,\n 19,\n 12717,\n 103,\n 22,\n 401,\n 24,\n 6348,\n 9,\n 12943,\n 4354,\n 153,\n 1068,\n 2768,\n 2286,\n 19,\n 33,\n 104,\n 19,\n 176,\n 24,\n 9313,\n 19,\n 20086,\n 28,\n 45,\n 10292,\n 9,\n 4,\n 3,\n ]\n ],\n dtype=tf.int32,\n )\n # In 1991, the remains of Russian Tsar Nicholas II and his family\n # (except for Alexei and Maria) are discovered.\n # The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the\n # remainder of the story. 1883 Western Siberia,\n # a young Grigori Rasputin is asked by his father and a group of men to perform magic.\n # Rasputin has a vision and denounces one of the men as a horse thief. Although his\n # father initially slaps him for making such an accusation, Rasputin watches as the\n # man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n # the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,\n # with people, even a bishop, begging for his blessing. \"\"\"\n\n expected_output_ids = [\n 67,\n 2840,\n 19,\n 18,\n 1484,\n 20,\n 965,\n 29077,\n 8719,\n 1273,\n 21,\n 45,\n 273,\n 17,\n 10,\n 15048,\n 28,\n 27511,\n 21,\n 4185,\n 11,\n 41,\n 2444,\n 9,\n 32,\n 1025,\n 20,\n 8719,\n 26,\n 23,\n 673,\n 966,\n 19,\n 29077,\n 20643,\n 27511,\n 20822,\n 20643,\n 19,\n 17,\n 6616,\n 17511,\n 18,\n 8978,\n 20,\n 18,\n 777,\n 9,\n 19233,\n 1527,\n 17669,\n 19,\n 24,\n 673,\n 17,\n 28756,\n 150,\n 12943,\n 4354,\n 153,\n 27,\n 442,\n 37,\n 45,\n 668,\n 21,\n 24,\n 256,\n 20,\n 416,\n 22,\n 2771,\n 4901,\n 9,\n 12943,\n 4354,\n 153,\n 51,\n 24,\n 3004,\n 21,\n 28142,\n 23,\n 65,\n 20,\n 18,\n 416,\n 34,\n 24,\n 2958,\n 22947,\n 9,\n 1177,\n 45,\n 668,\n 3097,\n 13768,\n 23,\n 103,\n 28,\n 441,\n 148,\n 48,\n 20522,\n 19,\n 12943,\n 4354,\n 153,\n 12860,\n 34,\n 18,\n 326,\n 27,\n 17492,\n 684,\n 21,\n 6709,\n 9,\n 8585,\n 123,\n 266,\n 19,\n 12943,\n 4354,\n 153,\n 6872,\n 24,\n 3004,\n 20,\n 18,\n 9225,\n 2198,\n 19,\n 12717,\n 103,\n 22,\n 401,\n 24,\n 6348,\n 9,\n 12943,\n 4354,\n 153,\n 1068,\n 2768,\n 2286,\n 19,\n 33,\n 104,\n 19,\n 176,\n 24,\n 9313,\n 19,\n 20086,\n 28,\n 45,\n 10292,\n 9,\n 4,\n 3,\n 19,\n 12943,\n 4354,\n 153,\n 27,\n 442,\n 22,\n 2771,\n 4901,\n 9,\n 69,\n 27,\n 50,\n 551,\n 22,\n 2771,\n 4901,\n 19,\n 21,\n 45,\n 668,\n 21,\n 18,\n 416,\n 41,\n 1499,\n 22,\n 755,\n 18,\n 14285,\n 9,\n 12943,\n 4354,\n 153,\n 27,\n 1499,\n 22,\n 642,\n 22,\n ]\n # In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria)\n # are discovered. The voice of Nicholas's young son, Tsarevich Alexei Nikolaevich,\n # narrates the remainder of the story. 1883 Western Siberia, a young Grigori Rasputin\n # is asked by his father and a group of men to perform magic. Rasputin has a vision and\n # denounces one of the men as a horse thief. Although his father initially slaps\n # him for making such an accusation, Rasputin watches as the man is chased outside and beaten.\n # Twenty years later, Rasputin sees a vision of the Virgin Mary, prompting him to become a priest.\n # Rasputin quickly becomes famous, with people, even a bishop, begging for his blessing.\n # <sep><cls>, Rasputin is asked to perform magic.\n # He is not able to perform magic, and his father and\n # the men are forced to leave the monastery. Rasputin is forced to return to\n\n output_ids = model.generate(input_ids, max_length=200, do_sample=False)\n\n self.assertListEqual(output_ids[0].numpy().tolist(), expected_output_ids)\n", "# coding=utf-8\n# Copyright 2020 The Google AI Language Team Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport os\nimport unittest\n\nfrom transformers.file_utils import cached_property\nfrom transformers.testing_utils import require_torch, slow\nfrom transformers.tokenization_bert_generation import BertGenerationTokenizer\n\nfrom .test_tokenization_common import TokenizerTesterMixin\n\n\nSPIECE_UNDERLINE = \"▁\"\n\nSAMPLE_VOCAB = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"fixtures/test_sentencepiece.model\")\n\n\nclass BertGenerationTokenizationTest(TokenizerTesterMixin, unittest.TestCase):\n\n tokenizer_class = BertGenerationTokenizer\n\n def setUp(self):\n super().setUp()\n\n tokenizer = BertGenerationTokenizer(SAMPLE_VOCAB, keep_accents=True)\n tokenizer.save_pretrained(self.tmpdirname)\n\n def test_full_tokenizer(self):\n tokenizer = BertGenerationTokenizer(SAMPLE_VOCAB, keep_accents=True)\n\n tokens = tokenizer.tokenize(\"This is a test\")\n self.assertListEqual(tokens, [\"▁This\", \"▁is\", \"▁a\", \"▁t\", \"est\"])\n\n self.assertListEqual(\n tokenizer.convert_tokens_to_ids(tokens),\n [285, 46, 10, 170, 382],\n )\n\n tokens = tokenizer.tokenize(\"I was born in 92000, and this is falsé.\")\n self.assertListEqual(\n tokens,\n [\n SPIECE_UNDERLINE + \"I\",\n SPIECE_UNDERLINE + \"was\",\n SPIECE_UNDERLINE + \"b\",\n \"or\",\n \"n\",\n SPIECE_UNDERLINE + \"in\",\n SPIECE_UNDERLINE + \"\",\n \"9\",\n \"2\",\n \"0\",\n \"0\",\n \"0\",\n \",\",\n SPIECE_UNDERLINE + \"and\",\n SPIECE_UNDERLINE + \"this\",\n SPIECE_UNDERLINE + \"is\",\n SPIECE_UNDERLINE + \"f\",\n \"al\",\n \"s\",\n \"é\",\n \".\",\n ],\n )\n ids = tokenizer.convert_tokens_to_ids(tokens)\n self.assertListEqual(\n ids,\n [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4],\n )\n\n back_tokens = tokenizer.convert_ids_to_tokens(ids)\n self.assertListEqual(\n back_tokens,\n [\n SPIECE_UNDERLINE + \"I\",\n SPIECE_UNDERLINE + \"was\",\n SPIECE_UNDERLINE + \"b\",\n \"or\",\n \"n\",\n SPIECE_UNDERLINE + \"in\",\n SPIECE_UNDERLINE + \"\",\n \"<unk>\",\n \"2\",\n \"0\",\n \"0\",\n \"0\",\n \",\",\n SPIECE_UNDERLINE + \"and\",\n SPIECE_UNDERLINE + \"this\",\n SPIECE_UNDERLINE + \"is\",\n SPIECE_UNDERLINE + \"f\",\n \"al\",\n \"s\",\n \"<unk>\",\n \".\",\n ],\n )\n\n @cached_property\n def big_tokenizer(self):\n return BertGenerationTokenizer.from_pretrained(\"google/bert_for_seq_generation_L-24_bbc_encoder\")\n\n @slow\n def test_tokenization_base_easy_symbols(self):\n symbols = \"Hello World!\"\n original_tokenizer_encodings = [18536, 2260, 101]\n\n self.assertListEqual(original_tokenizer_encodings, self.big_tokenizer.encode(symbols))\n\n @slow\n def test_tokenization_base_hard_symbols(self):\n symbols = 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth'\n original_tokenizer_encodings = [\n 871,\n 419,\n 358,\n 946,\n 991,\n 2521,\n 452,\n 358,\n 1357,\n 387,\n 7751,\n 3536,\n 112,\n 985,\n 456,\n 126,\n 865,\n 938,\n 5400,\n 5734,\n 458,\n 1368,\n 467,\n 786,\n 2462,\n 5246,\n 1159,\n 633,\n 865,\n 4519,\n 457,\n 582,\n 852,\n 2557,\n 427,\n 916,\n 508,\n 405,\n 34324,\n 497,\n 391,\n 408,\n 11342,\n 1244,\n 385,\n 100,\n 938,\n 985,\n 456,\n 574,\n 362,\n 12597,\n 3200,\n 3129,\n 1172,\n ]\n\n self.assertListEqual(original_tokenizer_encodings, self.big_tokenizer.encode(symbols))\n\n @require_torch\n @slow\n def test_torch_encode_plus_sent_to_model(self):\n import torch\n\n from transformers import BertGenerationConfig, BertGenerationEncoder\n\n # Build sequence\n first_ten_tokens = list(self.big_tokenizer.get_vocab().keys())[:10]\n sequence = \" \".join(first_ten_tokens)\n encoded_sequence = self.big_tokenizer.encode_plus(sequence, return_tensors=\"pt\", return_token_type_ids=False)\n batch_encoded_sequence = self.big_tokenizer.batch_encode_plus(\n [sequence + \" \" + sequence], return_tensors=\"pt\", return_token_type_ids=False\n )\n\n config = BertGenerationConfig()\n model = BertGenerationEncoder(config)\n\n assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size\n\n with torch.no_grad():\n model(**encoded_sequence)\n model(**batch_encoded_sequence)\n" ]
[ [ "torch.Size", "torch.randint", "torch.tensor" ], [ "tensorflow.TensorShape", "torch.save", "torch.load" ], [ "torch.save", "torch.load" ], [ "tensorflow.config.list_physical_devices" ], [ "tensorflow.convert_to_tensor", "tensorflow.concat", "tensorflow.zeros", "tensorflow.ones", "tensorflow.expand_dims", "tensorflow.random.set_seed" ], [ "torch.no_grad" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lucko515/cnn-raccoon
[ "e1c46544372751d82cc0c0f9cb2218d881a21f70" ]
[ "examples/tensorflow_example.py" ]
[ "import tensorflow as tf\n\nmodel = tf.keras.models.Sequential([\n # YOUR CODE HERE\n tf.keras.layers.BatchNormalization(input_shape=(32, 32, 3)),\n tf.keras.layers.Conv2D(filters=64, kernel_size=(3, 3), activation=\"relu\"),\n tf.keras.layers.MaxPool2D(2, 2),\n tf.keras.layers.Conv2D(filters=64, kernel_size=(3, 3), activation=\"relu\"),\n tf.keras.layers.MaxPool2D(2, 2),\n tf.keras.layers.Conv2D(filters=256, kernel_size=(3, 3), activation=\"relu\"),\n tf.keras.layers.MaxPool2D(2, 2),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dropout(0.5),\n tf.keras.layers.Dense(units=128, activation=\"relu\"),\n tf.keras.layers.Dense(10, activation=\"softmax\")\n ])\n\nmodel.compile(optimizer=\"adam\", loss=\"sparse_categorical_crossentropy\", metrics=[\"acc\"])\n\nfrom tensorflow.keras.datasets import cifar10\n\n(X_train, y_train), (X_test, y_test) = cifar10.load_data()\n\nfrom cnn_raccoon import inspector\ninspector(model=model, images=X_train[:10], number_of_classes=10, engine=\"keras\")\n" ]
[ [ "tensorflow.keras.layers.Dense", "tensorflow.keras.layers.Conv2D", "tensorflow.keras.layers.MaxPool2D", "tensorflow.keras.datasets.cifar10.load_data", "tensorflow.keras.layers.BatchNormalization", "tensorflow.keras.layers.Dropout", "tensorflow.keras.layers.Flatten" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] } ]
krystophny/chaospy
[ "18ff6c4fc56c632825e53fb24e17de51a7febd7d", "18ff6c4fc56c632825e53fb24e17de51a7febd7d", "18ff6c4fc56c632825e53fb24e17de51a7febd7d", "18ff6c4fc56c632825e53fb24e17de51a7febd7d", "18ff6c4fc56c632825e53fb24e17de51a7febd7d", "18ff6c4fc56c632825e53fb24e17de51a7febd7d", "18ff6c4fc56c632825e53fb24e17de51a7febd7d", "18ff6c4fc56c632825e53fb24e17de51a7febd7d" ]
[ "chaospy/distributions/collection/f.py", "chaospy/distributions/operators/negative.py", "chaospy/distributions/collection/laplace.py", "chaospy/bertran/indices.py", "chaospy/distributions/collection/alpha.py", "chaospy/distributions/operators/arccos.py", "chaospy/quadrature/gauss_legendre.py", "chaospy/chol/bastos_ohagen.py" ]
[ "\"\"\"(Non-central) F distribution.\"\"\"\nimport numpy\nfrom scipy import special\n\nfrom ..baseclass import Dist\nfrom ..operators.addition import Add\n\n\nclass f(Dist):\n \"\"\"F distribution.\"\"\"\n\n def __init__(self, dfn, dfd, nc):\n Dist.__init__(self, dfn=dfn, dfd=dfd, nc=nc)\n\n def _pdf(self, x, dfn, dfd, nc):\n n1, n2 = dfn, dfd\n term = -nc/2.+nc*n1*x/(2*(n2+n1*x)) + special.gammaln(n1/2.)+special.gammaln(1+n2/2.)\n term -= special.gammaln((n1+n2)/2.)\n Px = numpy.exp(term)\n Px *= n1**(n1/2.) * n2**(n2/2.) * x**(n1/2.-1)\n Px *= (n2+n1*x)**(-(n1+n2)/2.)\n Px *= special.assoc_laguerre(-nc*n1*x/(2.*(n2+n1*x)), n2/2., n1/2.-1)\n Px /= special.beta(n1/2., n2/2.)\n return Px\n\n def _cdf(self, x, dfn, dfd, nc):\n return special.ncfdtr(dfn, dfd, nc, x)\n\n def _ppf(self, q, dfn, dfd, nc):\n return special.ncfdtri(dfn, dfd, nc, q)\n\n def _bnd(self, x, dfn, dfd, nc):\n return 0.0, self._ppf(1-1e-10, dfn, dfd, nc)\n\n\nclass F(Add):\n \"\"\"\n (Non-central) F or Fisher-Snedecor distribution.\n\n Args:\n n (float, Dist) : Degres of freedom for numerator\n m (float, Dist) : Degres of freedom for denominator\n scale (float, Dist) : Scaling parameter\n shift (float, Dist) : Location parameter\n nc (float, Dist) : Non-centrality parameter\n\n Examples:\n >>> distribution = chaospy.F(3, 3, 2, 1, 1)\n >>> print(distribution)\n F(m=3, n=3, nc=1, scale=2, shift=1)\n >>> q = numpy.linspace(0, 1, 6)[1:-1]\n >>> print(numpy.around(distribution.inv(q), 4))\n [1.9336 2.9751 4.7028 8.8521]\n >>> print(numpy.around(distribution.fwd(distribution.inv(q)), 4))\n [0.2 0.4 0.6 0.8]\n >>> print(numpy.around(distribution.pdf(distribution.inv(q)), 4))\n [0.2277 0.1572 0.0837 0.027 ]\n >>> print(numpy.around(distribution.sample(4), 4))\n [ 5.4212 1.5739 25.7656 3.5586]\n >>> print(distribution.mom(1) > 10**8) # undefined\n True\n \"\"\"\n\n def __init__(self, n=1, m=1, scale=1, shift=0, nc=0):\n self._repr = {\"n\": n, \"m\": m, \"scale\": scale, \"shift\": shift, \"nc\": nc}\n Add.__init__(self, left=f(n, m, nc)*scale, right=shift)\n", "\"\"\"\nNegative of a distribution.\n\nExample usage\n-------------\n\nInvert sign of a distribution::\n\n >>> distribution = -chaospy.Uniform(0, 1)\n >>> print(distribution)\n Neg(Uniform(lower=0, upper=1))\n >>> print(numpy.around(distribution.sample(5), 4))\n [-0.3464 -0.885 -0.0497 -0.5178 -0.1275]\n >>> print(distribution.fwd([-0.3, -0.2, -0.1]))\n [0.7 0.8 0.9]\n >>> print(distribution.inv(distribution.fwd([-0.3, -0.2, -0.1])))\n [-0.3 -0.2 -0.1]\n >>> print(distribution.pdf([-0.3, -0.2, -0.1]))\n [1. 1. 1.]\n >>> print(numpy.around(distribution.mom([1, 2, 3]), 4))\n [-0.5 0.3333 -0.25 ]\n >>> print(numpy.around(distribution.ttr([1, 2, 3]), 4))\n [[-0.5 -0.5 -0.5 ]\n [ 0.0833 0.0667 0.0643]]\n\n\"\"\"\nimport numpy\nfrom ..baseclass import Dist\nfrom .. import evaluation\n\n\nclass Neg(Dist):\n \"\"\"Negative of a distribution.\"\"\"\n\n def __init__(self, dist):\n \"\"\"\n Constructor.\n\n Args:\n dist (Dist) : distribution.\n \"\"\"\n Dist.__init__(self, dist=dist)\n\n def _bnd(self, xloc, dist, cache):\n \"\"\"Distribution bounds.\"\"\"\n return -evaluation.evaluate_bound(dist, -xloc)[::-1]\n\n def _pdf(self, xloc, dist, cache):\n \"\"\"Probability density function.\"\"\"\n return evaluation.evaluate_density(dist, -xloc, cache=cache)\n\n def _cdf(self, xloc, dist, cache):\n \"\"\"Cumulative distribution function.\"\"\"\n return 1-evaluation.evaluate_forward(dist, -xloc, cache=cache)\n\n def _ppf(self, q, dist, cache):\n \"\"\"Point percentile function.\"\"\"\n return -evaluation.evaluate_inverse(dist, 1-q, cache=cache)\n\n def _mom(self, k, dist, cache):\n \"\"\"Statistical moments.\"\"\"\n return (-1)**numpy.sum(k)*evaluation.evaluate_moment(\n dist, k, cache=cache)\n\n def _ttr(self, k, dist, cache):\n \"\"\"Three terms recursion coefficients.\"\"\"\n a,b = evaluation.evaluate_recurrence_coefficients(dist, k)\n return -a, b\n\n def __str__(self):\n \"\"\"String representation.\"\"\"\n return self.__class__.__name__ + \"(\" + str(self.prm[\"dist\"]) + \")\"\n\n def _fwd_cache(self, cache):\n dist = evaluation.get_forward_cache(self.prm[\"dist\"], cache)\n if not isinstance(dist, Dist):\n return -dist\n return self\n\n def _inv_cache(self, cache):\n dist = evaluation.get_forward_cache(self.prm[\"dist\"], cache)\n if not isinstance(dist, Dist):\n return -dist\n return self\n\n\ndef neg(left):\n \"\"\"\n Negative of a distribution.\n\n Args:\n dist (Dist) : distribution.\n \"\"\"\n return Neg(left)\n", "\"\"\"Laplace Probability Distribution.\"\"\"\nimport numpy\nfrom scipy import special\n\nfrom ..baseclass import Dist\nfrom ..operators.addition import Add\n\n\n\nclass laplace(Dist):\n \"\"\"Laplace Probability Distribution.\"\"\"\n\n def __init__(self):\n Dist.__init__(self)\n\n def _pdf(self, x):\n return numpy.e**-numpy.abs(x)/2\n\n def _cdf(self, x):\n return (1+numpy.sign(x)*(1-numpy.e**-abs(x)))/2\n\n def _mom(self, k):\n return .5*special.factorial(k)*(1+(-1)**k)\n\n def _ppf(self, x):\n return numpy.where(x>.5, -numpy.log(2*(1-x)), numpy.log(2*x))\n\n def _bnd(self, x):\n return -32., 32.\n\n def _ttr(self, k):\n from ...quadrature import quad_fejer, discretized_stieltjes\n q1, w1 = quad_fejer(500, (-32, 0))\n q2, w2 = quad_fejer(500, (0, 32))\n q = numpy.concatenate([q1,q2], 1)\n w = numpy.concatenate([w1,w2])*self.pdf(q[0])\n\n coeffs, _, _ = discretized_stieltjes(k, q, w)\n return coeffs[:, 0, -1]\n\n\nclass Laplace(Add):\n R\"\"\"\n Laplace Probability Distribution\n\n Args:\n mu (float, Dist) : Mean of the distribution.\n scale (float, Dist) : Scaleing parameter. scale > 0.\n\n Examples:\n >>> distribution = chaospy.Laplace(2, 2)\n >>> q = numpy.linspace(0,1,6)[1:-1]\n >>> print(numpy.around(distribution.inv(q), 4))\n [0.1674 1.5537 2.4463 3.8326]\n >>> print(numpy.around(distribution.fwd(distribution.inv(q)), 4))\n [0.2 0.4 0.6 0.8]\n >>> print(numpy.around(distribution.pdf(distribution.inv(q)), 4))\n [0.1 0.2 0.2 0.1]\n >>> print(numpy.around(distribution.sample(4), 4))\n [ 2.734 -0.9392 6.6165 1.9275]\n >>> print(numpy.around(distribution.mom(1), 4))\n 2.0\n >>> print(numpy.around(distribution.ttr([1, 2, 3]), 4))\n [[ 2. 2. 2. ]\n [ 8. 39.9995 86.4011]]\n \"\"\"\n def __init__(self, mu=0, scale=1):\n self._repr = {\"mu\": mu, \"scale\": scale}\n Add.__init__(self, left=laplace()*scale, right=mu)\n", "\"\"\"Tools for creating multi-indices\"\"\"\nfrom __future__ import division\n\nimport itertools\nimport numpy\n\n\ndef bindex(start, stop=None, dim=1, sort=\"G\", cross_truncation=1.):\n \"\"\"\n Generator for creating multi-indices.\n\n Args:\n start (Union[int, numpy.ndarray]):\n The lower order of the indices. If array of int, counts as lower\n bound for each axis.\n stop (Union[int, numpy.ndarray, None]):\n the maximum shape included. If omitted: stop <- start; start <- 0\n If int is provided, set as largest total order. If array of int,\n set as upper bound for each axis.\n dim (int):\n The number of dimensions in the expansion\n sort (str):\n Criteria to sort the indices by.\n cross_truncation (float):\n Use hyperbolic cross truncation scheme to reduce the number of\n terms in expansion. Ignored if ``stop`` is a array.\n\n Returns:\n list:\n Order list of indices.\n\n Examples:\n >>> print(bindex(2, 3, 2).tolist())\n [[0, 2], [1, 1], [2, 0], [0, 3], [1, 2], [2, 1], [3, 0]]\n >>> print(bindex(2, [1, 3], 2, cross_truncation=0).tolist())\n [[0, 2], [1, 1], [0, 3], [1, 2], [1, 3]]\n >>> print(bindex([1, 2], [2, 3], 2, cross_truncation=0).tolist())\n [[1, 2], [1, 3], [2, 2], [2, 3]]\n >>> print(bindex(1, 3, 2, cross_truncation=0).tolist()) # doctest: +NORMALIZE_WHITESPACE\n [[0, 1], [1, 0], [0, 2], [1, 1], [2, 0], [0, 3], [1, 2], [2, 1], [3, 0],\n [1, 3], [2, 2], [3, 1], [2, 3], [3, 2], [3, 3]]\n >>> print(bindex(1, 3, 2, cross_truncation=1).tolist())\n [[0, 1], [1, 0], [0, 2], [1, 1], [2, 0], [0, 3], [1, 2], [2, 1], [3, 0]]\n >>> print(bindex(1, 3, 2, cross_truncation=1.5).tolist())\n [[0, 1], [1, 0], [0, 2], [1, 1], [2, 0], [0, 3], [3, 0]]\n >>> print(bindex(1, 3, 2, cross_truncation=2).tolist())\n [[0, 1], [1, 0], [0, 2], [2, 0], [0, 3], [3, 0]]\n >>> print(bindex(0, 1, 3).tolist())\n [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0]]\n >>> print(bindex([1, 1], 3, 2, cross_truncation=0).tolist())\n [[1, 1], [1, 2], [2, 1], [1, 3], [2, 2], [3, 1], [2, 3], [3, 2], [3, 3]]\n \"\"\"\n if stop is None:\n start, stop = 0, start\n start = numpy.array(start, dtype=int).flatten()\n stop = numpy.array(stop, dtype=int).flatten()\n sort = sort.upper()\n start[start < 0] = 0\n\n indices = _bindex(start, stop, dim, cross_truncation)\n if \"G\" in sort:\n indices = indices[numpy.lexsort([numpy.sum(indices, -1)])]\n\n if \"I\" in sort:\n indices = indices[::-1]\n\n if \"R\" in sort:\n indices = indices[:, ::-1]\n\n return indices\n\n\ndef _bindex(start, stop, dim=1, cross_truncation=1.):\n # At the beginning the current list of indices just ranges over the\n # last dimension.\n bound = stop.max()+1\n range_ = numpy.arange(bound, dtype=int)\n indices = range_[:, numpy.newaxis]\n\n for idx in range(dim-1):\n\n # Repeats the current set of indices.\n # e.g. [0,1,2] -> [0,1,2,0,1,2,...,0,1,2]\n indices = numpy.tile(indices, (bound, 1))\n\n # Stretches ranges over the new dimension.\n # e.g. [0,1,2] -> [0,0,...,0,1,1,...,1,2,2,...,2]\n front = range_.repeat(len(indices)//bound)[:, numpy.newaxis]\n\n # Puts them two together.\n indices = numpy.column_stack((front, indices))\n\n # Truncate at each iteration to ensure memory usage is low enough\n if stop.size == 1 and cross_truncation > 0:\n lhs = numpy.sum(indices**(1/cross_truncation), -1)\n rhs = numpy.max(stop, -1)**(1/cross_truncation)\n indices = indices[lhs <= rhs]\n else:\n indices = indices[numpy.all(indices <= stop, -1)]\n\n if start.size == 1:\n indices = indices[numpy.sum(indices, -1) >= start.item()]\n else:\n indices = indices[numpy.all(indices >= start, -1)]\n return indices.reshape(-1, dim)\n", "\"\"\"Alpha probability distribution.\"\"\"\nimport numpy\nfrom scipy import special\n\nfrom ..baseclass import Dist\nfrom ..operators.addition import Add\n\n\nclass alpha(Dist):\n \"\"\"Standard Alpha distribution.\"\"\"\n\n def __init__(self, a=1):\n Dist.__init__(self, a=a)\n\n def _cdf(self, x, a):\n return special.ndtr(a-1./x) / special.ndtr(a)\n\n def _ppf(self, q, a):\n return 1.0/(a-special.ndtri(q*special.ndtr(a)))\n\n def _pdf(self, x, a):\n return 1.0/(x**2)/special.ndtr(a)*numpy.e**(.5*(a-1.0/x)**2)/numpy.sqrt(2*numpy.pi)\n\n def _bnd(self, x, a):\n return 0, self._ppf(1-1e-10, a)\n\n\nclass Alpha(Add):\n \"\"\"\n Alpha distribution.\n\n Args:\n shape (float, Dist): Shape parameter\n scale (float, Dist): Scale Parameter\n shift (float, Dist): Location of lower threshold\n\n Examples:\n >>> distribution = chaospy.Alpha(2, 0.5, 4)\n >>> print(distribution)\n Alpha(scale=0.5, shape=2, shift=4)\n >>> q = numpy.linspace(0, 1, 7)[1:-1]\n >>> print(numpy.around(distribution.inv(q), 4))\n [4.1676 4.2039 4.2465 4.3104 4.4521]\n >>> print(numpy.around(distribution.fwd(distribution.inv(q)), 4))\n [0.1667 0.3333 0.5 0.6667 0.8333]\n >>> print(numpy.around(distribution.pdf(distribution.inv(q)), 4))\n [11.7723 5.4345 3.361 2.2848 1.4892]\n >>> print(numpy.around(distribution.sample(4), 4))\n [4.304 4.1556 4.9362 4.2413]\n \"\"\"\n\n def __init__(self, shape=1, scale=1, shift=0):\n self._repr = {\"shape\": shape, \"scale\": scale, \"shift\": shift}\n Add.__init__(self, left=alpha(shape)*scale, right=shift)\n", "\"\"\"Arc-Cosine.\"\"\"\nimport numpy\n\nfrom ..baseclass import Dist\nfrom .. import evaluation, approximation\n\n\nclass Arccos(Dist):\n \"\"\"\n Arc-Cosine.\n\n Args:\n dist (Dist): Distribution to perform transformation on.\n\n Example:\n >>> distribution = chaospy.Arccos(chaospy.Uniform(0, 1))\n >>> print(distribution)\n Arccos(Uniform(lower=0, upper=1))\n >>> q = numpy.linspace(0, 1, 6)[1:-1]\n >>> print(numpy.around(distribution.inv(q), 4))\n [0.6435 0.9273 1.1593 1.3694]\n >>> print(numpy.around(distribution.fwd(distribution.inv(q)), 4))\n [0.2 0.4 0.6 0.8]\n >>> print(numpy.around(distribution.pdf(distribution.inv(q)), 4))\n [0.6 0.8 0.9165 0.9798]\n >>> print(numpy.around(distribution.sample(4), 4))\n [1.2171 0.4843 1.5211 1.0265]\n >>> print(numpy.around(distribution.mom(1), 4))\n 1.0\n >>> print(numpy.around(distribution.ttr([0, 1, 2]), 4))\n [[1. 0.8406 0.8083]\n [1. 0.1416 0.1492]]\n \"\"\"\n\n def __init__(self, dist):\n assert isinstance(dist, Dist)\n assert numpy.all(dist.range() >= -1)\n assert numpy.all(dist.range() <= 1)\n Dist.__init__(self, dist=dist)\n\n def _pdf(self, x, dist, cache):\n return evaluation.evaluate_density(\n dist, numpy.cos(x), cache=cache)*numpy.sin(x)\n\n def _cdf(self, x, dist, cache):\n return 1-evaluation.evaluate_forward(dist, numpy.cos(x), cache=cache)\n\n def _ppf(self, q, dist, cache):\n return numpy.arccos(evaluation.evaluate_inverse(dist, 1-q, cache=cache))\n\n def _bnd(self, x, dist, cache):\n return numpy.arccos(evaluation.evaluate_bound(\n dist, numpy.cos(x), cache=cache))[::-1]\n\n def _mom(self, x, dist, cache):\n return approximation.approximate_moment(self, x)\n\n def __len__(self):\n return len(self.prm[\"dist\"])\n\n def __str__(self):\n return self.__class__.__name__ + \"(\" + str(self.prm[\"dist\"]) + \")\"\n\n def _fwd_cache(self, cache):\n dist = evaluation.get_forward_cache(self.prm[\"dist\"], cache)\n if not isinstance(dist, Dist):\n return numpy.arccos(dist)\n return self\n\n def _inv_cache(self, cache):\n dist = evaluation.get_forward_cache(self.prm[\"dist\"], cache)\n if not isinstance(dist, Dist):\n return numpy.cos(dist)\n return self\n", "r\"\"\"\nThe Gauss-Legendre quadrature rule is properly supported by in :ref:`gaussian`.\nHowever, as Gauss-Legendre is a special case where the weight function is\nconstant, it can in principle be used to integrate any weighting function. In\nother words, this is the same Gauss-Legendre integration rule, but only in the\ncontext of uniform distribution as weight function. Normalization of the\nweights will be used to achieve the general integration form.\n\nIt is also worth noting that this specific implementation of Gauss-Legendre is\nfaster to compute than the general version in :ref:`gaussian`.\n\nExample usage\n-------------\n\nThe first few orders::\n\n >>> distribution = chaospy.Uniform(0, 1)\n >>> for order in [0, 1, 2, 3]:\n ... abscissas, weights = chaospy.generate_quadrature(\n ... order, distribution, rule=\"gauss_legendre\")\n ... print(order, numpy.around(abscissas, 3),\n ... numpy.around(weights, 3))\n 0 [[0.5]] [1.]\n 1 [[0.211 0.789]] [0.5 0.5]\n 2 [[0.113 0.5 0.887]] [0.278 0.444 0.278]\n 3 [[0.069 0.33 0.67 0.931]] [0.174 0.326 0.326 0.174]\n\nUsing an alternative distribution::\n\n >>> distribution = chaospy.Beta(2, 4)\n >>> for order in [0, 1, 2, 3]:\n ... abscissas, weights = chaospy.generate_quadrature(\n ... order, distribution, rule=\"gauss_legendre\")\n ... print(order, numpy.around(abscissas, 3),\n ... numpy.around(weights, 3))\n 0 [[0.5]] [1.]\n 1 [[0.211 0.789]] [0.933 0.067]\n 2 [[0.113 0.5 0.887]] [0.437 0.556 0.007]\n 3 [[0.069 0.33 0.67 0.931]] [0.195 0.647 0.157 0.001]\n\nThe abscissas stays the same, but the weights are re-adjusted for the new\nweight function.\n\"\"\"\nfrom __future__ import print_function\n\nimport numpy\n\nfrom .recurrence import (\n construct_recurrence_coefficients, coefficients_to_quadrature)\nfrom .combine import combine_quadrature\n\n\ndef quad_gauss_legendre(\n order,\n domain=(0, 1),\n rule=\"fejer\",\n accuracy=100,\n recurrence_algorithm=\"\",\n):\n r\"\"\"\n Generate the quadrature nodes and weights in Gauss-Legendre quadrature.\n\n Note that this rule exists to allow for integrating functions with weight\n functions without actually adding the quadrature. Like:\n\n .. math:\n \\int_a^b p(x) f(x) dx \\approx \\sum_i p(X_i) f(X_i) W_i\n\n instead of the more traditional:\n\n .. math:\n \\int_a^b p(x) f(x) dx \\approx \\sum_i f(X_i) W_i\n\n To get the behavior where the weight function is taken into consideration,\n use :func:`~chaospy.quadrature.gaussian.quad_gaussian`.\n\n Args:\n order (int, numpy.ndarray):\n Quadrature order.\n domain (chaospy.distributions.baseclass.Dist, numpy.ndarray):\n Either distribution or bounding of interval to integrate over.\n rule (str):\n In the case of ``lanczos`` or ``stieltjes``, defines the\n proxy-integration scheme.\n accuracy (int):\n In the case ``rule`` is used, defines the quadrature order of the\n scheme used. In practice, must be at least as large as ``order``.\n recurrence_algorithm (str):\n Name of the algorithm used to generate abscissas and weights. If\n omitted, ``analytical`` will be tried first, and ``stieltjes`` used\n if that fails.\n\n Returns:\n (numpy.ndarray, numpy.ndarray):\n abscissas:\n The quadrature points for where to evaluate the model function\n with ``abscissas.shape == (len(dist), N)`` where ``N`` is the\n number of samples.\n weights:\n The quadrature weights with ``weights.shape == (N,)``.\n\n Example:\n >>> abscissas, weights = quad_gauss_legendre(3)\n >>> print(numpy.around(abscissas, 4))\n [[0.0694 0.33 0.67 0.9306]]\n >>> print(numpy.around(weights, 4))\n [0.1739 0.3261 0.3261 0.1739]\n \"\"\"\n from ..distributions.baseclass import Dist\n from ..distributions.collection import Uniform\n if isinstance(domain, Dist):\n abscissas, weights = quad_gauss_legendre(\n order, domain.range(), rule, accuracy, recurrence_algorithm)\n\n pdf = domain.pdf(abscissas)\n if len(domain) > 1:\n weights = (weights.T*pdf).T\n else:\n weights *= pdf.flatten()\n weights /= numpy.sum(weights)\n return abscissas, weights\n\n order = numpy.asarray(order, dtype=int).flatten()\n lower, upper = numpy.array(domain)\n lower = numpy.asarray(lower).flatten()\n upper = numpy.asarray(upper).flatten()\n\n dim = max(lower.size, upper.size, order.size)\n order = numpy.ones(dim, dtype=int)*order\n lower = numpy.ones(dim)*lower\n upper = numpy.ones(dim)*upper\n\n coefficients = construct_recurrence_coefficients(\n numpy.max(order), Uniform(0, 1), rule, accuracy, recurrence_algorithm)\n\n abscissas, weights = zip(*[coefficients_to_quadrature(\n coefficients[:order_+1]) for order_ in order])\n abscissas = list(numpy.asarray(abscissas).reshape(dim, -1))\n weights = list(numpy.asarray(weights).reshape(dim, -1))\n\n return combine_quadrature(abscissas, weights, (lower, upper))\n", "\"\"\"\nImplementation of Bastos-O'Hagen algorithm for modified Cholesky decomposition.\n\nAlgorithm 3 from \"Pivoting Cholesky Decomposition applied to Emulation and\nValidation of computer models\" by lowtri.S. Bastos and and mat. O'Hagan, 2007\n\"\"\"\nimport numpy\n\n\ndef bastos_ohagen(mat, eps=1e-16):\n \"\"\"\n Bastos-O'Hagen algorithm for modified Cholesky decomposition.\n\n Args:\n mat (numpy.ndarray):\n Input matrix to decompose. Assumed to close to positive definite.\n eps (float):\n Tolerance value for the eigenvalues. Values smaller\n than `tol*numpy.diag(mat).max()` are considered to be zero.\n\n Returns:\n (:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]):\n perm:\n Permutation matrix\n lowtri:\n Upper triangular decomposition\n errors:\n Error matrix\n\n Examples:\n >>> mat = [[4, 2, 1], [2, 6, 3], [1, 3, -.004]]\n >>> perm, lowtri = bastos_ohagen(mat)\n >>> print(perm)\n [[0 1 0]\n [1 0 0]\n [0 0 1]]\n >>> print(numpy.around(lowtri, 4))\n [[ 2.4495 0. 0. ]\n [ 0.8165 1.8257 0. ]\n [ 1.2247 -0. 0.9129]]\n >>> comp = numpy.dot(perm, lowtri)\n >>> print(numpy.around(numpy.dot(comp, comp.T), 4))\n [[4. 2. 1. ]\n [2. 6. 3. ]\n [1. 3. 2.3333]]\n \"\"\"\n mat_ref = numpy.asfarray(mat)\n mat = mat_ref.copy()\n diag_max = numpy.diag(mat).max()\n assert len(mat.shape) == 2\n size = len(mat)\n\n hitri = numpy.zeros((size, size))\n piv = numpy.arange(size)\n\n for idx in range(size):\n\n idx_max = numpy.argmax(numpy.diag(mat[idx:, idx:])) + idx\n\n if mat[idx_max, idx_max] <= numpy.abs(diag_max*eps):\n\n if not idx:\n raise ValueError(\"Purly negative definite\")\n\n for j in range(idx, size):\n hitri[j, j] = hitri[j-1, j-1]/float(j)\n\n break\n\n tmp = mat[:, idx].copy()\n mat[:, idx] = mat[:, idx_max]\n mat[:, idx_max] = tmp\n tmp = hitri[:, idx].copy()\n hitri[:, idx] = hitri[:, idx_max]\n hitri[:, idx_max] = tmp\n tmp = mat[idx, :].copy()\n mat[idx, :] = mat[idx_max, :]\n mat[idx_max, :] = tmp\n piv[idx], piv[idx_max] = piv[idx_max], piv[idx]\n\n hitri[idx, idx] = numpy.sqrt(mat[idx, idx])\n rval = mat[idx, idx+1:]/hitri[idx, idx]\n hitri[idx, idx+1:] = rval\n mat[idx+1:, idx+1:] -= numpy.outer(rval, rval)\n\n perm = numpy.zeros((size, size), dtype=int)\n for idx in range(size):\n perm[idx, piv[idx]] = 1\n\n return perm, hitri.T\n" ]
[ [ "scipy.special.ncfdtri", "scipy.special.ncfdtr", "scipy.special.assoc_laguerre", "scipy.special.gammaln", "numpy.exp", "scipy.special.beta" ], [ "numpy.sum" ], [ "numpy.log", "numpy.abs", "numpy.concatenate", "numpy.sign", "scipy.special.factorial" ], [ "numpy.arange", "numpy.tile", "numpy.all", "numpy.max", "numpy.column_stack", "numpy.array", "numpy.sum" ], [ "numpy.sqrt", "scipy.special.ndtr" ], [ "numpy.cos", "numpy.arccos", "numpy.sin" ], [ "numpy.asarray", "numpy.ones", "numpy.max", "numpy.array", "numpy.sum" ], [ "numpy.diag", "numpy.sqrt", "numpy.abs", "numpy.arange", "numpy.asfarray", "numpy.outer", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.14", "1.6", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "1.0", "0.17", "1.3", "1.8" ], "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": [] } ]
amgrigoriev/daal4py
[ "97fbe7a9181410dac348dc724178e8605492e3c4" ]
[ "tests/test_estimators.py" ]
[ "#*******************************************************************************\n# Copyright 2014-2020 Intel Corporation\n# All Rights Reserved.\n#\n# This software is licensed under the Apache License, Version 2.0 (the\n# \"License\"), the following terms apply:\n#\n# You may not use this file except in compliance with the License. You may\n# obtain a copy of the License at 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#*******************************************************************************\n\nimport unittest\n\nfrom sklearn.utils.estimator_checks import check_estimator\nimport sklearn.utils.estimator_checks\n\nfrom daal4py import __daal_run_version__\ndaal_run_version = tuple(map(int, (__daal_run_version__[0:4], __daal_run_version__[4:8])))\n\nfrom daal4py.sklearn.neighbors import KNeighborsClassifier\nfrom daal4py.sklearn.ensemble import RandomForestClassifier\nfrom daal4py.sklearn.ensemble import RandomForestRegressor\nfrom daal4py.sklearn.ensemble import GBTDAALClassifier\nfrom daal4py.sklearn.ensemble import GBTDAALRegressor\nfrom daal4py.sklearn.ensemble import AdaBoostClassifier\n\nfrom daal4py import __daal_link_version__ as dv\ndaal_version = tuple(map(int, (dv[0:4], dv[4:8])))\n\n\ndef check_version(rule, target):\n if not isinstance(rule[0], type(target)):\n if rule > target:\n return False\n else:\n for rule_item in range(len(rule)):\n if rule[rule_item] > target:\n return False\n else:\n if rule[rule_item][0]==target[0]:\n break\n return True\n\ndef _replace_and_save(md, fns, replacing_fn):\n \"\"\"\n Replaces functions in `fns` list in `md` module with `replacing_fn`.\n\n Returns the dictionary with functions that were replaced.\n \"\"\"\n saved = dict()\n for check_f in fns:\n try:\n fn = getattr(md, check_f)\n setattr(md, check_f, replacing_fn)\n saved[check_f] = fn\n except:\n pass\n return saved\n\n\ndef _restore_from_saved(md, saved_dict):\n \"\"\"\n Restores functions in `md` that were replaced in the function above.\n \"\"\"\n for check_f in saved_dict:\n setattr(md, check_f, saved_dict[check_f])\n\n\nclass Test(unittest.TestCase):\n def test_KNeighborsClassifier(self):\n check_estimator(KNeighborsClassifier)\n\n @unittest.skipUnless(check_version(((2019,0),(2021, 107)), daal_version), \"not supported in this library version\")\n def test_RandomForestClassifier(self):\n # check_methods_subset_invariance fails.\n # Issue is created:\n # https://github.com/IntelPython/daal4py/issues/129\n # Skip the test\n def dummy(*args, **kwargs):\n pass\n\n md = sklearn.utils.estimator_checks\n saved = _replace_and_save(md, ['check_methods_subset_invariance', 'check_dict_unchanged'], dummy)\n check_estimator(RandomForestClassifier)\n _restore_from_saved(md, saved)\n\n def test_RandomForestRegressor(self):\n # check_fit_idempotent is known to fail with DAAL's decision\n # forest regressor, due to different partitioning of data\n # between threads from run to run.\n # Hence skip that test\n def dummy(*args, **kwargs):\n pass\n md = sklearn.utils.estimator_checks\n saved = _replace_and_save(md, ['check_methods_subset_invariance', 'check_dict_unchanged'], dummy)\n check_estimator(RandomForestRegressor)\n _restore_from_saved(md, saved)\n\n def test_GBTDAALClassifier(self):\n check_estimator(GBTDAALClassifier)\n\n def test_GBTDAALRegressor(self):\n def dummy(*args, **kwargs):\n pass\n\n md = sklearn.utils.estimator_checks\n # got unexpected slightly different prediction result between two same calls in this test\n saved = _replace_and_save(md, ['check_estimators_data_not_an_array'], dummy)\n check_estimator(GBTDAALRegressor)\n _restore_from_saved(md, saved)\n\n @unittest.skipIf(daal_run_version < (2020, 0), \"not supported in this library version\")\n def test_AdaBoostClassifier(self):\n check_estimator(AdaBoostClassifier)\n\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "sklearn.utils.estimator_checks.check_estimator" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dvtrung/dl-torch
[ "b49e57d10d32bb223e2d7643f2579ccc32c63a9a", "b49e57d10d32bb223e2d7643f2579ccc32c63a9a", "b49e57d10d32bb223e2d7643f2579ccc32c63a9a" ]
[ "dlex/datasets/nlp/utils.py", "dlex_impl/bert/src/models/bert.py", "dlex/torch/models/attention/classifier.py" ]
[ "\"\"\"NLP Dataset\"\"\"\r\nimport os\r\nimport re\r\nfrom typing import List, Union, Dict, Tuple\r\n\r\nimport nltk\r\nimport unicodedata\r\nimport numpy as np\r\nfrom dlex.configs import ModuleConfigs\r\nfrom dlex.utils.logging import logger\r\n\r\n\r\n# nltk.download('punkt')\r\n\r\n\r\n# Turn a Unicode string to plain ASCII, thanks to\r\n# https://stackoverflow.com/a/518232/2809427\r\n\r\n\r\ndef unicodeToAscii(s):\r\n return ''.join(\r\n c for c in unicodedata.normalize('NFD', s)\r\n if unicodedata.category(c) != 'Mn'\r\n )\r\n\r\n\r\ndef load_tkn_to_idx(filename):\r\n tkn_to_idx = {}\r\n fo = open(filename, encoding='utf-8')\r\n for line in fo:\r\n line = line.strip()\r\n if line == \"\":\r\n continue\r\n tkn_to_idx[line] = len(tkn_to_idx)\r\n fo.close()\r\n return tkn_to_idx\r\n\r\n\r\ndef normalize_lower(sentence: str):\r\n return sentence.strip().lower()\r\n\r\n\r\ndef normalize_lower_alphanumeric(sentence: str):\r\n s = sentence.strip().lower()\r\n s = re.sub(\"[^a-z0-9\\uAC00-\\uD7A3]+\", \" \", s)\r\n return s\r\n\r\n\r\ndef normalize_string_ascii(sentence):\r\n \"\"\"\r\n :param str sentence:\r\n :return: normalized sentence, separated by space\r\n :rtype str\r\n \"\"\"\r\n # x = re.sub(\"[^ a-zA-Z0-9\\uAC00-\\uD7A3]+\", \" \", x)\r\n # x = re.sub(\"[\\u3040-\\u30FF]+\", \"\\u3042\", x) # convert Hiragana and Katakana to あ\r\n # x = re.sub(\"[\\u4E00-\\u9FFF]+\", \"\\u6F22\", x) # convert CJK unified ideographs to 漢\r\n sent = unicodeToAscii(sentence.lower().strip())\r\n sent = re.sub(r\"([.!?,])\", r\" \\1\", sent)\r\n sent = re.sub(r\"[^a-zA-Z.!?,]+\", r\" \", sent)\r\n sent = re.sub(r\"\\s+\", \" \", sent)\r\n sent = re.sub(\"^ | $\", \"\", sent)\r\n\r\n words = sent.split(' ')\r\n ret = []\r\n for word in words:\r\n ret.append(normalize_word(word))\r\n return ' '.join(ret)\r\n\r\n\r\ndef normalize_string(sentence):\r\n \"\"\"\r\n :param str sentence:\r\n :return: normalized sentence, separated by space\r\n :rtype str\r\n \"\"\"\r\n # x = re.sub(\"[^ a-zA-Z0-9\\uAC00-\\uD7A3]+\", \" \", x)\r\n # x = re.sub(\"[\\u3040-\\u30FF]+\", \"\\u3042\", x) # convert Hiragana and Katakana to あ\r\n # x = re.sub(\"[\\u4E00-\\u9FFF]+\", \"\\u6F22\", x) # convert CJK unified ideographs to 漢\r\n sentence = re.sub(r\"([\\.!?,\\\";\\(\\)])\\'\", r\" \\1\", sentence)\r\n # sent = re.sub(r\"[^a-zA-Z.!?,]+\", r\" \", sent)\r\n sentence = re.sub(r\"\\s+\", \" \", sentence)\r\n sentence = re.sub(\"^ | $\", \"\", sentence)\r\n\r\n words = sentence.split(' ')\r\n ret = []\r\n for word in words:\r\n ret.append(normalize_word(word))\r\n return ' '.join(ret)\r\n\r\n\r\ndef normalize_word(word):\r\n punctuations = [',', '.', '-', '\"', ':', '!', '(', ')', '...', '?']\r\n if word in ',.!?':\r\n return word\r\n elif word in punctuations:\r\n return '<punc>'\r\n elif any('0' <= c <= '9' for c in word):\r\n return '<non-word>'\r\n else:\r\n return word.lower()\r\n\r\n\r\ndef normalize_none(s):\r\n return s\r\n\r\n\r\ndef nltk_tokenize(s):\r\n return nltk.word_tokenize(s)\r\n\r\n\r\nclass Tokenizer:\r\n def __init__(self, normalize_fn=None, tokenize_fn=None):\r\n self.normalize_fn = normalize_fn\r\n self.tokenize_fn = tokenize_fn\r\n\r\n def process(self, s):\r\n s = self.normalize_fn(s)\r\n s = self.tokenize_fn(s)\r\n return s\r\n\r\n\r\nspacy_nlp = None\r\n\r\n\r\ndef spacy_tokenize(s):\r\n import spacy\r\n from spacy.symbols import ORTH\r\n global spacy_nlp\r\n if spacy_nlp is None:\r\n # sputnik.install('spacy', spacy.about.__version__, 'en_default', data_path=ModuleConfigs.get_tmp_path())\r\n spacy_nlp = spacy.load('en_core_web_sm', via=ModuleConfigs.get_tmp_path())\r\n spacy_nlp.tokenizer.add_special_case('<eos>', [{ORTH: '<eos>'}])\r\n spacy_nlp.tokenizer.add_special_case('<bos>', [{ORTH: '<bos>'}])\r\n spacy_nlp.tokenizer.add_special_case('<unk>', [{ORTH: '<unk>'}])\r\n return [_s.text for _s in spacy_nlp.tokenizer(s)]\r\n\r\n\r\ndef normalize_char(char):\r\n return char.lower().replace(' ', '_')\r\n\r\n\r\ndef space_tokenize(s):\r\n return s.split(' ')\r\n\r\n\r\ndef char_tokenize(s: str):\r\n s = s.replace(\" \", \"_\")\r\n return list(s)\r\n\r\n\r\ndef mecab_tokenize(s):\r\n import MeCab\r\n wakati = MeCab.Tagger(\"-Owakati\")\r\n return wakati.parse(s).split()\r\n\r\n\r\ndef write_vocab(\r\n text: Union[str, List[str], List[List[str]]],\r\n output_path: str,\r\n tokenizer: Tokenizer = None,\r\n min_freq=0,\r\n specials=None):\r\n \"\"\"\r\n\r\n :param text: text or list of sentences\r\n :param output_path:\r\n :param tokenizer: if tokenizer is None, tokens are separated by space\r\n :param min_freq:\r\n :param specials:\r\n :return:\r\n \"\"\"\r\n if tokenizer is None:\r\n tokenizer = Tokenizer(normalize_none, space_tokenize)\r\n if specials is None:\r\n specials = ['<pad>', '<sos>', '<eos>', '<oov>']\r\n word_freqs = {}\r\n\r\n if isinstance(text, str):\r\n text = [text]\r\n\r\n for sent in text:\r\n if isinstance(sent, str):\r\n # if normalize_fn is not None:\r\n # s = normalize_fn(sent.replace('_', ' '))\r\n # else:\r\n # s = sent\r\n # ls = char_tokenize(s) if token == 'char' else space_tokenize(s)\r\n sent = tokenizer.process(sent)\r\n \r\n for word in sent:\r\n if word.strip() == '':\r\n continue\r\n if word in word_freqs:\r\n word_freqs[word] += 1\r\n else:\r\n word_freqs[word] = 1\r\n\r\n words = list([word for word in word_freqs if word_freqs[word] > min_freq])\r\n words.sort(key=lambda word: word_freqs[word], reverse=True)\r\n with open(output_path, \"w\", encoding='utf-8') as fo:\r\n fo.write('\\n'.join(specials) + '\\n')\r\n fo.write(\"\\n\".join(words))\r\n\r\n logger.info(\"Vocab written to %s (%d tokens)\", output_path, len(specials) + len(words))\r\n\r\n\r\ndef get_token_id(vocab, word):\r\n \"\"\"\r\n :type vocab: Vocab\r\n :type word: str\r\n :rtype: int\r\n \"\"\"\r\n if word in vocab:\r\n return vocab[word]\r\n else:\r\n if '<oov>' in vocab:\r\n return vocab['<oov>']\r\n elif '<unk>' in vocab:\r\n return vocab['<unk>']\r\n else:\r\n raise Exception(\"No out-of-vocabulary token found.\")\r\n\r\n\r\nclass Vocab:\r\n def __init__(self, index2token: List[str] = None, token2index: Dict[str, int] = None):\r\n if index2token is None:\r\n self._token2index = {}\r\n self._index2token = []\r\n else:\r\n self._index2token = index2token\r\n if token2index:\r\n self._token2index = token2index\r\n else:\r\n self._token2index = {token: idx for idx, token in enumerate(index2token)}\r\n self.embeddings = None\r\n self.embedding_dim = None\r\n\r\n @classmethod\r\n def from_file(cls, file_name):\r\n index2token = []\r\n fo = open(file_name, encoding='utf-8')\r\n for line in fo:\r\n line = line.strip()\r\n if line == \"\":\r\n continue\r\n index2token.append(line)\r\n fo.close()\r\n return cls(index2token)\r\n\r\n def __getitem__(self, token: str) -> int:\r\n return self._token2index[token] if token in self._token2index else self.oov_token_idx\r\n\r\n def tolist(self) -> List[str]:\r\n return self._index2token\r\n\r\n def get_token_id(self, token):\r\n return self[token] or self.oov_token_idx\r\n\r\n def add_token(self, token: str):\r\n if token not in self._token2index:\r\n self._token2index[token] = len(self._token2index)\r\n self._index2token.append(token)\r\n\r\n def __len__(self):\r\n return len(self._token2index)\r\n\r\n def get_token(self, idx: int) -> str:\r\n return self._index2token[idx]\r\n\r\n def decode_idx_list(self, ls: List[int], ignore: List[int] = None, stop_at: int = None) -> List[str]:\r\n ret = []\r\n for idx in ls:\r\n if stop_at and idx == stop_at:\r\n break\r\n elif ignore and idx in ignore:\r\n continue\r\n else:\r\n ret.append(self.get_token(idx))\r\n return ret\r\n\r\n def encode_token_list(self, ls: List[str]) -> List[int]:\r\n return [self.get_token_id(token) for token in ls]\r\n\r\n @property\r\n def sos_token_idx(self) -> int:\r\n idx = self['<sos>'] or self['<s>']\r\n assert idx is not None\r\n return idx\r\n\r\n @property\r\n def eos_token_idx(self) -> int:\r\n idx = self['<eos>'] or self['</s>']\r\n assert idx is not None\r\n return idx\r\n\r\n @property\r\n def blank_token_idx(self):\r\n idx = self['<blank>'] or self['<pad>']\r\n assert idx is not None\r\n return idx\r\n\r\n @property\r\n def oov_token_idx(self) -> int:\r\n if '<oov>' in self._token2index:\r\n return self._token2index['<oov>']\r\n elif '<unk>' in self._token2index:\r\n return self._token2index['<unk>']\r\n else:\r\n raise Exception(\"<oov> token not found.\")\r\n\r\n def get_specials(self):\r\n return [token for token in self._index2token if token.startswith('<')]\r\n\r\n def init_pretrained_embeddings(\r\n self,\r\n pretrained: str,\r\n emb_name: str = None,\r\n dim: int = None) -> np.ndarray:\r\n if pretrained == 'glove':\r\n from torchtext.vocab import GloVe\r\n dim = dim or 300\r\n vocab = GloVe(\r\n name=emb_name or '840B', dim=dim,\r\n cache=os.path.join(ModuleConfigs.get_tmp_path(), \"torchtext\"))\r\n elif pretrained == 'fasttext':\r\n from torchtext.vocab import FastText\r\n vocab = FastText()\r\n else:\r\n raise ValueError(\"Pre-trained embeddings not found.\")\r\n\r\n vectors = vocab.vectors\r\n oovs = []\r\n\r\n embeddings = np.zeros([len(self), dim])\r\n for idx, t in enumerate(self._index2token):\r\n _t = t.lower()\r\n if _t in vocab.stoi:\r\n embeddings[idx, :] = vectors[vocab.stoi[_t]].cpu().numpy()\r\n if all(token in vocab.stoi for token in _t.split(' ')):\r\n embeddings[idx, :] = np.sum([vectors[vocab.stoi[token]].cpu().numpy() for token in _t.split(' ')])\r\n else:\r\n oovs.append(_t)\r\n\r\n if oovs:\r\n logger.warning(f\"{len(oovs)} tokens not found in pre-trained embeddings: {', '.join(oovs)}\")\r\n\r\n logger.debug(f\"Load embeddings: {pretrained} (no. embeddings: {len(self) - len(oovs):,})\")\r\n\r\n self.embedding_dim = dim\r\n self.embeddings = embeddings\r\n\r\n def get_token_embedding(self, token: str) -> np.ndarray:\r\n if self.embeddings is None:\r\n raise ValueError('Embeddings are not initialized')\r\n return self.embeddings[self.get_token_id(token)]\r\n\r\n def embed_token_list(self, ls):\r\n emb = np.zeros(self.embedding_dim)\r\n for token in ls:\r\n emb += self.get_token_embedding(token)\r\n return emb\r\n\r\n\r\ndef load_embeddings(\r\n pretrained: str,\r\n emb_name: str = None,\r\n dim: int = None,\r\n vocab_size: int = None,\r\n tokens: List[str] = None,\r\n specials: List[str] = None) -> Tuple[np.ndarray, Vocab]:\r\n \"\"\"\r\n Load pre-trained embedding defined in dataset.embeddings\r\n :param tokens: if specified, only load embeddings of these tokens\r\n :param specials: special tokens\r\n :return:\r\n \"\"\"\r\n if not pretrained:\r\n assert dim is not None\r\n assert vocab_size is not None\r\n return np.random.rand(vocab_size, dim), None\r\n elif pretrained.lower() in [\"glove\", \"fasttext\"]:\r\n if pretrained.lower() == 'glove':\r\n from torchtext.vocab import GloVe\r\n vocab = GloVe(\r\n name=emb_name, dim=dim,\r\n cache=os.path.join(ModuleConfigs.get_tmp_path(), \"torchtext\"))\r\n elif pretrained.lower() == 'fasttext':\r\n from torchtext.vocab import FastText\r\n vocab = FastText()\r\n else:\r\n raise ValueError(\"Pre-trained embeddings not found.\")\r\n\r\n vectors = vocab.vectors\r\n index2token = vocab.itos\r\n token2index = None\r\n if tokens: # limit vocabulary to list of tokens\r\n num_oovs = 0\r\n keep = []\r\n index2token = []\r\n token2index = {}\r\n for t in tokens:\r\n _t = t.lower()\r\n if _t in token2index:\r\n if t not in token2index:\r\n token2index[t] = token2index[_t]\r\n elif _t in vocab.stoi:\r\n keep.append(vocab.stoi[_t.lower()])\r\n token2index[_t] = len(index2token)\r\n token2index[t] = len(index2token)\r\n index2token.append(_t)\r\n else:\r\n num_oovs += 1\r\n vectors = vectors[keep]\r\n if num_oovs:\r\n logger.warning(f\"{num_oovs} tokens not found in pre-trained embeddings\")\r\n\r\n logger.debug(f\"Load embeddings: {pretrained} (no. embeddings: {len(index2token):,})\")\r\n\r\n if specials is not None:\r\n for s in specials:\r\n token2index[s] = len(index2token)\r\n index2token.append(s)\r\n index2token += specials\r\n vectors = torch.cat([vectors, torch.rand(len(specials), len(vectors[0]))])\r\n\r\n # return nn.Embedding.from_pretrained(vectors, freeze=emb.freeze or True), Vocab(index2token, token2index)\r\n return vectors, Vocab(index2token, token2index)\r\n else:\r\n raise ValueError(f\"{pretrained} is not supported.\")\r\n", "import bert\r\nfrom dlex import Params\r\nfrom dlex.datasets.tf import Dataset\r\nfrom dlex.tf.models import BaseModelV1\r\nimport tensorflow_hub as hub\r\nimport tensorflow as tf\r\nfrom dlex.utils import logger\r\n\r\nBERT_MODEL_HUB = \"https://tfhub.dev/google/bert_uncased_L-12_H-768_A-12/1\"\r\n\r\n\r\nclass BERT(BaseModelV1):\r\n def __init__(self, params: Params, dataset: Dataset):\r\n super().__init__(params, dataset)\r\n self._optimizer = None\r\n self._metric_ops = None\r\n self._train_op = None\r\n\r\n def forward(self, batch):\r\n input_ids = batch[\"input_ids\"]\r\n input_mask = batch[\"input_mask\"]\r\n segment_ids = batch[\"segment_ids\"]\r\n\r\n bert_module = hub.Module(BERT_MODEL_HUB, trainable=True)\r\n bert_inputs = dict(input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids)\r\n bert_outputs = bert_module(inputs=bert_inputs, signature=\"tokens\", as_dict=True)\r\n\r\n # Use \"pooled_output\" for classification tasks on an entire sentence.\r\n # Use \"sequence_outputs\" for token-level output.\r\n output_layer = bert_outputs[\"pooled_output\"]\r\n hidden_size = output_layer.shape[-1].value\r\n output_weights = tf.compat.v1.get_variable(\r\n \"output_weights\", [self.dataset.num_labels, hidden_size],\r\n initializer=tf.truncated_normal_initializer(stddev=0.02))\r\n output_bias = tf.compat.v1.get_variable(\r\n \"output_bias\", [self.dataset.num_labels],\r\n initializer=tf.zeros_initializer())\r\n\r\n with tf.compat.v1.variable_scope(\"loss\"):\r\n output_layer = tf.nn.dropout(output_layer, rate=0.1)\r\n\r\n logits = tf.matmul(output_layer, output_weights, transpose_b=True)\r\n logits = tf.nn.bias_add(logits, output_bias)\r\n\r\n return tf.nn.log_softmax(logits, axis=-1)\r\n\r\n def get_train_op(self, loss):\r\n train_cfg = self.params.train\r\n num_train_steps = int(len(self.dataset) / train_cfg.batch_size * train_cfg.num_epochs)\r\n num_warmup_steps = int(num_train_steps * 0.1)\r\n return bert.optimization.create_optimizer(\r\n loss, train_cfg.optimizer.lr,\r\n num_train_steps, num_warmup_steps, use_tpu=False\r\n )\r\n\r\n def get_loss(self, batch, output):\r\n log_probs = tf.nn.log_softmax(output, axis=-1)\r\n one_hot_labels = tf.one_hot(batch[\"label_ids\"], depth=self.dataset.num_labels, dtype=tf.float32)\r\n per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)\r\n return tf.reduce_mean(per_example_loss)\r\n\r\n def get_metric_ops(self, batch, output):\r\n ref = batch[\"label_ids\"]\r\n pred = tf.squeeze(tf.argmax(output, axis=-1, output_type=tf.int32))\r\n return dict(\r\n acc=tf.compat.v1.metrics.accuracy(ref, pred),\r\n f1=tf.contrib.metrics.f1_score(ref, pred),\r\n auc=tf.compat.v1.metrics.auc(ref, pred),\r\n recall=tf.compat.v1.metrics.recall(ref, pred),\r\n precision=tf.compat.v1.metrics.precision(ref, pred),\r\n )", "from dataclasses import dataclass\nfrom typing import List\n\nimport math\nimport numpy as np\nimport torch.nn as nn\n\nimport torch\nfrom dlex.datasets.seq2seq.torch import PytorchSeq2SeqDataset\nfrom dlex.torch import Batch\nfrom dlex.torch.models.attention.attention import BahdanauAttention, NoAttention\nfrom dlex.torch.models.base import ClassificationModel\nfrom dlex.utils.logging import logger\nfrom .decoder import DecoderRNN\nfrom .encoder import EncoderRNN\n\n\n@dataclass\nclass EncoderConfigDict:\n num_layers: int\n hidden_size: int\n output_size: int\n rnn_type: str = \"lstm\"\n bidirectional: bool = False\n input_size: int = None\n update_embedding: bool = True\n\n\n@dataclass\nclass DecoderConfigDict:\n hidden_size: int\n output_size: int = None\n\n\n@dataclass\nclass AttentionConfigDict:\n type: str\n size: int = None\n # location-based attention\n num_channels: int = None\n filter_size: int = None\n\n\n@dataclass\nclass AttentionModelConfigDict:\n name: str\n encoder: EncoderConfigDict\n decoder: DecoderConfigDict\n attention: AttentionConfigDict\n dropout: float\n\n def __post_init__(self):\n self.encoder = EncoderConfigDict(**self.encoder)\n self.decoder = DecoderConfigDict(**self.decoder)\n self.attention = AttentionConfigDict(**self.attention)\n\n\nclass SequenceClassifier(ClassificationModel):\n def __init__(self, params, dataset: PytorchSeq2SeqDataset):\n super().__init__(params, dataset)\n self.configs = AttentionModelConfigDict(**self.params.model)\n\n # subsample info\n # +1 means input (+1) and layers outputs (args.elayer)\n subsample = np.ones(self.configs.encoder.num_layers + 1, dtype=np.int)\n logger.info('subsample: ' + ' '.join([str(x) for x in subsample]))\n self.subsample = subsample\n\n # encoder\n self._encoder = self._build_encoder()\n # attention\n self._attention = self._build_attention()\n # decoder\n self._decoder = self._build_decoder()\n\n # weight initialization\n self.init_like_chainer()\n\n def _build_encoder(self) -> EncoderRNN:\n cfg = self.configs\n return EncoderRNN(\n input_size=self.dataset.input_size,\n rnn_type=cfg.encoder.rnn_type,\n bidirectional=cfg.encoder.bidirectional,\n num_layers=cfg.encoder.num_layers,\n hidden_size=cfg.encoder.hidden_size,\n output_size=cfg.encoder.output_size,\n dropout=cfg.dropout)\n\n def _build_decoder(self) -> DecoderRNN:\n cfg = self.configs\n return DecoderRNN(\n input_size=0,\n rnn_type=\"rnn\",\n num_layers=1,\n hidden_size=cfg.decoder.hidden_size,\n output_size=cfg.decoder.output_size,\n vocab_size=self.dataset.num_classes,\n attention=self._attention,\n sos_idx=0, # any label since input_size = 0\n eos_idx=None,\n max_length=None,\n beam_search_configs=None,\n dropout=cfg.dropout)\n\n def _build_attention(self) -> List[torch.nn.Module]:\n cfg = self.configs\n logger.info(\"Attention type: %s\", cfg.attention.type)\n if cfg.attention.type is None:\n attention = [NoAttention()]\n elif cfg.attention.type == 'bahdanau':\n self._test = BahdanauAttention(\n encoder_output_size=cfg.encoder.output_size,\n decoder_hidden_size=cfg.decoder.hidden_size,\n attention_dim=cfg.attention.size,\n )\n attention = torch.nn.ModuleList([self._test])\n else:\n raise Exception(f\"Attention type is not defined: ${cfg.attention.type}\")\n return attention\n\n def init_like_chainer(self):\n \"\"\"Initialize weight like chainer\n\n chainer basically uses LeCun way: W ~ Normal(0, fan_in ** -0.5), b = 0\n pytorch basically uses W, b ~ Uniform(-fan_in**-0.5, fan_in**-0.5)\n\n however, there are two exceptions as far as I know.\n - EmbedID.W ~ Normal(0, 1)\n - LSTM.upward.b[forget_gate_range] = 1 (but not used in NStepLSTM)\n \"\"\"\n\n def lecun_normal_init_parameters(module):\n for p in module.parameters():\n data = p.data\n if data.dim() > 1 and data.size(1) == 0:\n continue\n if data.dim() == 1:\n # bias\n data.zero_()\n elif data.dim() == 2:\n # linear weight\n n = data.size(1)\n stdv = 1. / math.sqrt(n)\n data.normal_(0, stdv)\n elif data.dim() == 4:\n # conv weight\n n = data.size(1)\n for k in data.size()[2:]:\n n *= k\n stdv = 1. / math.sqrt(n)\n data.normal_(0, stdv)\n else:\n raise NotImplementedError\n\n def set_forget_bias_to_one(bias):\n n = bias.size(0)\n start, end = n // 4, n // 2\n bias.data[start:end].fill_(1.)\n\n lecun_normal_init_parameters(self)\n # exceptions\n # embed weight ~ Normal(0, 1)\n self._decoder.embed.weight.data.normal_(0, 1)\n # forget-bias = 1.0\n # https://discuss.pytorch.org/t/set-forget-gate-bias-of-lstm/1745\n for l in range(len(self._decoder._decoder)):\n set_forget_bias_to_one(self._decoder._decoder[l].bias_ih)\n\n def forward(self, batch: Batch):\n states = self._encoder(batch.X, batch.X_len)\n y = batch.Y.view((-1, 1))\n states.decoder_inputs = torch.cat([torch.full(y.shape, 0, dtype=y.dtype, device=y.device), y], dim=-1)\n states = self._decoder(states, use_teacher_forcing=True)\n return states.decoder_outputs[:, 0, :]\n\n def infer(self, batch: Batch):\n states = self._encoder(batch.X, batch.X_len)\n y = batch.Y.view((-1, 1))\n states.decoder_inputs = torch.cat([torch.full(y.shape, 0, dtype=y.dtype, device=y.device), y], dim=-1)\n states = self._decoder(states, use_teacher_forcing=True)\n _, sequences = torch.max(states.decoder_outputs[:, 0, :], dim=-1)\n return sequences, None, states\n\n def calculate_all_attentions(self, batch):\n with torch.no_grad():\n encoder_outputs, encoder_output_lens, _ = self._encoder(batch.X, batch.X_len)\n return self._decoder.calculate_all_attentions(encoder_outputs, encoder_output_lens, batch.Y)\n\n def subsample_frames(self, x):\n # subsample frame\n x = x[::self.subsample[0], :]\n ilen = [x.shape[0]]\n h = to_device(self, torch.from_numpy(\n np.array(x, dtype=np.float32)))\n h.contiguous()\n return h, ilen\n\n def write_summary(self, summary_writer, batch, output):\n y_pred, others = output\n str_input, str_ground_truth, str_predicted = self.dataset.format_output(y_pred[0], batch.item(i))\n summary_writer.add_text(\n \"inference_result\",\n str_predicted,\n self.current_epoch)\n # img = [attentions[0] for attentions in others.attentions]\n # logger.debug(len(others.attentions))\n\n def train_log(self, batch: Batch, output, verbose):\n d = super().train_log(batch, output, verbose)\n if verbose:\n d[\"input_length\"] = batch.X.shape[1]\n d[\"output_length\"] = batch.Y.shape[1]\n return d\n\n def infer_log(self, batch: Batch, output, verbose):\n d = super().infer_log(batch, output, verbose)\n if verbose:\n d[\"input_length\"] = batch.X.shape[1]\n d[\"output_length\"] = max([len(seq) for seq in output])\n return d\n\n\nclass LabelSequenceClassifier(SequenceClassifier):\n def __init__(self, params, dataset):\n super().__init__(params, dataset)\n\n def _build_encoder(self) -> EncoderRNN:\n \"\"\"\n :rtype: EncoderRNN\n \"\"\"\n cfg = self.params.model\n\n self.embedding = nn.Embedding(\n num_embeddings=self.dataset.vocab_size,\n embedding_dim=cfg.encoder.input_size)\n if cfg.encoder.embedding is not None:\n # TODO: implement custom embedding\n pass\n self.embedding.requires_grad = cfg.encoder.update_embedding\n\n return EncoderRNN(\n input_size=cfg.encoder.input_size,\n rnn_type=cfg.encoder.rnn_type,\n num_layers=cfg.encoder.num_layers,\n hidden_size=cfg.encoder.hidden_size,\n output_size=cfg.encoder.output_size,\n bidirectional=cfg.encoder.bidirectional,\n dropout=cfg.dropout\n )\n\n def forward(self, batch: Batch):\n return super().forward(Batch(\n X=self.embedding(batch.X.to(self.embedding.weight.device)),\n X_len=batch.X_len,\n Y=batch.Y.to(self.embedding.weight.device),\n Y_len=batch.Y_len\n ))\n\n def infer(self, batch: Batch):\n return super().infer(Batch(\n X=self.embedding(batch.X.to(self.embedding.weight.device)),\n X_len=batch.X_len,\n Y=batch.Y,\n Y_len=batch.Y_len\n ))" ]
[ [ "numpy.zeros", "numpy.random.rand" ], [ "tensorflow.nn.bias_add", "tensorflow.matmul", "tensorflow.nn.log_softmax", "tensorflow.compat.v1.metrics.auc", "tensorflow.reduce_mean", "tensorflow.compat.v1.metrics.accuracy", "tensorflow.reduce_sum", "tensorflow.zeros_initializer", "tensorflow.truncated_normal_initializer", "tensorflow.compat.v1.metrics.recall", "tensorflow.contrib.metrics.f1_score", "tensorflow.compat.v1.metrics.precision", "tensorflow.one_hot", "tensorflow.argmax", "tensorflow.compat.v1.variable_scope", "tensorflow.nn.dropout" ], [ "torch.max", "torch.full", "torch.nn.ModuleList", "torch.nn.Embedding", "numpy.ones", "torch.no_grad", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
annaproxy/udify-metalearning
[ "55206a3aac0aba74a3615a36192d03b6467cfd6f", "55206a3aac0aba74a3615a36192d03b6467cfd6f", "55206a3aac0aba74a3615a36192d03b6467cfd6f", "55206a3aac0aba74a3615a36192d03b6467cfd6f" ]
[ "allennlp/tests/data/fields/sequence_label_field_test.py", "allennlp/modules/scalar_mix.py", "allennlp/tests/modules/highway_test.py", "allennlp/models/semantic_parsing/quarel/quarel_semantic_parser.py" ]
[ "# pylint: disable=no-self-use,invalid-name\nfrom collections import defaultdict\n\nimport pytest\nimport numpy\n\nfrom allennlp.common.checks import ConfigurationError\nfrom allennlp.common.testing import AllenNlpTestCase\nfrom allennlp.data import Token, Vocabulary\nfrom allennlp.data.fields import TextField, SequenceLabelField\nfrom allennlp.data.token_indexers import SingleIdTokenIndexer\n\n\nclass TestSequenceLabelField(AllenNlpTestCase):\n def setUp(self):\n super(TestSequenceLabelField, self).setUp()\n self.text = TextField([Token(t) for t in [\"here\", \"are\", \"some\", \"words\", \".\"]],\n {\"words\": SingleIdTokenIndexer(\"words\")})\n\n def test_tag_length_mismatch_raises(self):\n with pytest.raises(ConfigurationError):\n wrong_tags = [\"B\", \"O\", \"O\"]\n _ = SequenceLabelField(wrong_tags, self.text)\n\n def test_count_vocab_items_correctly_indexes_tags(self):\n tags = [\"B\", \"I\", \"O\", \"O\", \"O\"]\n sequence_label_field = SequenceLabelField(tags, self.text, label_namespace=\"labels\")\n\n counter = defaultdict(lambda: defaultdict(int))\n sequence_label_field.count_vocab_items(counter)\n\n assert counter[\"labels\"][\"B\"] == 1\n assert counter[\"labels\"][\"I\"] == 1\n assert counter[\"labels\"][\"O\"] == 3\n assert set(counter.keys()) == {\"labels\"}\n\n def test_index_converts_field_correctly(self):\n vocab = Vocabulary()\n b_index = vocab.add_token_to_namespace(\"B\", namespace='*labels')\n i_index = vocab.add_token_to_namespace(\"I\", namespace='*labels')\n o_index = vocab.add_token_to_namespace(\"O\", namespace='*labels')\n\n tags = [\"B\", \"I\", \"O\", \"O\", \"O\"]\n sequence_label_field = SequenceLabelField(tags, self.text, label_namespace=\"*labels\")\n sequence_label_field.index(vocab)\n\n # pylint: disable=protected-access\n assert sequence_label_field._indexed_labels == [b_index, i_index, o_index, o_index, o_index]\n # pylint: enable=protected-access\n\n def test_as_tensor_produces_integer_targets(self):\n vocab = Vocabulary()\n vocab.add_token_to_namespace(\"B\", namespace='*labels')\n vocab.add_token_to_namespace(\"I\", namespace='*labels')\n vocab.add_token_to_namespace(\"O\", namespace='*labels')\n\n tags = [\"B\", \"I\", \"O\", \"O\", \"O\"]\n sequence_label_field = SequenceLabelField(tags, self.text, label_namespace=\"*labels\")\n sequence_label_field.index(vocab)\n padding_lengths = sequence_label_field.get_padding_lengths()\n tensor = sequence_label_field.as_tensor(padding_lengths).detach().cpu().numpy()\n numpy.testing.assert_array_almost_equal(tensor, numpy.array([0, 1, 2, 2, 2]))\n\n def test_sequence_label_field_raises_on_incorrect_type(self):\n\n with pytest.raises(ConfigurationError):\n _ = SequenceLabelField([[], [], [], [], []], self.text)\n\n def test_class_variables_for_namespace_warnings_work_correctly(self):\n # pylint: disable=protected-access\n tags = [\"B\", \"I\", \"O\", \"O\", \"O\"]\n assert \"text\" not in SequenceLabelField._already_warned_namespaces\n with self.assertLogs(logger=\"allennlp.data.fields.sequence_label_field\", level=\"WARNING\"):\n _ = SequenceLabelField(tags, self.text, label_namespace=\"text\")\n\n # We've warned once, so we should have set the class variable to False.\n assert \"text\" in SequenceLabelField._already_warned_namespaces\n with pytest.raises(AssertionError):\n with self.assertLogs(logger=\"allennlp.data.fields.sequence_label_field\", level=\"WARNING\"):\n _ = SequenceLabelField(tags, self.text, label_namespace=\"text\")\n\n # ... but a new namespace should still log a warning.\n assert \"text2\" not in SequenceLabelField._already_warned_namespaces\n with self.assertLogs(logger=\"allennlp.data.fields.sequence_label_field\", level=\"WARNING\"):\n _ = SequenceLabelField(tags, self.text, label_namespace=\"text2\")\n\n def test_printing_doesnt_crash(self):\n tags = [\"B\", \"I\", \"O\", \"O\", \"O\"]\n sequence_label_field = SequenceLabelField(tags, self.text, label_namespace=\"labels\")\n print(sequence_label_field)\n\n def test_sequence_methods(self):\n tags = [\"B\", \"I\", \"O\", \"O\", \"O\"]\n sequence_label_field = SequenceLabelField(tags, self.text, label_namespace=\"labels\")\n\n assert len(sequence_label_field) == 5\n assert sequence_label_field[1] == \"I\"\n assert [label for label in sequence_label_field] == tags\n", "from typing import List\n\nimport torch\nfrom torch.nn import ParameterList, Parameter\n\nfrom allennlp.common.checks import ConfigurationError\n\nclass ScalarMix(torch.nn.Module):\n \"\"\"\n Computes a parameterised scalar mixture of N tensors, ``mixture = gamma * sum(s_k * tensor_k)``\n where ``s = softmax(w)``, with ``w`` and ``gamma`` scalar parameters.\n\n In addition, if ``do_layer_norm=True`` then apply layer normalization to each tensor\n before weighting.\n \"\"\"\n def __init__(self,\n mixture_size: int,\n do_layer_norm: bool = False,\n initial_scalar_parameters: List[float] = None,\n trainable: bool = True) -> None:\n super(ScalarMix, self).__init__()\n self.mixture_size = mixture_size\n self.do_layer_norm = do_layer_norm\n\n if initial_scalar_parameters is None:\n initial_scalar_parameters = [0.0] * mixture_size\n elif len(initial_scalar_parameters) != mixture_size:\n raise ConfigurationError(\"Length of initial_scalar_parameters {} differs \"\n \"from mixture_size {}\".format(\n initial_scalar_parameters, mixture_size))\n\n self.scalar_parameters = ParameterList(\n [Parameter(torch.FloatTensor([initial_scalar_parameters[i]]),\n requires_grad=trainable) for i\n in range(mixture_size)])\n self.gamma = Parameter(torch.FloatTensor([1.0]), requires_grad=trainable)\n\n def forward(self, tensors: List[torch.Tensor], # pylint: disable=arguments-differ\n mask: torch.Tensor = None) -> torch.Tensor:\n \"\"\"\n Compute a weighted average of the ``tensors``. The input tensors an be any shape\n with at least two dimensions, but must all be the same shape.\n\n When ``do_layer_norm=True``, the ``mask`` is required input. If the ``tensors`` are\n dimensioned ``(dim_0, ..., dim_{n-1}, dim_n)``, then the ``mask`` is dimensioned\n ``(dim_0, ..., dim_{n-1})``, as in the typical case with ``tensors`` of shape\n ``(batch_size, timesteps, dim)`` and ``mask`` of shape ``(batch_size, timesteps)``.\n\n When ``do_layer_norm=False`` the ``mask`` is ignored.\n \"\"\"\n if len(tensors) != self.mixture_size:\n raise ConfigurationError(\"{} tensors were passed, but the module was initialized to \"\n \"mix {} tensors.\".format(len(tensors), self.mixture_size))\n\n def _do_layer_norm(tensor, broadcast_mask, num_elements_not_masked):\n tensor_masked = tensor * broadcast_mask\n mean = torch.sum(tensor_masked) / num_elements_not_masked\n variance = torch.sum(((tensor_masked - mean) * broadcast_mask)**2) / num_elements_not_masked\n return (tensor - mean) / torch.sqrt(variance + 1E-12)\n\n normed_weights = torch.nn.functional.softmax(torch.cat([parameter for parameter\n in self.scalar_parameters]), dim=0)\n normed_weights = torch.split(normed_weights, split_size_or_sections=1)\n\n if not self.do_layer_norm:\n pieces = []\n for weight, tensor in zip(normed_weights, tensors):\n pieces.append(weight * tensor)\n return self.gamma * sum(pieces)\n\n else:\n mask_float = mask.float()\n broadcast_mask = mask_float.unsqueeze(-1)\n input_dim = tensors[0].size(-1)\n num_elements_not_masked = torch.sum(mask_float) * input_dim\n\n pieces = []\n for weight, tensor in zip(normed_weights, tensors):\n pieces.append(weight * _do_layer_norm(tensor,\n broadcast_mask, num_elements_not_masked))\n return self.gamma * sum(pieces)\n", "# pylint: disable=no-self-use,invalid-name\nfrom numpy.testing import assert_almost_equal\nimport torch\n\nfrom allennlp.modules import Highway\nfrom allennlp.common.testing import AllenNlpTestCase\n\n\nclass TestHighway(AllenNlpTestCase):\n def test_forward_works_on_simple_input(self):\n highway = Highway(2, 2)\n # pylint: disable=protected-access\n highway._layers[0].weight.data.fill_(1)\n highway._layers[0].bias.data.fill_(0)\n highway._layers[1].weight.data.fill_(2)\n highway._layers[1].bias.data.fill_(-2)\n input_tensor = torch.FloatTensor([[-2, 1], [3, -2]])\n result = highway(input_tensor).data.numpy()\n assert result.shape == (2, 2)\n # This was checked by hand.\n assert_almost_equal(result, [[-0.0394, 0.0197], [1.7527, -0.5550]], decimal=4)\n\n def test_forward_works_on_nd_input(self):\n highway = Highway(2, 2)\n input_tensor = torch.ones(2, 2, 2)\n output = highway(input_tensor)\n assert output.size() == (2, 2, 2)\n", "from typing import Any, Dict, List, Tuple\n\nimport math\nfrom overrides import overrides\nimport torch\n\nfrom allennlp.common.util import pad_sequence_to_length\nfrom allennlp.data import Vocabulary\nfrom allennlp.data.fields.production_rule_field import ProductionRule\nfrom allennlp.models.model import Model\nfrom allennlp.modules import Attention, TextFieldEmbedder, Seq2SeqEncoder, FeedForward, Embedding\nfrom allennlp.modules.seq2vec_encoders import Seq2VecEncoder\nfrom allennlp.modules.time_distributed import TimeDistributed\nfrom allennlp.nn import util\nfrom allennlp.semparse.type_declarations import type_declaration\nfrom allennlp.semparse.type_declarations.type_declaration import START_SYMBOL\nfrom allennlp.semparse.worlds.quarel_world import QuarelWorld\nfrom allennlp.semparse import ParsingError\nfrom allennlp.state_machines import BeamSearch\nfrom allennlp.state_machines.states import GrammarBasedState, GrammarStatelet, RnnStatelet\nfrom allennlp.state_machines.trainers import MaximumMarginalLikelihood\nfrom allennlp.state_machines.transition_functions import LinkingTransitionFunction\nfrom allennlp.training.metrics import Average, CategoricalAccuracy\n\n\[email protected](\"quarel_parser\")\nclass QuarelSemanticParser(Model):\n \"\"\"\n A ``QuarelSemanticParser`` is a variant of ``WikiTablesSemanticParser`` with various\n tweaks and changes.\n\n Parameters\n ----------\n vocab : ``Vocabulary``\n question_embedder : ``TextFieldEmbedder``\n Embedder for questions.\n action_embedding_dim : ``int``\n Dimension to use for action embeddings.\n encoder : ``Seq2SeqEncoder``\n The encoder to use for the input question.\n decoder_beam_search : ``BeamSearch``\n When we're not training, this is how we will do decoding.\n max_decoding_steps : ``int``\n When we're decoding with a beam search, what's the maximum number of steps we should take?\n This only applies at evaluation time, not during training.\n attention : ``Attention``\n We compute an attention over the input question at each step of the decoder, using the\n decoder hidden state as the query. Passed to the transition function.\n dropout : ``float``, optional (default=0)\n If greater than 0, we will apply dropout with this probability after all encoders (pytorch\n LSTMs do not apply dropout to their last layer).\n num_linking_features : ``int``, optional (default=10)\n We need to construct a parameter vector for the linking features, so we need to know how\n many there are. The default of 8 here matches the default in the ``KnowledgeGraphField``,\n which is to use all eight defined features. If this is 0, another term will be added to the\n linking score. This term contains the maximum similarity value from the entity's neighbors\n and the question.\n use_entities : ``bool``, optional (default=False)\n Whether dynamic entities are part of the action space\n num_entity_bits : ``int``, optional (default=0)\n Whether any bits are added to encoder input/output to represent tagged entities\n entity_bits_output : ``bool``, optional (default=False)\n Whether entity bits are added to the encoder output or input\n denotation_only : ``bool``, optional (default=False)\n Whether to only predict target denotation, skipping the the whole logical form decoder\n entity_similarity_mode : ``str``, optional (default=\"dot_product\")\n How to compute vector similarity between question and entity tokens, can take values\n \"dot_product\" or \"weighted_dot_product\" (learned weights on each dimension)\n rule_namespace : ``str``, optional (default=rule_labels)\n The vocabulary namespace to use for production rules. The default corresponds to the\n default used in the dataset reader, so you likely don't need to modify this.\n \"\"\"\n def __init__(self,\n vocab: Vocabulary,\n question_embedder: TextFieldEmbedder,\n action_embedding_dim: int,\n encoder: Seq2SeqEncoder,\n decoder_beam_search: BeamSearch,\n max_decoding_steps: int,\n attention: Attention,\n mixture_feedforward: FeedForward = None,\n add_action_bias: bool = True,\n dropout: float = 0.0,\n num_linking_features: int = 0,\n num_entity_bits: int = 0,\n entity_bits_output: bool = True,\n use_entities: bool = False,\n denotation_only: bool = False,\n # Deprecated parameter to load older models\n entity_encoder: Seq2VecEncoder = None, # pylint: disable=unused-argument\n entity_similarity_mode: str = \"dot_product\",\n rule_namespace: str = 'rule_labels') -> None:\n super(QuarelSemanticParser, self).__init__(vocab)\n self._question_embedder = question_embedder\n self._encoder = encoder\n self._beam_search = decoder_beam_search\n self._max_decoding_steps = max_decoding_steps\n if dropout > 0:\n self._dropout = torch.nn.Dropout(p=dropout)\n else:\n self._dropout = lambda x: x\n self._rule_namespace = rule_namespace\n self._denotation_accuracy = Average()\n self._action_sequence_accuracy = Average()\n self._has_logical_form = Average()\n\n self._embedding_dim = question_embedder.get_output_dim()\n self._use_entities = use_entities\n\n # Note: there's only one non-trivial entity type in QuaRel for now, so most of the\n # entity_type stuff is irrelevant\n self._num_entity_types = 4 # TODO(mattg): get this in a more principled way somehow?\n self._entity_type_encoder_embedding = Embedding(self._num_entity_types, self._embedding_dim)\n self._entity_type_decoder_embedding = Embedding(self._num_entity_types, action_embedding_dim)\n\n self._entity_similarity_layer = None\n self._entity_similarity_mode = entity_similarity_mode\n if self._entity_similarity_mode == \"weighted_dot_product\":\n self._entity_similarity_layer = \\\n TimeDistributed(torch.nn.Linear(self._embedding_dim, 1, bias=False))\n # Center initial values around unweighted dot product\n self._entity_similarity_layer._module.weight.data += 1 # pylint: disable=protected-access\n elif self._entity_similarity_mode == \"dot_product\":\n pass\n else:\n raise ValueError(\"Invalid entity_similarity_mode: {}\".format(self._entity_similarity_mode))\n\n if num_linking_features > 0:\n self._linking_params = torch.nn.Linear(num_linking_features, 1)\n else:\n self._linking_params = None\n\n self._decoder_trainer = MaximumMarginalLikelihood()\n\n self._encoder_output_dim = self._encoder.get_output_dim()\n if entity_bits_output:\n self._encoder_output_dim += num_entity_bits\n\n self._entity_bits_output = entity_bits_output\n\n self._debug_count = 10\n\n self._num_denotation_cats = 2 # Hardcoded for simplicity\n self._denotation_only = denotation_only\n if self._denotation_only:\n self._denotation_accuracy_cat = CategoricalAccuracy()\n self._denotation_classifier = torch.nn.Linear(self._encoder_output_dim,\n self._num_denotation_cats)\n # Rest of init not needed for denotation only where no decoding to actions needed\n return\n\n self._action_padding_index = -1 # the padding value used by IndexField\n num_actions = vocab.get_vocab_size(self._rule_namespace)\n self._num_actions = num_actions\n self._action_embedder = Embedding(num_embeddings=num_actions, embedding_dim=action_embedding_dim)\n # We are tying the action embeddings used for input and output\n # self._output_action_embedder = Embedding(num_embeddings=num_actions, embedding_dim=action_embedding_dim)\n self._output_action_embedder = self._action_embedder # tied weights\n self._add_action_bias = add_action_bias\n if self._add_action_bias:\n self._action_biases = Embedding(num_embeddings=num_actions, embedding_dim=1)\n\n # This is what we pass as input in the first step of decoding, when we don't have a\n # previous action, or a previous question attention.\n self._first_action_embedding = torch.nn.Parameter(torch.FloatTensor(action_embedding_dim))\n self._first_attended_question = torch.nn.Parameter(torch.FloatTensor(self._encoder_output_dim))\n torch.nn.init.normal_(self._first_action_embedding)\n torch.nn.init.normal_(self._first_attended_question)\n\n self._decoder_step = LinkingTransitionFunction(encoder_output_dim=self._encoder_output_dim,\n action_embedding_dim=action_embedding_dim,\n input_attention=attention,\n add_action_bias=self._add_action_bias,\n mixture_feedforward=mixture_feedforward,\n dropout=dropout)\n\n @overrides\n def forward(self, # type: ignore\n question: Dict[str, torch.LongTensor],\n table: Dict[str, torch.LongTensor],\n world: List[QuarelWorld],\n actions: List[List[ProductionRule]],\n entity_bits: torch.Tensor = None,\n denotation_target: torch.Tensor = None,\n target_action_sequences: torch.LongTensor = None,\n metadata: List[Dict[str, Any]] = None) -> Dict[str, torch.Tensor]:\n # pylint: disable=arguments-differ\n # pylint: disable=unused-argument\n \"\"\"\n In this method we encode the table entities, link them to words in the question, then\n encode the question. Then we set up the initial state for the decoder, and pass that\n state off to either a DecoderTrainer, if we're training, or a BeamSearch for inference,\n if we're not.\n\n Parameters\n ----------\n question : Dict[str, torch.LongTensor]\n The output of ``TextField.as_array()`` applied on the question ``TextField``. This will\n be passed through a ``TextFieldEmbedder`` and then through an encoder.\n table : ``Dict[str, torch.LongTensor]``\n The output of ``KnowledgeGraphField.as_array()`` applied on the table\n ``KnowledgeGraphField``. This output is similar to a ``TextField`` output, where each\n entity in the table is treated as a \"token\", and we will use a ``TextFieldEmbedder`` to\n get embeddings for each entity.\n world : ``List[QuarelWorld]``\n We use a ``MetadataField`` to get the ``World`` for each input instance. Because of\n how ``MetadataField`` works, this gets passed to us as a ``List[QuarelWorld]``,\n actions : ``List[List[ProductionRule]]``\n A list of all possible actions for each ``World`` in the batch, indexed into a\n ``ProductionRule`` using a ``ProductionRuleField``. We will embed all of these\n and use the embeddings to determine which action to take at each timestep in the\n decoder.\n entity_bits : ``torch.Tensor``, optional (default=None)\n Tensor encoding bits for the world entities.\n denotation_target : ``torch.Tensor``, optional (default=None)\n If model's field ``denotation_only`` is True, this is the tensor target denotation.\n target_action_sequences : torch.Tensor, optional (default=None)\n A list of possibly valid action sequences, where each action is an index into the list\n of possible actions. This tensor has shape ``(batch_size, num_action_sequences,\n sequence_length)``.\n metadata : List[Dict[str, Any]], optional (default=None).\n A dictionary of metadata for each batch element which has keys:\n question_tokens : ``List[str]``, optional.\n The original string tokens in the question.\n world_extractions : ``nltk.Tree``, optional.\n Extracted worlds from the question.\n answer_index : ``List[str]``, optional.\n Index of the correct answer.\n \"\"\"\n\n table_text = table['text']\n\n self._debug_count -= 1\n\n # (batch_size, question_length, embedding_dim)\n embedded_question = self._question_embedder(question)\n question_mask = util.get_text_field_mask(question).float()\n num_question_tokens = embedded_question.size(1)\n\n # (batch_size, num_entities, num_entity_tokens, embedding_dim)\n embedded_table = self._question_embedder(table_text, num_wrapping_dims=1)\n\n batch_size, num_entities, num_entity_tokens, _ = embedded_table.size()\n\n # entity_types: one-hot tensor with shape (batch_size, num_entities, num_types)\n # entity_type_dict: Dict[int, int], mapping flattened_entity_index -> type_index\n # These encode the same information, but for efficiency reasons later it's nice\n # to have one version as a tensor and one that's accessible on the cpu.\n entity_types, entity_type_dict = self._get_type_vector(world, num_entities, embedded_table)\n\n if self._use_entities:\n\n if self._entity_similarity_mode == \"dot_product\":\n # Compute entity and question word cosine similarity. Need to add a small value to\n # to the table norm since there are padding values which cause a divide by 0.\n embedded_table = embedded_table / (embedded_table.norm(dim=-1, keepdim=True) + 1e-13)\n embedded_question = embedded_question / (embedded_question.norm(dim=-1, keepdim=True) + 1e-13)\n question_entity_similarity = torch.bmm(embedded_table.view(batch_size,\n num_entities * num_entity_tokens,\n self._embedding_dim),\n torch.transpose(embedded_question, 1, 2))\n\n question_entity_similarity = question_entity_similarity.view(batch_size,\n num_entities,\n num_entity_tokens,\n num_question_tokens)\n\n # (batch_size, num_entities, num_question_tokens)\n question_entity_similarity_max_score, _ = torch.max(question_entity_similarity, 2)\n\n linking_scores = question_entity_similarity_max_score\n elif self._entity_similarity_mode == \"weighted_dot_product\":\n embedded_table = embedded_table / (embedded_table.norm(dim=-1, keepdim=True) + 1e-13)\n embedded_question = embedded_question / (embedded_question.norm(dim=-1, keepdim=True) + 1e-13)\n eqe = embedded_question.unsqueeze(1).expand(-1, num_entities*num_entity_tokens, -1, -1)\n ete = embedded_table.view(batch_size, num_entities*num_entity_tokens, self._embedding_dim)\n ete = ete.unsqueeze(2).expand(-1, -1, num_question_tokens, -1)\n product = torch.mul(eqe, ete)\n product = product.view(batch_size,\n num_question_tokens*num_entities*num_entity_tokens,\n self._embedding_dim)\n question_entity_similarity = self._entity_similarity_layer(product)\n question_entity_similarity = question_entity_similarity.view(batch_size,\n num_entities,\n num_entity_tokens,\n num_question_tokens)\n\n # (batch_size, num_entities, num_question_tokens)\n question_entity_similarity_max_score, _ = torch.max(question_entity_similarity, 2)\n linking_scores = question_entity_similarity_max_score\n\n # (batch_size, num_entities, num_question_tokens, num_features)\n linking_features = table['linking']\n\n if self._linking_params is not None:\n feature_scores = self._linking_params(linking_features).squeeze(3)\n linking_scores = linking_scores + feature_scores\n\n # (batch_size, num_question_tokens, num_entities)\n linking_probabilities = self._get_linking_probabilities(world, linking_scores.transpose(1, 2),\n question_mask, entity_type_dict)\n encoder_input = embedded_question\n else:\n if entity_bits is not None and not self._entity_bits_output:\n encoder_input = torch.cat([embedded_question, entity_bits], 2)\n else:\n encoder_input = embedded_question\n\n # Fake linking_scores added for downstream code to not object\n linking_scores = question_mask.clone().fill_(0).unsqueeze(1)\n linking_probabilities = None\n\n # (batch_size, question_length, encoder_output_dim)\n encoder_outputs = self._dropout(self._encoder(encoder_input, question_mask))\n\n if self._entity_bits_output and entity_bits is not None:\n encoder_outputs = torch.cat([encoder_outputs, entity_bits], 2)\n\n # This will be our initial hidden state and memory cell for the decoder LSTM.\n final_encoder_output = util.get_final_encoder_states(encoder_outputs,\n question_mask,\n self._encoder.is_bidirectional())\n # For predicting a categorical denotation directly\n if self._denotation_only:\n denotation_logits = self._denotation_classifier(final_encoder_output)\n loss = torch.nn.functional.cross_entropy(denotation_logits, denotation_target.view(-1))\n self._denotation_accuracy_cat(denotation_logits, denotation_target)\n return {\"loss\": loss}\n\n memory_cell = encoder_outputs.new_zeros(batch_size, self._encoder_output_dim)\n\n _, num_entities, num_question_tokens = linking_scores.size()\n\n if target_action_sequences is not None:\n # Remove the trailing dimension (from ListField[ListField[IndexField]]).\n target_action_sequences = target_action_sequences.squeeze(-1)\n target_mask = target_action_sequences != self._action_padding_index\n else:\n target_mask = None\n\n # To make grouping states together in the decoder easier, we convert the batch dimension in\n # all of our tensors into an outer list. For instance, the encoder outputs have shape\n # `(batch_size, question_length, encoder_output_dim)`. We need to convert this into a list\n # of `batch_size` tensors, each of shape `(question_length, encoder_output_dim)`. Then we\n # won't have to do any index selects, or anything, we'll just do some `torch.cat()`s.\n encoder_output_list = [encoder_outputs[i] for i in range(batch_size)]\n question_mask_list = [question_mask[i] for i in range(batch_size)]\n initial_rnn_state = []\n\n for i in range(batch_size):\n initial_rnn_state.append(RnnStatelet(final_encoder_output[i],\n memory_cell[i],\n self._first_action_embedding,\n self._first_attended_question,\n encoder_output_list,\n question_mask_list))\n\n initial_grammar_state = [self._create_grammar_state(world[i], actions[i],\n linking_scores[i], entity_types[i])\n for i in range(batch_size)]\n\n initial_score = initial_rnn_state[0].hidden_state.new_zeros(batch_size)\n initial_score_list = [initial_score[i] for i in range(batch_size)]\n initial_state = GrammarBasedState(batch_indices=list(range(batch_size)),\n action_history=[[] for _ in range(batch_size)],\n score=initial_score_list,\n rnn_state=initial_rnn_state,\n grammar_state=initial_grammar_state,\n possible_actions=actions,\n extras=None,\n debug_info=None)\n\n if self.training:\n outputs = self._decoder_trainer.decode(initial_state,\n self._decoder_step,\n (target_action_sequences, target_mask))\n return outputs\n\n else:\n action_mapping = {}\n for batch_index, batch_actions in enumerate(actions):\n for action_index, action in enumerate(batch_actions):\n action_mapping[(batch_index, action_index)] = action[0]\n outputs = {'action_mapping': action_mapping}\n if target_action_sequences is not None:\n outputs['loss'] = self._decoder_trainer.decode(initial_state,\n self._decoder_step,\n (target_action_sequences, target_mask))['loss']\n\n num_steps = self._max_decoding_steps\n # This tells the state to start keeping track of debug info, which we'll pass along in\n # our output dictionary.\n initial_state.debug_info = [[] for _ in range(batch_size)]\n best_final_states = self._beam_search.search(num_steps,\n initial_state,\n self._decoder_step,\n keep_final_unfinished_states=False)\n outputs['best_action_sequence'] = []\n outputs['debug_info'] = []\n outputs['entities'] = []\n if self._linking_params is not None:\n outputs['linking_scores'] = linking_scores\n outputs['feature_scores'] = feature_scores\n outputs['linking_features'] = linking_features\n if self._use_entities:\n outputs['linking_probabilities'] = linking_probabilities\n if entity_bits is not None:\n outputs['entity_bits'] = entity_bits\n # outputs['similarity_scores'] = question_entity_similarity_max_score\n outputs['logical_form'] = []\n outputs['denotation_acc'] = []\n outputs['score'] = []\n outputs['parse_acc'] = []\n outputs['answer_index'] = []\n if metadata is not None:\n outputs['question_tokens'] = []\n outputs['world_extractions'] = []\n for i in range(batch_size):\n if metadata is not None:\n outputs['question_tokens'].append(metadata[i].get('question_tokens', []))\n if metadata is not None:\n outputs['world_extractions'].append(metadata[i].get('world_extractions', {}))\n outputs['entities'].append(world[i].table_graph.entities)\n # Decoding may not have terminated with any completed logical forms, if `num_steps`\n # isn't long enough (or if the model is not trained enough and gets into an\n # infinite action loop).\n if i in best_final_states:\n best_action_indices = best_final_states[i][0].action_history[0]\n sequence_in_targets = 0\n if target_action_sequences is not None:\n targets = target_action_sequences[i].data\n sequence_in_targets = self._action_history_match(best_action_indices, targets)\n self._action_sequence_accuracy(sequence_in_targets)\n action_strings = [action_mapping[(i, action_index)] for action_index in best_action_indices]\n try:\n self._has_logical_form(1.0)\n logical_form = world[i].get_logical_form(action_strings, add_var_function=False)\n except ParsingError:\n self._has_logical_form(0.0)\n logical_form = 'Error producing logical form'\n denotation_accuracy = 0.0\n predicted_answer_index = world[i].execute(logical_form)\n if metadata is not None and 'answer_index' in metadata[i]:\n answer_index = metadata[i]['answer_index']\n denotation_accuracy = self._denotation_match(predicted_answer_index, answer_index)\n self._denotation_accuracy(denotation_accuracy)\n score = math.exp(best_final_states[i][0].score[0].data.cpu().item())\n outputs['answer_index'].append(predicted_answer_index)\n outputs['score'].append(score)\n outputs['parse_acc'].append(sequence_in_targets)\n outputs['best_action_sequence'].append(action_strings)\n outputs['logical_form'].append(logical_form)\n outputs['denotation_acc'].append(denotation_accuracy)\n outputs['debug_info'].append(best_final_states[i][0].debug_info[0]) # type: ignore\n else:\n outputs['parse_acc'].append(0)\n outputs['logical_form'].append('')\n outputs['denotation_acc'].append(0)\n outputs['score'].append(0)\n outputs['answer_index'].append(-1)\n outputs['best_action_sequence'].append([])\n outputs['debug_info'].append([])\n self._has_logical_form(0.0)\n return outputs\n\n @staticmethod\n def _get_type_vector(worlds: List[QuarelWorld],\n num_entities: int,\n tensor: torch.Tensor) -> Tuple[torch.LongTensor, Dict[int, int]]:\n \"\"\"\n Produces a tensor with shape ``(batch_size, num_entities)`` that encodes each entity's\n type. In addition, a map from a flattened entity index to type is returned to combine\n entity type operations into one method.\n\n Parameters\n ----------\n worlds : ``List[WikiTablesWorld]``\n num_entities : ``int``\n tensor : ``torch.Tensor``\n Used for copying the constructed list onto the right device.\n\n Returns\n -------\n A ``torch.LongTensor`` with shape ``(batch_size, num_entities)``.\n entity_types : ``Dict[int, int]``\n This is a mapping from ((batch_index * num_entities) + entity_index) to entity type id.\n \"\"\"\n entity_types = {}\n batch_types = []\n for batch_index, world in enumerate(worlds):\n types = []\n for entity_index, entity in enumerate(world.table_graph.entities):\n # We need numbers to be first, then cells, then parts, then row, because our\n # entities are going to be sorted. We do a split by type and then a merge later,\n # and it relies on this sorting.\n if entity.startswith('fb:cell'):\n entity_type = 1\n elif entity.startswith('fb:part'):\n entity_type = 2\n elif entity.startswith('fb:row'):\n entity_type = 3\n else:\n entity_type = 0\n types.append(entity_type)\n\n # For easier lookups later, we're actually using a _flattened_ version\n # of (batch_index, entity_index) for the key, because this is how the\n # linking scores are stored.\n flattened_entity_index = batch_index * num_entities + entity_index\n entity_types[flattened_entity_index] = entity_type\n padded = pad_sequence_to_length(types, num_entities, lambda: 0)\n batch_types.append(padded)\n return tensor.new_tensor(batch_types, dtype=torch.long), entity_types\n\n def _get_linking_probabilities(self,\n worlds: List[QuarelWorld],\n linking_scores: torch.FloatTensor,\n question_mask: torch.LongTensor,\n entity_type_dict: Dict[int, int]) -> torch.FloatTensor:\n \"\"\"\n Produces the probability of an entity given a question word and type. The logic below\n separates the entities by type since the softmax normalization term sums over entities\n of a single type.\n\n Parameters\n ----------\n worlds : ``List[QuarelWorld]``\n linking_scores : ``torch.FloatTensor``\n Has shape (batch_size, num_question_tokens, num_entities).\n question_mask: ``torch.LongTensor``\n Has shape (batch_size, num_question_tokens).\n entity_type_dict : ``Dict[int, int]``\n This is a mapping from ((batch_index * num_entities) + entity_index) to entity type id.\n\n Returns\n -------\n batch_probabilities : ``torch.FloatTensor``\n Has shape ``(batch_size, num_question_tokens, num_entities)``.\n Contains all the probabilities for an entity given a question word.\n \"\"\"\n _, num_question_tokens, num_entities = linking_scores.size()\n batch_probabilities = []\n\n for batch_index, world in enumerate(worlds):\n all_probabilities = []\n num_entities_in_instance = 0\n\n # NOTE: The way that we're doing this here relies on the fact that entities are\n # implicitly sorted by their types when we sort them by name, and that numbers come\n # before \"fb:cell\", and \"fb:cell\" comes before \"fb:row\". This is not a great\n # assumption, and could easily break later, but it should work for now.\n for type_index in range(self._num_entity_types):\n # This index of 0 is for the null entity for each type, representing the case where a\n # word doesn't link to any entity.\n entity_indices = [0]\n entities = world.table_graph.entities\n for entity_index, _ in enumerate(entities):\n if entity_type_dict[batch_index * num_entities + entity_index] == type_index:\n entity_indices.append(entity_index)\n\n if len(entity_indices) == 1:\n # No entities of this type; move along...\n continue\n\n # We're subtracting one here because of the null entity we added above.\n num_entities_in_instance += len(entity_indices) - 1\n\n # We separate the scores by type, since normalization is done per type. There's an\n # extra \"null\" entity per type, also, so we have `num_entities_per_type + 1`. We're\n # selecting from a (num_question_tokens, num_entities) linking tensor on _dimension 1_,\n # so we get back something of shape (num_question_tokens,) for each index we're\n # selecting. All of the selected indices together then make a tensor of shape\n # (num_question_tokens, num_entities_per_type + 1).\n indices = linking_scores.new_tensor(entity_indices, dtype=torch.long)\n entity_scores = linking_scores[batch_index].index_select(1, indices)\n\n # We used index 0 for the null entity, so this will actually have some values in it.\n # But we want the null entity's score to be 0, so we set that here.\n entity_scores[:, 0] = 0\n\n # No need for a mask here, as this is done per batch instance, with no padding.\n type_probabilities = torch.nn.functional.softmax(entity_scores, dim=1)\n all_probabilities.append(type_probabilities[:, 1:])\n\n # We need to add padding here if we don't have the right number of entities.\n if num_entities_in_instance != num_entities:\n zeros = linking_scores.new_zeros(num_question_tokens,\n num_entities - num_entities_in_instance)\n all_probabilities.append(zeros)\n\n # (num_question_tokens, num_entities)\n probabilities = torch.cat(all_probabilities, dim=1)\n batch_probabilities.append(probabilities)\n batch_probabilities = torch.stack(batch_probabilities, dim=0)\n return batch_probabilities * question_mask.unsqueeze(-1).float()\n\n @staticmethod\n def _action_history_match(predicted: List[int], targets: torch.LongTensor) -> int:\n # TODO(mattg): this could probably be moved into a FullSequenceMatch metric, or something.\n # Check if target is big enough to cover prediction (including start/end symbols)\n if len(predicted) > targets.size(1):\n return 0\n predicted_tensor = targets.new_tensor(predicted)\n targets_trimmed = targets[:, :len(predicted)]\n # Return 1 if the predicted sequence is anywhere in the list of targets.\n return torch.max(torch.min(targets_trimmed.eq(predicted_tensor), dim=1)[0]).item()\n\n def _denotation_match(self, predicted_answer_index: int, target_answer_index: int) -> float:\n if predicted_answer_index < 0:\n # Logical form doesn't properly resolve, we do random guess with appropriate credit\n return 1.0/self._num_denotation_cats\n elif predicted_answer_index == target_answer_index:\n return 1.0\n return 0.0\n\n @overrides\n def get_metrics(self, reset: bool = False) -> Dict[str, float]:\n \"\"\"\n We track three metrics here:\n\n 1. parse_acc, which is the percentage of the time that our best output action sequence\n corresponds to a correct logical form\n\n 2. denotation_acc, which is the percentage of examples where we get the correct\n denotation, including spurious correct answers using the wrong logical form\n\n 3. lf_percent, which is the percentage of time that decoding actually produces a\n finished logical form. We might not produce a valid logical form if the decoder gets\n into a repetitive loop, or we're trying to produce a super long logical form and run\n out of time steps, or something.\n \"\"\"\n if self._denotation_only:\n metrics = {'denotation_acc': self._denotation_accuracy_cat.get_metric(reset)}\n else:\n metrics = {\n 'parse_acc': self._action_sequence_accuracy.get_metric(reset),\n 'denotation_acc': self._denotation_accuracy.get_metric(reset),\n 'lf_percent': self._has_logical_form.get_metric(reset),\n }\n return metrics\n\n def _create_grammar_state(self,\n world: QuarelWorld,\n possible_actions: List[ProductionRule],\n linking_scores: torch.Tensor,\n entity_types: torch.Tensor) -> GrammarStatelet:\n \"\"\"\n This method creates the GrammarStatelet object that's used for decoding. Part of creating\n that is creating the `valid_actions` dictionary, which contains embedded representations of\n all of the valid actions. So, we create that here as well.\n\n The inputs to this method are for a `single instance in the batch`; none of the tensors we\n create here are batched. We grab the global action ids from the input\n ``ProductionRules``, and we use those to embed the valid actions for every\n non-terminal type. We use the input ``linking_scores`` for non-global actions.\n\n Parameters\n ----------\n world : ``QuarelWorld``\n From the input to ``forward`` for a single batch instance.\n possible_actions : ``List[ProductionRule]``\n From the input to ``forward`` for a single batch instance.\n linking_scores : ``torch.Tensor``\n Assumed to have shape ``(num_entities, num_question_tokens)`` (i.e., there is no batch\n dimension).\n entity_types : ``torch.Tensor``\n Assumed to have shape ``(num_entities,)`` (i.e., there is no batch dimension).\n \"\"\"\n action_map = {}\n for action_index, action in enumerate(possible_actions):\n action_string = action[0]\n action_map[action_string] = action_index\n entity_map = {}\n for entity_index, entity in enumerate(world.table_graph.entities):\n entity_map[entity] = entity_index\n\n valid_actions = world.get_valid_actions()\n translated_valid_actions: Dict[str, Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]] = {}\n for key, action_strings in valid_actions.items():\n translated_valid_actions[key] = {}\n # `key` here is a non-terminal from the grammar, and `action_strings` are all the valid\n # productions of that non-terminal. We'll first split those productions by global vs.\n # linked action.\n action_indices = [action_map[action_string] for action_string in action_strings]\n production_rule_arrays = [(possible_actions[index], index) for index in action_indices]\n global_actions = []\n linked_actions = []\n for production_rule_array, action_index in production_rule_arrays:\n if production_rule_array[1]:\n global_actions.append((production_rule_array[2], action_index))\n else:\n linked_actions.append((production_rule_array[0], action_index))\n\n # Then we get the embedded representations of the global actions.\n global_action_tensors, global_action_ids = zip(*global_actions)\n global_action_tensor = torch.cat(global_action_tensors, dim=0)\n global_input_embeddings = self._action_embedder(global_action_tensor)\n if self._add_action_bias:\n global_action_biases = self._action_biases(global_action_tensor)\n global_input_embeddings = torch.cat([global_input_embeddings, global_action_biases], dim=-1)\n global_output_embeddings = self._output_action_embedder(global_action_tensor)\n translated_valid_actions[key]['global'] = (global_input_embeddings,\n global_output_embeddings,\n list(global_action_ids))\n\n # Then the representations of the linked actions.\n if linked_actions:\n linked_rules, linked_action_ids = zip(*linked_actions)\n entities = [rule.split(' -> ')[1] for rule in linked_rules]\n entity_ids = [entity_map[entity] for entity in entities]\n # (num_linked_actions, num_question_tokens)\n entity_linking_scores = linking_scores[entity_ids]\n # (num_linked_actions,)\n entity_type_tensor = entity_types[entity_ids]\n # (num_linked_actions, entity_type_embedding_dim)\n entity_type_embeddings = self._entity_type_decoder_embedding(entity_type_tensor)\n translated_valid_actions[key]['linked'] = (entity_linking_scores,\n entity_type_embeddings,\n list(linked_action_ids))\n\n return GrammarStatelet([START_SYMBOL],\n translated_valid_actions,\n type_declaration.is_nonterminal)\n\n @overrides\n def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:\n \"\"\"\n This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test\n time, to finalize predictions. This is (confusingly) a separate notion from the \"decoder\"\n in \"encoder/decoder\", where that decoder logic lives in ``FrictionQDecoderStep``.\n\n This method trims the output predictions to the first end symbol, replaces indices with\n corresponding tokens, and adds a field called ``predicted_tokens`` to the ``output_dict``.\n \"\"\"\n action_mapping = output_dict['action_mapping']\n best_actions = output_dict[\"best_action_sequence\"]\n debug_infos = output_dict['debug_info']\n batch_action_info = []\n for batch_index, (predicted_actions, debug_info) in enumerate(zip(best_actions, debug_infos)):\n instance_action_info = []\n for predicted_action, action_debug_info in zip(predicted_actions, debug_info):\n action_info = {}\n action_info['predicted_action'] = predicted_action\n considered_actions = action_debug_info['considered_actions']\n probabilities = action_debug_info['probabilities']\n actions = []\n for action, probability in zip(considered_actions, probabilities):\n if action != -1:\n actions.append((action_mapping[(batch_index, action)], probability))\n actions.sort()\n considered_actions, probabilities = zip(*actions)\n action_info['considered_actions'] = considered_actions\n action_info['action_probabilities'] = probabilities\n action_info['question_attention'] = action_debug_info.get('question_attention', [])\n instance_action_info.append(action_info)\n batch_action_info.append(instance_action_info)\n output_dict[\"predicted_actions\"] = batch_action_info\n return output_dict\n" ]
[ [ "numpy.array" ], [ "torch.cat", "torch.sqrt", "torch.sum", "torch.FloatTensor", "torch.split" ], [ "numpy.testing.assert_almost_equal", "torch.FloatTensor", "torch.ones" ], [ "torch.nn.Dropout", "torch.nn.functional.softmax", "torch.transpose", "torch.max", "torch.cat", "torch.nn.Linear", "torch.mul", "torch.FloatTensor", "torch.nn.init.normal_", "torch.stack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
andrewliao11/Andrew_tensorpack
[ "735a2672e3d93b5b612a303b5b6d222e9b2d4280" ]
[ "tensorpack/dataflow/dataset/ilsvrc.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# File: ilsvrc.py\n# Author: Yuxin Wu <[email protected]>\nimport os\nimport tarfile\nimport cv2\nimport numpy as np\nfrom six.moves import range\nimport xml.etree.ElementTree as ET\n\nfrom ...utils import logger, get_rng, get_dataset_path\nfrom ...utils.loadcaffe import get_caffe_pb\nfrom ...utils.fs import mkdir_p, download\nfrom ...utils.timer import timed_operation\nfrom ..base import RNGDataFlow\n\n__all__ = ['ILSVRCMeta', 'ILSVRC12']\n\nCAFFE_ILSVRC12_URL = \"http://dl.caffe.berkeleyvision.org/caffe_ilsvrc12.tar.gz\"\n\nclass ILSVRCMeta(object):\n \"\"\"\n Some metadata for ILSVRC dataset.\n \"\"\"\n def __init__(self, dir=None):\n if dir is None:\n dir = get_dataset_path('ilsvrc_metadata')\n self.dir = dir\n mkdir_p(self.dir)\n self.caffepb = get_caffe_pb()\n f = os.path.join(self.dir, 'synsets.txt')\n if not os.path.isfile(f):\n self._download_caffe_meta()\n\n def get_synset_words_1000(self):\n \"\"\"\n :returns a dict of {cls_number: cls_name}\n \"\"\"\n fname = os.path.join(self.dir, 'synset_words.txt')\n assert os.path.isfile(fname)\n lines = [x.strip() for x in open(fname).readlines()]\n return dict(enumerate(lines))\n\n def get_synset_1000(self):\n \"\"\"\n :returns a dict of {cls_number: synset_id}\n \"\"\"\n fname = os.path.join(self.dir, 'synsets.txt')\n assert os.path.isfile(fname)\n lines = [x.strip() for x in open(fname).readlines()]\n return dict(enumerate(lines))\n\n def _download_caffe_meta(self):\n fpath = download(CAFFE_ILSVRC12_URL, self.dir)\n tarfile.open(fpath, 'r:gz').extractall(self.dir)\n\n def get_image_list(self, name):\n \"\"\"\n :param name: 'train' or 'val' or 'test'\n :returns: list of (image filename, cls)\n \"\"\"\n assert name in ['train', 'val', 'test']\n fname = os.path.join(self.dir, name + '.txt')\n assert os.path.isfile(fname)\n with open(fname) as f:\n ret = []\n for line in f.readlines():\n name, cls = line.strip().split()\n ret.append((name, int(cls)))\n assert len(ret)\n return ret\n\n def get_per_pixel_mean(self, size=None):\n \"\"\"\n :param size: return image size in [h, w]. default to (256, 256)\n :returns: per-pixel mean as an array of shape (h, w, 3) in range [0, 255]\n \"\"\"\n obj = self.caffepb.BlobProto()\n\n mean_file = os.path.join(self.dir, 'imagenet_mean.binaryproto')\n with open(mean_file, 'rb') as f:\n obj.ParseFromString(f.read())\n arr = np.array(obj.data).reshape((3, 256, 256)).astype('float32')\n arr = np.transpose(arr, [1,2,0])\n if size is not None:\n arr = cv2.resize(arr, size[::-1])\n return arr\n\nclass ILSVRC12(RNGDataFlow):\n def __init__(self, dir, name, meta_dir=None, shuffle=True,\n dir_structure='original', include_bb=False):\n \"\"\"\n :param dir: A directory containing a subdir named `name`, where the\n original ILSVRC12_`name`.tar gets decompressed.\n :param name: 'train' or 'val' or 'test'\n :param dir_structure: The dir structure of 'val' and 'test'.\n If is 'original' then keep the original decompressed directory with list\n of image files (as below). If set to 'train', use the the same\n directory structure as 'train/', with class name as subdirectories.\n :param include_bb: Include the bounding box. Maybe useful in training.\n\n When `dir_structure=='original'`, `dir` should have the following structure:\n\n .. code-block:: none\n\n dir/\n train/\n n02134418/\n n02134418_198.JPEG\n ...\n ...\n val/\n ILSVRC2012_val_00000001.JPEG\n ...\n test/\n ILSVRC2012_test_00000001.JPEG\n ...\n bbox/\n n02134418/\n n02134418_198.xml\n ...\n ...\n\n After decompress ILSVRC12_img_train.tar, you can use the following\n command to build the above structure for `train/`:\n\n .. code-block:: none\n\n tar xvf ILSVRC12_img_train.tar -C train && cd train\n find -type f -name '*.tar' | parallel -P 10 'echo {} && mkdir -p {/.} && tar xf {} -C {/.}'\n Or:\n for i in *.tar; do dir=${i%.tar}; echo $dir; mkdir -p $dir; tar xf $i -C $dir; done\n\n \"\"\"\n assert name in ['train', 'test', 'val']\n self.full_dir = os.path.join(dir, name)\n self.name = name\n assert os.path.isdir(self.full_dir), self.full_dir\n self.shuffle = shuffle\n meta = ILSVRCMeta(meta_dir)\n self.imglist = meta.get_image_list(name)\n self.dir_structure = dir_structure\n self.synset = meta.get_synset_1000()\n\n if include_bb:\n bbdir = os.path.join(dir, 'bbox') if not \\\n isinstance(include_bb, six.string_types) else include_bb\n assert name == 'train', 'Bounding box only available for training'\n self.bblist = ILSVRC12.get_training_bbox(bbdir, self.imglist)\n self.include_bb = include_bb\n\n def size(self):\n return len(self.imglist)\n\n def get_data(self):\n \"\"\"\n Produce original images of shape [h, w, 3(BGR)], and label,\n and optionally a bbox of [xmin, ymin, xmax, ymax]\n \"\"\"\n idxs = np.arange(len(self.imglist))\n add_label_to_fname = (self.name != 'train' and self.dir_structure != 'original')\n if self.shuffle:\n self.rng.shuffle(idxs)\n for k in idxs:\n fname, label = self.imglist[k]\n if add_label_to_fname:\n fname = os.path.join(self.full_dir, self.synset[label], fname)\n else:\n fname = os.path.join(self.full_dir, fname)\n im = cv2.imread(fname.strip(), cv2.IMREAD_COLOR)\n assert im is not None, fname\n if im.ndim == 2:\n im = np.expand_dims(im, 2).repeat(3,2)\n if self.include_bb:\n bb = self.bblist[k]\n if bb is None:\n bb = [0, 0, im.shape[1]-1, im.shape[0]-1]\n yield [im, label, bb]\n else:\n yield [im, label]\n\n @staticmethod\n def get_training_bbox(bbox_dir, imglist):\n ret = []\n\n def parse_bbox(fname):\n root = ET.parse(fname).getroot()\n size = root.find('size').getchildren()\n size = map(int, [size[0].text, size[1].text])\n\n box = root.find('object').find('bndbox').getchildren()\n box = map(lambda x: float(x.text), box)\n #box[0] /= size[0]\n #box[1] /= size[1]\n #box[2] /= size[0]\n #box[3] /= size[1]\n return np.asarray(box, dtype='float32')\n\n with timed_operation('Loading Bounding Boxes ...'):\n cnt = 0\n import tqdm\n for k in tqdm.trange(len(imglist)):\n fname = imglist[k][0]\n fname = fname[:-4] + 'xml'\n fname = os.path.join(bbox_dir, fname)\n try:\n ret.append(parse_bbox(fname))\n cnt += 1\n except KeyboardInterrupt:\n raise\n except:\n ret.append(None)\n logger.info(\"{}/{} images have bounding box.\".format(cnt, len(imglist)))\n return ret\n\nif __name__ == '__main__':\n meta = ILSVRCMeta()\n #print(meta.get_synset_words_1000())\n\n ds = ILSVRC12('/home/wyx/data/fake_ilsvrc/', 'train', include_bb=True,\n shuffle=False)\n ds.reset_state()\n\n for k in ds.get_data():\n from IPython import embed; embed()\n break\n" ]
[ [ "numpy.asarray", "numpy.array", "numpy.expand_dims", "numpy.transpose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
droyston/spectralize
[ "572770e7358acc3ec433470659759c17453409f2" ]
[ "app/clean_test_app.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 18 18:54:48 2020\n\n@author: dylanroyston\n\"\"\"\n\n\n# -*- coding: utf-8 -*-\n\n# import packages\n#import dash_player\nimport dash\nimport dash_table\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\nimport psycopg2\nimport os\nimport pandas as pd\nimport numpy as np\nimport plotly\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport librosa\nimport librosa.display as ld\nimport IPython.display as ipd\nimport pylab as pl\nimport boto3\n#import matplotlib as mpl\n#import matplotlib.pyplot as plt\n#from matplotlib import cm\n#from colorspacious import cspace_converter\n#from collections import OrderedDict\n\n######\n\n\n# connect to PSQL and retrieve \npsql_usr = os.environ.get('PSQL_USR')\npsql_pw = os.environ.get('PSQL_PW')\n\nconn = psycopg2.connect(host = 'ec2-13-58-251-142.us-east-2.compute.amazonaws.com',\n dbname = 'spectralize',\n user='postgres',\n password=psql_pw)\n\n\n\n##### read out metadata\nmetadata = conn.cursor()\n\nmetadata.execute(\"SELECT * FROM clean_metadata WHERE false;\")\ncols = set(metadata.fetchall())\n\nmetadata.execute(\"SELECT * FROM clean_metadata;\")\nmd = set(metadata.fetchall())\n\ncols = [\"s3_key\", \"song_id\", \"album\", \"albumartist\", \"artist\", \n \"audio_offset\", \"bitrate\", \"channels\", \"comment\", \"composer\",\n \"disc\", \"disc_total\", \"duration\", \"filesize\", \"genre\",\n \"samplerate\", \"title\", \"track\", \"track_total\", \"year\"]\n\ntag_df = pd.DataFrame(data=md, columns=cols)\n\n\n\n\n##### s3 acess for playing audio files\ns3_bucket = 'mdp-spectralize-pal'\nnumber_of_files = 0\ns3 = boto3.resource('s3')\nbucket = s3.Bucket(s3_bucket)\n \n# placeholders for callback initialization\nstandin_fp = '/home/dylanroyston/Documents/GIT/spectralize/app/hello.wav'\naudio_sd_file = standin_fp\n#audio_rawfile, new_sr = librosa.load(standin_fp, sr=None)\nstandin_data = np.array([[0,0],[0,0]])\nstandin_df = pd.DataFrame(standin_data, columns=['x','y'])\n#audio_fig = px.line(standin_df, x='x', y='y', title='audio data', render_mode='webgl')\nspec_fig = px.imshow(standin_df)\n\ndef load_audio_data(selected_row):\n # read out audio data\n \n #curr_song_id = tag_df.iloc[selected_row]['song_id']\n curr_song_id = selected_row\n \n # audiodata = conn.cursor()\n \n # qstring = 'SELECT intensity FROM clean_audio WHERE song_id=' + str(curr_song_id)\n \n # audiodata.execute(qstring)\n # ad = np.array(audiodata.fetchall())\n \n # audio_df = pd.DataFrame(data=ad, columns=['I'])\n # audio_fig = px.line(audio_df, x=audio_df.index, y='I', title='audio data', render_mode='webgl')\n # audio_fig.update_layout(\n # height=250,\n # margin_r=0,\n # margin_l=0,\n # margin_t=0,\n # yaxis_title='',\n # yaxis_fixedrange=True)\n \n\n s3_key = tag_df.iloc[curr_song_id]['s3_key']\n \n #this_row = tag_df.loc[tag_df['song_id'] == curr_song_id]\n #s3_key = tag_df.iloc[this_row]['s3_key']\n \n ext = s3_key[-4:]\n audio_sd_file = '/home/dylanroyston/Documents/GIT/spectralize/app/audio_file' + ext\n \n bucket.download_file(s3_key, audio_sd_file) \n \n #audio_rawfile = librosa.load(audio_sd_file)\n \n \n \n return audio_sd_file#, audio_fig\n\ndef load_spec_data(selected_row):\n \n curr_song_id = selected_row\n \n specdata = conn.cursor()\n qstring = 'SELECT * FROM clean_spec WHERE song_id=' + str(curr_song_id)\n specdata.execute(qstring)\n sd = np.array(specdata.fetchall())\n \n spec_df = pd.DataFrame(data=sd)\n \n #currtitle = tag_df.iloc[curr_song_id]['title']\n #currdur = tag_df.iloc[curr_song_id]['duration'] \n \n\n # numpts = len(sd)\n \n # interval = float(currdur) / numpts\n \n # timeline = np.linspace(0,float(currdur),numpts)\n \n # rt = timeline.round(0)\n\n trim_sd = spec_df.iloc[:,2:]\n spec_fig = px.imshow(trim_sd.transpose(),\n origin='lower',\n #title=currtitle,\n #x=timeline\n )\n spec_fig.update_layout(\n height=250,\n margin_r=0,\n margin_l=0,\n margin_t=0,\n yaxis_title='Frequency',\n xaxis_title='Time',\n #colorbar.title='power',\n yaxis_fixedrange=True,\n #x=str(rt)\n #title=currtitle\n )\n \n return spec_fig\n\n\n#####\n# initialize Dash app \nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\napp.layout = html.Div(children=[\n \n # header\n html.H1(children='Metadata'),\n \n # metadata table\n dash_table.DataTable(\n id = 'metadata_table',\n data=tag_df.to_dict('rows'),\n columns=[{'id': c, 'name': c} for c in tag_df.columns],\n style_cell={\n 'overflowX': 'auto',\n 'overflow': 'hidden',\n 'textOverflow': 'ellipsis',\n 'maxWidth': 10,\n 'row_selectable': 'single',\n 'font_family': 'Arial',\n 'font_size': '1.5rem',\n 'padding': '.5rem',\n 'backgroundColor': '#f4f4f2'\n },\n style_cell_conditional=[\n {'textAlign': 'center'}\n ],\n style_header={\n 'backgroundColor':'#f4f4f2',\n 'fontWeight': 'bold',\n 'overflowX': 'auto',\n 'textOverflow': 'ellipsis'\n },\n style_table={\n 'maxHeight':'500px',\n 'overflowX': 'scroll'\n },\n tooltip_data=[\n {\n column: {'value': str(value), 'type': 'markdown'}\n for column, value in row.items()\n } for row in tag_df.to_dict('rows')\n ],\n tooltip_duration=None,\n style_as_list_view=True,\n ),# end table\n \n \n # load audio button\n html.Br(),\n \n html.Div(\n [\n dcc.Input(id='input_songnum', value='input song number', type='number'),\n html.Button('Load audio', \n id='submit-val',\n style={'display': 'inline-block'},\n n_clicks=0),\n html.Div(id='song_input')\n ],\n ),\n \n html.Br(),\n \n \n # html.Audio(id=\"player\", src=audio_sd_file, controls=True, style={\n # \"width\": \"100%\"\n # }), \n # dash_player.DashPlayer(\n # id='player',\n # url='audio_sd_file',\n # controls=True\n # ),\n \n html.Br(),\n \n #dcc.Graph(id='waveform', figure=audio_fig),\n \n html.Br(),\n\n dcc.Graph(id='spect', figure=spec_fig)\n \n])\n##### finish Dash layout\n\n\n\n##### callbacks\n# load-audio button control\n# @app.callback(\n# Output('input_songnum', 'value'),\n# [Input('submit-val', 'n_clicks')]\n# )\n# def retrieve_audio(value):\n# return load_audio_data(value)\n\n\n# @app.callback(\n# Output('waveform', 'figure'),\n# [Input('submit-val', 'n_clicks')]\n# )\n# def update_A_figure(submit_val):\n# audio_fig = load_audio_data(submit_val)\n# return audio_fig\n \n\n## update audio player\n# @app.callback(\n# Output('player', 'src'),\n# [Input('submit-val', 'n_clicks')]\n# )\n# def update_player(submit_val):\n# audio_sd_file = load_audio_data(submit_val)\n# return audio_sd_file\n\n\n\n## update spect figure on button click\[email protected](\n Output('spect', 'figure'),\n [Input('submit-val', 'n_clicks'),\n Input('input_songnum', 'value')]\n )\ndef update_S_figure(n_clicks, value):\n \n changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]\n \n if 'submit-val' in changed_id:\n spec_fig = load_spec_data(value)\n \n return spec_fig\n\n\n\n\n\n## combined audiofile/spec update\n# @app.callback(\n# [Output('player', 'src'),\n# Output('spect', 'figure')],\n# [Input('submit-val', 'n_clicks')]\n# )\n# def update_figures(submit_val):\n# audio_sd_file = load_audio_data(submit_val)\n# spec_fig = load_spec_data(submit_val)\n# return audio_sd_file, spec_fig\n \n\n# @app.callback(\n# Output('metadata_table', 'derived_virtual_selected_rows'),\n# [Input('submit-val', 'n_clicks'),\n# State('metadata_table', 'derived_virtual_selected_rows')]\n# )\n# def update_audio(n_clicks, derived_virtual_selected_rows):\n# if derived_virtual_selected_rows is None:\n# derived_virtual_selected_rows = []\n \n \n# return load_audio_data(derived_virtual_selected_rows)\n\n\nif __name__ == '__main__':\n #app.run_server(debug=True, port=8050, host='127.0.0.1')\n app.run_server(debug=True, port=8050, host='127.0.0.1')\n #app.run_server(debug=True, port=80, host='ec2-18-224-114-72.us-east-2.compute.amazonaws.com')\n" ]
[ [ "numpy.array", "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": [] } ]
SoftwareUnderstanding/inspect4py
[ "9c4d7252535082ad938b26baf281d93f3a27285e", "9c4d7252535082ad938b26baf281d93f3a27285e", "9c4d7252535082ad938b26baf281d93f3a27285e", "9c4d7252535082ad938b26baf281d93f3a27285e", "9c4d7252535082ad938b26baf281d93f3a27285e" ]
[ "test/test_files/pylops/examples/plot_imag.py", "test/test_files/pylops/pytests/test_lsm.py", "test/test_files/pylops/examples/plot_tapers.py", "test/test_files/pylops/pylops/signalprocessing/_Radon2D_numba.py", "test/test_files/pylops/pytests/test_basicoperators.py" ]
[ "\"\"\"\nImag\n====\n\nThis example shows how to use the :py:class:`pylops.basicoperators.Imag`\noperator.\nThis operator returns the imaginary part of the data as a real value in\nforward mode, and the real part of the model as an imaginary value in\nadjoint mode (with zero real part).\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as pltgs\n\nimport pylops\n\nplt.close('all')\n\n###############################################################################\n# Let's define a Imag operator :math:`\\mathbf{\\Im}` to extract the imaginary\n# component of the input.\n\nM = 5\nx = np.arange(M) + 1j * np.arange(M)[::-1]\nRop = pylops.basicoperators.Imag(M, dtype='complex128')\n\ny = Rop*x\nxadj = Rop.H*y\n\n_, axs = plt.subplots(1, 3, figsize=(10, 4))\naxs[0].plot(np.real(x), lw=2, label='Real')\naxs[0].plot(np.imag(x), lw=2, label='Imag')\naxs[0].legend()\naxs[0].set_title('Input')\naxs[1].plot(np.real(y), lw=2, label='Real')\naxs[1].plot(np.imag(y), lw=2, label='Imag')\naxs[1].legend()\naxs[1].set_title('Forward of Input')\naxs[2].plot(np.real(xadj), lw=2, label='Real')\naxs[2].plot(np.imag(xadj), lw=2, label='Imag')\naxs[2].legend()\naxs[2].set_title('Adjoint of Forward')\n", "import pytest\nimport numpy as np\nfrom numpy.testing import assert_array_almost_equal\n\nfrom pylops.utils import dottest\nfrom pylops.utils.wavelets import ricker\nfrom pylops.waveeqprocessing.lsm import _identify_geometry, \\\n _traveltime_table, Demigration, LSM\n\nPAR = {'ny': 10, 'nx': 12, 'nz': 20, 'nt': 50,\n 'dy': 3, 'dx': 1, 'dz': 2, 'dt': 0.004,\n 'nsy': 4, 'nry': 8, 'nsx': 6, 'nrx': 4}\n\nv0 = 500\n\ny = np.arange(PAR['ny']) * PAR['dy']\nx = np.arange(PAR['nx']) * PAR['dx']\nz = np.arange(PAR['nz']) * PAR['dz']\nt = np.arange(PAR['nt']) * PAR['dt']\n\nsy = np.linspace(y.min(), y.max(), PAR['nsy'])\nsx = np.linspace(x.min(), x.max(), PAR['nsx'])\nsyy, sxx = np.meshgrid(sy, sx, indexing='ij')\ns2d = np.vstack((sx, 2 * np.ones(PAR['nsx'])))\ns3d = np.vstack((syy.ravel(), sxx.ravel(),\n 2 * np.ones(PAR['nsx']*PAR['nsy'])))\n\nry = np.linspace(y.min(), y.max(), PAR['nry'])\nrx = np.linspace(x.min(), x.max(), PAR['nrx'])\nryy, rxx = np.meshgrid(ry, rx, indexing='ij')\nr2d = np.vstack((rx, 2 * np.ones(PAR['nrx'])))\nr3d = np.vstack((ryy.ravel(), rxx.ravel(),\n 2 * np.ones(PAR['nrx'] * PAR['nry'])))\n\nwav, _, wavc = ricker(t[:41], f0=40)\n\npar1 = {'mode':'analytic'}\npar2 = {'mode':'eikonal'}\npar3 = {'mode':'byot'}\n\n\ndef test_identify_geometry():\n \"\"\"Identify geometry, check expected outputs\n \"\"\"\n # 2d\n ndims, shiftdim, dims, ny, nx, nz, ns, nr, dy, dx, dz, dsamp, origin = \\\n _identify_geometry(z, x, s2d, r2d)\n assert ndims == 2\n assert shiftdim == 0\n assert [1, 2] == [1, 2]\n assert list(dims) == [PAR['nx'], PAR['nz']]\n assert ny == 1\n assert nx == PAR['nx']\n assert nz == PAR['nz']\n assert ns == PAR['nsx']\n assert nr == PAR['nrx']\n assert list(dsamp) == [dx, dz]\n assert list(origin) == [0, 0]\n\n # 3d\n ndims, shiftdim, dims, ny, nx, nz, ns, nr, dy, dx, dz, dsamp, origin = \\\n _identify_geometry(z, x, s3d, r3d, y=y)\n assert ndims == 3\n assert shiftdim == 1\n assert list(dims) == [PAR['ny'], PAR['nx'], PAR['nz']]\n assert ny == PAR['ny']\n assert nx == PAR['nx']\n assert nz == PAR['nz']\n assert ns == PAR['nsy']*PAR['nsx']\n assert nr == PAR['nry']*PAR['nrx']\n assert list(dsamp) == [dy, dx, dz]\n assert list(origin) == [0, 0, 0]\n\n\ndef test_traveltime_ana():\n \"\"\"Check analytical traveltimes in homogenous medium for horizontal and\n vertical paths\n \"\"\"\n src = np.array([100, 0])[:, np.newaxis]\n\n _, trav_srcs_ana, trav_recs_ana = \\\n _traveltime_table(np.arange(0, 200, 1), np.arange(0, 200, 1),\n src, src, v0, mode='analytic')\n assert trav_srcs_ana[0, 0] == 100/v0\n assert trav_recs_ana[0, 0] == 100/v0\n\n\ndef test_traveltime_table():\n \"\"\"Compare analytical and eikonal traveltimes in homogenous medium\n \"\"\"\n # 2d\n trav_ana, trav_srcs_ana, trav_recs_ana =\\\n _traveltime_table(z, x, s2d, r2d, v0, mode='analytic')\n\n trav_eik, trav_srcs_eik, trav_recs_eik = \\\n _traveltime_table(z, x, s2d, r2d, v0*np.ones((PAR['nx'], PAR['nz'])),\n mode='eikonal')\n\n assert_array_almost_equal(trav_srcs_ana, trav_srcs_eik, decimal=2)\n assert_array_almost_equal(trav_recs_ana, trav_recs_ana, decimal=2)\n assert_array_almost_equal(trav_ana, trav_eik, decimal=2)\n\n # 3d\n trav_ana, trav_srcs_ana, trav_recs_ana = \\\n _traveltime_table(z, x, s3d, r3d, v0, y=y, mode='analytic')\n\n trav_eik, trav_srcs_eik, trav_recs_eik = \\\n _traveltime_table(z, x, s3d, r3d,\n v0 * np.ones((PAR['ny'], PAR['nx'], PAR['nz'])),\n y=y, mode='eikonal')\n\n assert_array_almost_equal(trav_srcs_ana, trav_srcs_eik, decimal=2)\n assert_array_almost_equal(trav_recs_ana, trav_recs_eik, decimal=2)\n assert_array_almost_equal(trav_ana, trav_eik, decimal=2)\n\n\ndef test_unknown_mode():\n \"\"\"Check error is raised if unknown mode is passed\n \"\"\"\n with pytest.raises(NotImplementedError):\n _ = LSM(z, x, t, s2d, r2d, 0,\n np.ones(3), 1, mode='foo')\n\n\[email protected](\"par\", [(par1), (par2), (par3)])\ndef test_demigration2d(par):\n \"\"\"Dot-test for Demigration operator\n \"\"\"\n vel = v0 * np.ones((PAR['nx'], PAR['nz']))\n\n if par['mode'] == 'byot':\n trav, _, _ = \\\n _traveltime_table(z, x, s2d, r2d, v0, mode='analytic')\n else:\n trav = None\n\n Dop = Demigration(z, x, t, s2d, r2d,\n vel if par['mode'] == 'eikonal' else v0, wav, wavc,\n y=None, trav=trav, mode=par['mode'])\n assert dottest(Dop, PAR['nsx']*PAR['nrx']*PAR['nt'], PAR['nz']*PAR['nx'])\n\n\[email protected](\"par\", [(par1), (par2)])\ndef test_lsm2d(par):\n \"\"\"Dot-test and inverse for LSM operator\n \"\"\"\n vel = v0 * np.ones((PAR['nx'], PAR['nz']))\n refl = np.zeros((PAR['nx'], PAR['nz']))\n refl[:, PAR['nz']//2] = 1\n refl[:, 3*PAR['nz']//4] = 1\n\n lsm = LSM(z, x, t, s2d, r2d, vel if par['mode'] == 'eikonal' else v0,\n wav, wavc, mode=par['mode'], dottest=True)\n\n d = lsm.Demop * refl.ravel()\n d = d.reshape(PAR['nsx'], PAR['nrx'], PAR['nt'])\n\n minv = lsm.solve(d.ravel(), **dict(iter_lim=100, show=True))\n minv = minv.reshape(PAR['nx'], PAR['nz'])\n\n dinv = lsm.Demop * minv.ravel()\n dinv = dinv.reshape(PAR['nsx'], PAR['nrx'], PAR['nt'])\n\n assert_array_almost_equal(d, dinv, decimal=1)\n assert_array_almost_equal(refl, minv, decimal=1)\n", "\"\"\"\nTapers\n======\nThis example shows how to create some basic tapers in 1d, 2d, and 3d\nusing the :py:mod:`pylops.utils.tapers` module.\n\"\"\"\nimport matplotlib.pyplot as plt\nimport pylops\n\nplt.close('all')\n\n############################################\n# Let's first define the time and space axes\npar = {'ox':-200, 'dx':2, 'nx':201,\n 'oy':-100, 'dy':2, 'ny':101,\n 'ot':0, 'dt':0.004, 'nt':501,\n 'ntapx': 21, 'ntapy': 31}\n\n############################################\n# We can now create tapers in 1d\ntap_han = pylops.utils.tapers.hanningtaper(par['nx'],\n par['ntapx'])\ntap_cos = pylops.utils.tapers.cosinetaper(par['nx'], par['ntapx'], False)\ntap_cos2 = pylops.utils.tapers.cosinetaper(par['nx'], par['ntapx'], True)\n\nplt.figure()\nplt.plot(tap_han, 'r', label='hanning')\nplt.plot(tap_cos, 'k', label='cosine')\nplt.plot(tap_cos2, 'b', label='cosine square')\nplt.title('Tapers')\nplt.legend()\n\n############################################\n# Similarly we can create 2d and 3d tapers with any of the tapers above\ntap2d = pylops.utils.tapers.taper2d(par['nt'], par['nx'],\n par['ntapx'])\n\nplt.figure(figsize=(7, 3))\nplt.plot(tap2d[:, par['nt']//2], 'k', lw=2)\nplt.title('Taper')\n\ntap3d = pylops.utils.tapers.taper3d(par['nt'], (par['ny'], par['nx']),\n (par['ntapy'], par['ntapx']))\n\nplt.figure(figsize=(7, 3))\nplt.imshow(tap3d[:, :, par['nt']//2], 'jet')\nplt.title('Taper in y-x slice')\nplt.xlabel('x')\nplt.ylabel('y')\n\n", "import os\nimport numpy as np\nfrom numba import jit\n\n# detect whether to use parallel or not\nnumba_threads = int(os.getenv('NUMBA_NUM_THREADS', '1'))\nparallel = True if numba_threads != 1 else False\n\n\n@jit(nopython=True)\ndef _linear_numba(x, t, px):\n return t + px * x\n\n@jit(nopython=True)\ndef _parabolic_numba(x, t, px):\n return t + px*x**2\n\n@jit(nopython=True)\ndef _hyperbolic_numba(x, t, px):\n return np.sqrt(t**2 + (x/px)**2)\n\n@jit(nopython=True, nogil=True)\ndef _indices_2d_numba(f, x, px, t, nt, interp=True):\n \"\"\"Compute time and space indices of parametric line in ``f`` function\n using numba. Refer to ``_indices_2d`` for full documentation.\n\n \"\"\"\n tdecscan = f(x, t, px)\n if not interp:\n xscan = (tdecscan >= 0) & (tdecscan < nt)\n else:\n xscan = (tdecscan >= 0) & (tdecscan < nt - 1)\n tscanfs = tdecscan[xscan]\n tscan = np.zeros(len(tscanfs))\n dtscan = np.zeros(len(tscanfs))\n for it, tscanf in enumerate(tscanfs):\n tscan[it] = int(tscanf)\n if interp:\n dtscan[it] = tscanf - tscan[it]\n return xscan, tscan, dtscan\n\n@jit(nopython=True, parallel=parallel, nogil=True)\ndef _indices_2d_onthefly_numba(f, x, px, ip, t, nt, interp=True):\n \"\"\"Wrapper around _indices_2d to allow on-the-fly computation of\n parametric curves using numba\n \"\"\"\n tscan = np.full(len(x), np.nan, dtype=np.float32)\n if interp:\n dtscan = np.full(len(x), np.nan)\n else:\n dtscan = None\n xscan, tscan1, dtscan1 = \\\n _indices_2d_numba(f, x, px[ip], t, nt, interp=interp)\n tscan[xscan] = tscan1\n if interp:\n dtscan[xscan] = dtscan1\n return xscan, tscan, dtscan\n\n@jit(nopython=True, parallel=parallel, nogil=True)\ndef _create_table_numba(f, x, pxaxis, nt, npx, nx, interp):\n \"\"\"Create look up table using numba\n \"\"\"\n table = np.full((npx, nt, nx), np.nan, dtype=np.float32)\n dtable = np.full((npx, nt, nx), np.nan)\n for ipx in range(npx):\n px = pxaxis[ipx]\n for it in range(nt):\n xscans, tscan, dtscan = _indices_2d_numba(f, x, px,\n it, nt,\n interp=interp)\n itscan = 0\n for ixscan, xscan in enumerate(xscans):\n if xscan:\n table[ipx, it, ixscan] = tscan[itscan]\n if interp:\n dtable[ipx, it, ixscan] = dtscan[itscan]\n itscan += 1\n return table, dtable\n", "import pytest\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\nfrom scipy.sparse import rand\nfrom scipy.sparse.linalg import lsqr\n\nfrom pylops.utils import dottest\nfrom pylops.basicoperators import Regression, LinearRegression, MatrixMult, \\\n Identity, Zero, Flip, Symmetrize, Roll, Sum, Real, Imag, Conj\n\npar1 = {'ny': 11, 'nx': 11, 'imag': 0,\n 'dtype':'float64'} # square real\npar2 = {'ny': 21, 'nx': 11, 'imag': 0,\n 'dtype':'float64'} # overdetermined real\npar1j = {'ny': 11, 'nx': 11, 'imag': 1j,\n 'dtype':'complex128'} # square complex\npar2j = {'ny': 21, 'nx': 11, 'imag': 1j,\n 'dtype':'complex128'} # overdetermined complex\npar3 = {'ny': 11, 'nx': 21, 'imag': 0,\n 'dtype':'float64'} # underdetermined real\n\nnp.random.seed(10)\n\[email protected](\"par\", [(par1), (par2)])\ndef test_Regression(par):\n \"\"\"Dot-test, inversion and apply for Regression operator\n \"\"\"\n np.random.seed(10)\n order = 4\n t = np.arange(par['ny'], dtype=np.float32)\n LRop = Regression(t, order=order, dtype=par['dtype'])\n assert dottest(LRop, par['ny'], order+1)\n\n x = np.array([1., 2., 0., 3., -1.], dtype=np.float32)\n xlsqr = lsqr(LRop, LRop*x, damp=1e-10, iter_lim=300, show=0)[0]\n assert_array_almost_equal(x, xlsqr, decimal=3)\n\n y = LRop * x\n y1 = LRop.apply(t, x)\n assert_array_almost_equal(y, y1, decimal=3)\n\n\[email protected](\"par\", [(par1), (par2)])\ndef test_LinearRegression(par):\n \"\"\"Dot-test and inversion for LinearRegression operator\n \"\"\"\n np.random.seed(10)\n t = np.arange(par['ny'], dtype=np.float32)\n LRop = LinearRegression(t, dtype=par['dtype'])\n assert dottest(LRop, par['ny'], 2)\n\n x = np.array([1., 2.], dtype=np.float32)\n xlsqr = lsqr(LRop, LRop*x, damp=1e-10, iter_lim=300, show=0)[0]\n assert_array_almost_equal(x, xlsqr, decimal=3)\n\n y = LRop * x\n y1 = LRop.apply(t, x)\n assert_array_almost_equal(y, y1, decimal=3)\n\n\[email protected](\"par\", [(par1), (par2), (par1j), (par2j)])\ndef test_MatrixMult(par):\n \"\"\"Dot-test and inversion for MatrixMult operator\n \"\"\"\n np.random.seed(10)\n G = np.random.normal(0, 10, (par['ny'],\n par['nx'])).astype('float32') + \\\n par['imag']*np.random.normal(0, 10, (par['ny'],\n par['nx'])).astype('float32')\n Gop = MatrixMult(G, dtype=par['dtype'])\n assert dottest(Gop, par['ny'], par['nx'],\n complexflag=0 if par['imag'] == 0 else 3)\n\n x = np.ones(par['nx']) + par['imag']*np.ones(par['nx'])\n xlsqr = lsqr(Gop, Gop*x, damp=1e-20, iter_lim=300, show=0)[0]\n assert_array_almost_equal(x, xlsqr, decimal=4)\n\n\[email protected](\"par\", [(par1), (par2), (par1j), (par2j)])\ndef test_MatrixMult_sparse(par):\n \"\"\"Dot-test and inversion for test_MatrixMult operator using sparse\n matrix\n \"\"\"\n np.random.seed(10)\n G = rand(par['ny'], par['nx'], density=0.75).astype('float32') + \\\n par['imag'] * rand(par['ny'], par['nx'], density=0.75).astype('float32')\n\n Gop = MatrixMult(G, dtype=par['dtype'])\n assert dottest(Gop, par['ny'], par['nx'],\n complexflag=0 if par['imag'] == 1 else 3)\n\n x = np.ones(par['nx']) + par['imag'] * np.ones(par['nx'])\n xlsqr = lsqr(Gop, Gop * x, damp=1e-20, iter_lim=300, show=0)[0]\n assert_array_almost_equal(x, xlsqr, decimal=4)\n\n\[email protected](\"par\", [(par1), (par2), (par1j), (par2j)])\ndef test_MatrixMult_repeated(par):\n \"\"\"Dot-test and inversion for test_MatrixMult operator repeated\n along another dimension\n \"\"\"\n np.random.seed(10)\n G = np.random.normal(0, 10, (par['ny'], par['nx'])).astype('float32') + \\\n par['imag'] * np.random.normal(0, 10, (par['ny'],\n par['nx'])).astype('float32')\n Gop = MatrixMult(G, dims=5, dtype=par['dtype'])\n assert dottest(Gop, par['ny']*5, par['nx']*5,\n complexflag=0 if par['imag'] == 1 else 3)\n\n x = (np.ones((par['nx'], 5)) +\n par['imag'] * np.ones((par['nx'], 5))).flatten()\n xlsqr = lsqr(Gop, Gop*x, damp=1e-20, iter_lim=300, show=0)[0]\n assert_array_almost_equal(x, xlsqr, decimal=4)\n\n\[email protected](\"par\", [(par1), (par2), (par1j), (par2j), (par3)])\ndef test_Identity_inplace(par):\n \"\"\"Dot-test, forward and adjoint for Identity operator\n \"\"\"\n np.random.seed(10)\n Iop = Identity(par['ny'], par['nx'], dtype=par['dtype'], inplace=True)\n assert dottest(Iop, par['ny'], par['nx'],\n complexflag=0 if par['imag'] == 0 else 3)\n\n x = np.ones(par['nx']) + par['imag'] * np.ones(par['nx'])\n y = Iop*x\n x1 = Iop.H*y\n\n assert_array_almost_equal(x[:min(par['ny'], par['nx'])],\n y[:min(par['ny'], par['nx'])], decimal=4)\n assert_array_almost_equal(x[:min(par['ny'], par['nx'])],\n x1[:min(par['ny'], par['nx'])], decimal=4)\n\n\[email protected](\"par\", [(par1), (par2), (par1j), (par2j), (par3)])\ndef test_Identity_noinplace(par):\n \"\"\"Dot-test, forward and adjoint for Identity operator (not in place)\n \"\"\"\n np.random.seed(10)\n Iop = Identity(par['ny'], par['nx'], dtype=par['dtype'], inplace=False)\n assert dottest(Iop, par['ny'], par['nx'],\n complexflag=0 if par['imag'] == 0 else 3)\n\n x = np.ones(par['nx']) + par['imag'] * np.ones(par['nx'])\n y = Iop*x\n x1 = Iop.H*y\n\n assert_array_almost_equal(x[:min(par['ny'], par['nx'])],\n y[:min(par['ny'], par['nx'])], decimal=4)\n assert_array_almost_equal(x[:min(par['ny'], par['nx'])],\n x1[:min(par['ny'], par['nx'])], decimal=4)\n\n # change value in x and check it doesn't change in y\n x[0] = 10\n assert x[0] != y[0]\n\n\[email protected](\"par\", [(par1), (par2), (par1j), (par2j), (par3)])\ndef test_Zero(par):\n \"\"\"Dot-test, forward and adjoint for Zero operator\n \"\"\"\n np.random.seed(10)\n Zop = Zero(par['ny'], par['nx'], dtype=par['dtype'])\n assert dottest(Zop, par['ny'], par['nx'])\n\n x = np.ones(par['nx']) + par['imag']*np.ones(par['nx'])\n y = Zop * x\n x1 = Zop.H*y\n\n assert_array_almost_equal(y, np.zeros(par['ny']))\n assert_array_almost_equal(x1, np.zeros(par['nx']))\n\n\[email protected](\"par\", [(par1), (par2), (par1j), (par2j)])\ndef test_Flip1D(par):\n \"\"\"Dot-test, forward and adjoint for Flip operator on 1d signal\n \"\"\"\n np.random.seed(10)\n x = np.arange(par['ny']) + par['imag'] * np.arange(par['ny'])\n\n Fop = Flip(par['ny'], dtype=par['dtype'])\n assert dottest(Fop, par['ny'], par['ny'])\n\n y = Fop * x\n xadj = Fop.H * y\n assert_array_equal(x, xadj)\n\n\[email protected](\"par\", [(par1), (par2), (par1j), (par2j)])\ndef test_Flip2D(par):\n \"\"\"Dot-test, forward and adjoint for Flip operator on 2d signal\n \"\"\"\n np.random.seed(10)\n x = {}\n x['0'] = np.outer(np.arange(par['ny']), np.ones(par['nx'])) + \\\n par['imag'] * np.outer(np.arange(par['ny']), np.ones(par['nx']))\n x['1'] = np.outer(np.ones(par['ny']), np.arange(par['nx'])) + \\\n par['imag'] * np.outer(np.ones(par['ny']), np.arange(par['nx']))\n\n for dir in [0, 1]:\n Fop = Flip(par['ny']*par['nx'], dims=(par['ny'], par['nx']),\n dir=dir, dtype=par['dtype'])\n assert dottest(Fop, par['ny']*par['nx'], par['ny']*par['nx'])\n\n y = Fop * x[str(dir)].flatten()\n xadj = Fop.H * y.flatten()\n xadj = xadj.reshape(par['ny'], par['nx'])\n assert_array_equal(x[str(dir)], xadj)\n\n\[email protected](\"par\", [(par1), (par2), (par1j), (par2j)])\ndef test_Flip3D(par):\n \"\"\"Dot-test, forward and adjoint for Flip operator on 3d signal\n \"\"\"\n np.random.seed(10)\n x = {}\n x['0'] = np.outer(np.arange(par['ny']),\n np.ones(par['nx']))[:, :, np.newaxis] * \\\n np.ones(par['nx']) + \\\n par['imag'] * np.outer(np.arange(par['ny']),\n np.ones(par['nx']))[:, :, np.newaxis] * \\\n np.ones(par['nx'])\n\n x['1'] = np.outer(np.ones(par['ny']),\n np.arange(par['nx']))[:, :, np.newaxis] * \\\n np.ones(par['nx']) + \\\n par['imag'] * np.outer(np.ones(par['ny']),\n np.arange(par['nx']))[:, :, np.newaxis] * \\\n np.ones(par['nx'])\n x['2'] = np.outer(np.ones(par['ny']),\n np.ones(par['nx']))[:, :, np.newaxis] * \\\n np.arange(par['nx']) + \\\n par['imag'] * np.outer(np.ones(par['ny']),\n np.ones(par['nx']))[:, :, np.newaxis] * \\\n np.arange(par['nx'])\n\n for dir in [0, 1, 2]:\n Fop = Flip(par['ny']*par['nx']*par['nx'],\n dims=(par['ny'], par['nx'], par['nx']),\n dir=dir, dtype=par['dtype'])\n assert dottest(Fop, par['ny']*par['nx']*par['nx'],\n par['ny']*par['nx']*par['nx'])\n\n y = Fop * x[str(dir)].flatten()\n xadj = Fop.H * y.flatten()\n xadj = xadj.reshape(par['ny'], par['nx'], par['nx'])\n assert_array_equal(x[str(dir)], xadj)\n\n\[email protected](\"par\", [(par1), (par2), (par1j), (par2j), (par3)])\ndef test_Symmetrize1D(par):\n \"\"\"Dot-test, forward and inverse for Symmetrize operator on 1d signal\n \"\"\"\n np.random.seed(10)\n x = np.arange(par['ny']) + par['imag'] * np.arange(par['ny'])\n\n Sop = Symmetrize(par['ny'], dtype=par['dtype'])\n dottest(Sop, par['ny']*2-1, par['ny'], verb=True)\n\n y = Sop * x\n xinv = Sop / y\n assert_array_almost_equal(x, xinv, decimal=3)\n\n\[email protected](\"par\", [(par1), (par2), (par1j), (par2j), (par3)])\ndef test_Symmetrize2D(par):\n \"\"\"Dot-test, forward and inverse for Symmetrize operator on 2d signal\n \"\"\"\n np.random.seed(10)\n x = {}\n x['0'] = np.outer(np.arange(par['ny']), np.ones(par['nx'])) + \\\n par['imag'] * np.outer(np.arange(par['ny']), np.ones(par['nx']))\n x['1'] = np.outer(np.ones(par['ny']), np.arange(par['nx'])) + \\\n par['imag'] * np.outer(np.ones(par['ny']), np.arange(par['nx']))\n\n for dir in [0, 1]:\n Sop = Symmetrize(par['ny']*par['nx'],\n dims=(par['ny'], par['nx']),\n dir=dir, dtype=par['dtype'])\n y = Sop * x[str(dir)].flatten()\n assert dottest(Sop, y.size, par['ny']*par['nx'])\n\n xinv = Sop / y\n assert_array_almost_equal(x[str(dir)].ravel(), xinv, decimal=3)\n\n\[email protected](\"par\", [(par1), (par2), (par1j), (par2j), (par3)])\ndef test_Symmetrize3D(par):\n \"\"\"Dot-test, forward and adjoint for Symmetrize operator on 3d signal\n \"\"\"\n np.random.seed(10)\n x = {}\n x['0'] = np.outer(np.arange(par['ny']),\n np.ones(par['nx']))[:, :, np.newaxis] * \\\n np.ones(par['nx']) + \\\n par['imag'] * np.outer(np.arange(par['ny']),\n np.ones(par['nx']))[:, :, np.newaxis] * \\\n np.ones(par['nx'])\n\n x['1'] = np.outer(np.ones(par['ny']),\n np.arange(par['nx']))[:, :, np.newaxis] * \\\n np.ones(par['nx']) + \\\n par['imag'] * np.outer(np.ones(par['ny']),\n np.arange(par['nx']))[:, :, np.newaxis] * \\\n np.ones(par['nx'])\n x['2'] = np.outer(np.ones(par['ny']),\n np.ones(par['nx']))[:, :, np.newaxis] * \\\n np.arange(par['nx']) + \\\n par['imag'] * np.outer(np.ones(par['ny']),\n np.ones(par['nx']))[:, :, np.newaxis] * \\\n np.arange(par['nx'])\n\n for dir in [0, 1, 2]:\n Sop = Symmetrize(par['ny']*par['nx']*par['nx'],\n dims=(par['ny'], par['nx'], par['nx']),\n dir=dir, dtype=par['dtype'])\n y = Sop * x[str(dir)].flatten()\n assert dottest(Sop, y.size, par['ny']*par['nx']*par['nx'])\n\n xinv = Sop / y\n assert_array_almost_equal(x[str(dir)].ravel(), xinv, decimal=3)\n\n\[email protected](\"par\", [(par1), (par2), (par1j), (par2j), (par3)])\ndef test_Roll1D(par):\n \"\"\"Dot-test, forward and adjoint for Roll operator on 1d signal\n \"\"\"\n np.random.seed(10)\n x = np.arange(par['ny']) + par['imag'] * np.arange(par['ny'])\n\n Rop = Roll(par['ny'], shift=2, dtype=par['dtype'])\n assert dottest(Rop, par['ny'], par['ny'])\n\n y = Rop * x\n xadj = Rop.H * y\n assert_array_almost_equal(x, xadj, decimal=3)\n\n\[email protected](\"par\", [(par1), (par2), (par1j), (par2j), (par3)])\ndef test_Roll2D(par):\n \"\"\"Dot-test, forward and inverse for Roll operator on 2d signal\n \"\"\"\n np.random.seed(10)\n x = {}\n x['0'] = np.outer(np.arange(par['ny']), np.ones(par['nx'])) + \\\n par['imag'] * np.outer(np.arange(par['ny']),\n np.ones(par['nx']))\n x['1'] = np.outer(np.ones(par['ny']), np.arange(par['nx'])) + \\\n par['imag'] * np.outer(np.ones(par['ny']),\n np.arange(par['nx']))\n\n for dir in [0, 1]:\n Rop = Roll(par['ny'] * par['nx'],\n dims=(par['ny'], par['nx']),\n dir=dir, shift=-2, dtype=par['dtype'])\n y = Rop * x[str(dir)].flatten()\n assert dottest(Rop, par['ny'] * par['nx'], par['ny'] * par['nx'])\n\n xadj = Rop.H * y\n assert_array_almost_equal(x[str(dir)].ravel(), xadj, decimal=3)\n\n\[email protected](\"par\", [(par1), (par2), (par1j), (par2j), (par3)])\ndef test_Roll3D(par):\n \"\"\"Dot-test, forward and adjoint for Roll operator on 3d signal\n \"\"\"\n np.random.seed(10)\n x = {}\n x['0'] = np.outer(np.arange(par['ny']),\n np.ones(par['nx']))[:, :, np.newaxis] * \\\n np.ones(par['nx']) + \\\n par['imag'] * np.outer(np.arange(par['ny']),\n np.ones(par['nx']))[:, :, np.newaxis] * \\\n np.ones(par['nx'])\n\n x['1'] = np.outer(np.ones(par['ny']),\n np.arange(par['nx']))[:, :, np.newaxis] * \\\n np.ones(par['nx']) + \\\n par['imag'] * np.outer(np.ones(par['ny']),\n np.arange(par['nx']))[:, :, np.newaxis] * \\\n np.ones(par['nx'])\n x['2'] = np.outer(np.ones(par['ny']),\n np.ones(par['nx']))[:, :, np.newaxis] * \\\n np.arange(par['nx']) + \\\n par['imag'] * np.outer(np.ones(par['ny']),\n np.ones(par['nx']))[:, :, np.newaxis] * \\\n np.arange(par['nx'])\n\n for dir in [0, 1, 2]:\n Rop = Roll(par['ny'] * par['nx'] * par['nx'],\n dims=(par['ny'], par['nx'], par['nx']),\n dir=dir, shift=3, dtype=par['dtype'])\n y = Rop * x[str(dir)].flatten()\n assert dottest(Rop, par['ny'] * par['nx'] * par['nx'],\n par['ny'] * par['nx'] * par['nx'])\n\n xinv = Rop.H * y\n assert_array_almost_equal(x[str(dir)].ravel(), xinv, decimal=3)\n\n\[email protected](\"par\", [(par1), (par2), (par1j), (par2j), (par3)])\ndef test_Sum2D(par):\n \"\"\"Dot-test for Sum operator on 2d signal\n \"\"\"\n for dir in [0, 1]:\n dim_d = [par['ny'], par['nx']]\n dim_d.pop(dir)\n Sop = Sum(dims=(par['ny'], par['nx']),\n dir=dir, dtype=par['dtype'])\n assert dottest(Sop, np.prod(dim_d), par['ny'] * par['nx'])\n\n\[email protected](\"par\", [(par1), (par2), (par1j), (par2j), (par3)])\ndef test_Sum3D(par):\n \"\"\"Dot-test, forward and adjoint for Sum operator on 3d signal\n \"\"\"\n for dir in [0, 1, 2]:\n dim_d = [par['ny'], par['nx'], par['nx']]\n dim_d.pop(dir)\n Sop = Sum(dims=(par['ny'], par['nx'], par['nx']),\n dir=dir, dtype=par['dtype'])\n assert dottest(Sop, np.prod(dim_d), par['ny'] * par['nx'] * par['nx'])\n\n\[email protected](\"par\", [(par1), (par2), (par1j), (par2j), (par3)])\ndef test_Real(par):\n \"\"\"Dot-test, forward and adjoint for Real operator\n \"\"\"\n Rop = Real(dims=(par['ny'], par['nx']), dtype=par['dtype'])\n if np.dtype(par['dtype']).kind == 'c':\n complexflag = 3\n else:\n complexflag = 0\n assert dottest(Rop, par['ny'] * par['nx'], par['ny'] * par['nx'],\n complexflag=complexflag)\n\n np.random.seed(10)\n x = (np.random.randn(par['nx'] * par['ny'])\n + par['imag'] * np.random.randn(par['nx'] * par['ny']))\n y = Rop * x\n assert_array_equal(y, np.real(x))\n y = (np.random.randn(par['nx'] * par['ny'])\n + par['imag'] * np.random.randn(par['nx'] * par['ny']))\n x = Rop.H * y\n assert_array_equal(x, np.real(y) + 0j)\n\n\[email protected](\"par\", [(par1), (par2), (par1j), (par2j), (par3)])\ndef test_Imag(par):\n \"\"\"Dot-test, forward and adjoint for Imag operator\n \"\"\"\n Iop = Imag(dims=(par['ny'], par['nx']), dtype=par['dtype'])\n if np.dtype(par['dtype']).kind == 'c':\n complexflag = 3\n else:\n complexflag = 0\n assert dottest(Iop, par['ny'] * par['nx'], par['ny'] * par['nx'],\n complexflag=complexflag)\n\n np.random.seed(10)\n x = (np.random.randn(par['nx'] * par['ny'])\n + par['imag'] * np.random.randn(par['nx'] * par['ny']))\n y = Iop * x\n assert_array_equal(y, np.imag(x))\n y = (np.random.randn(par['nx'] * par['ny'])\n + par['imag'] * np.random.randn(par['nx'] * par['ny']))\n x = Iop.H * y\n if np.dtype(par['dtype']).kind == 'c':\n assert_array_equal(x, 0 + 1j*np.real(y))\n else:\n assert_array_equal(x, 0)\n\n\[email protected](\"par\", [(par1), (par2), (par1j), (par2j), (par3)])\ndef test_Conj(par):\n \"\"\"Dot-test, forward and adjoint for Conj operator\n \"\"\"\n Cop = Conj(dims=(par['ny'], par['nx']), dtype=par['dtype'])\n if np.dtype(par['dtype']).kind == 'c':\n complexflag = 3\n else:\n complexflag = 0\n assert dottest(Cop, par['ny'] * par['nx'], par['ny'] * par['nx'],\n complexflag=complexflag)\n\n np.random.seed(10)\n x = (np.random.randn(par['nx'] * par['ny'])\n + par['imag'] * np.random.randn(par['nx'] * par['ny']))\n y = Cop * x\n xadj = Cop.H * y\n assert_array_equal(x, xadj)\n assert_array_equal(y, np.conj(x))\n assert_array_equal(xadj, np.conj(y))\n" ]
[ [ "numpy.imag", "numpy.arange", "matplotlib.pyplot.subplots", "numpy.real", "matplotlib.pyplot.close" ], [ "numpy.meshgrid", "numpy.arange", "numpy.ones", "numpy.array", "numpy.zeros", "numpy.testing.assert_array_almost_equal" ], [ "matplotlib.pyplot.legend", "matplotlib.pyplot.imshow", "matplotlib.pyplot.title", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.close", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.figure" ], [ "numpy.sqrt", "numpy.full" ], [ "scipy.sparse.linalg.lsqr", "numpy.imag", "numpy.conj", "numpy.random.seed", "numpy.arange", "scipy.sparse.rand", "numpy.dtype", "numpy.ones", "numpy.testing.assert_array_equal", "numpy.real", "numpy.random.normal", "numpy.random.randn", "numpy.prod", "numpy.array", "numpy.zeros", "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": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "1.3", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "0.16", "1.8" ], "tensorflow": [] } ]
shubhamkumaR630/datasets
[ "fe9ee91849cefed0953141ea3588f73b7def78fd", "fe9ee91849cefed0953141ea3588f73b7def78fd", "fe9ee91849cefed0953141ea3588f73b7def78fd", "fe9ee91849cefed0953141ea3588f73b7def78fd", "fe9ee91849cefed0953141ea3588f73b7def78fd", "fe9ee91849cefed0953141ea3588f73b7def78fd", "fe9ee91849cefed0953141ea3588f73b7def78fd", "fe9ee91849cefed0953141ea3588f73b7def78fd", "fe9ee91849cefed0953141ea3588f73b7def78fd", "fe9ee91849cefed0953141ea3588f73b7def78fd", "fe9ee91849cefed0953141ea3588f73b7def78fd", "fe9ee91849cefed0953141ea3588f73b7def78fd", "fe9ee91849cefed0953141ea3588f73b7def78fd" ]
[ "tensorflow_datasets/summarization/summscreen/summscreen.py", "tensorflow_datasets/audio/fuss.py", "tensorflow_datasets/object_detection/kitti.py", "tensorflow_datasets/image_classification/binary_alpha_digits.py", "tensorflow_datasets/image_classification/eurosat.py", "tensorflow_datasets/graphs/cardiotox/cardiotox.py", "tensorflow_datasets/image/scene_parse_150.py", "tensorflow_datasets/question_answering/web_questions.py", "tensorflow_datasets/text/assin2/assin2.py", "tensorflow_datasets/question_answering/trivia_qa.py", "tensorflow_datasets/translate/ted_hrlr.py", "tensorflow_datasets/d4rl/dataset_builder_test.py", "tensorflow_datasets/text/multi_nli.py" ]
[ "# coding=utf-8\n# Copyright 2022 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"SummScreen Summarization dataset, non-anonymized, non-tokenized version.\"\"\"\n\nimport json\nimport os\n\nimport tensorflow as tf\nimport tensorflow_datasets.public_api as tfds\n\n_DESCRIPTION = \"\"\"\nSummScreen Summarization dataset, non-anonymized, non-tokenized version.\n\nTrain/val/test splits and filtering are based on the final tokenized dataset,\nbut transcripts and recaps provided are based on the untokenized text.\n\nThere are two features:\n\n - transcript: Full episode transcripts, each line of dialogue\n separated by newlines\n - recap: Recaps or summaries of episodes\n\"\"\"\n\n_CITATION = \"\"\"\\\n@article{DBLP:journals/corr/abs-2104-07091,\n author = {Mingda Chen and\n Zewei Chu and\n Sam Wiseman and\n Kevin Gimpel},\n title = {SummScreen: {A} Dataset for Abstractive Screenplay Summarization},\n journal = {CoRR},\n volume = {abs/2104.07091},\n year = {2021},\n url = {https://arxiv.org/abs/2104.07091},\n archivePrefix = {arXiv},\n eprint = {2104.07091},\n timestamp = {Mon, 19 Apr 2021 16:45:47 +0200},\n biburl = {https://dblp.org/rec/journals/corr/abs-2104-07091.bib},\n bibsource = {dblp computer science bibliography, https://dblp.org}\n}\n\"\"\"\n\n_DL_URLS = {\n # pylint: disable=line-too-long\n 'tokenized':\n 'https://drive.google.com/uc?export=download&id=1BvdIllGBo9d2-bzXQRzWuJXB04XPVmfF',\n 'untokenized':\n 'https://drive.google.com/uc?export=download&id=1tFpt32USOO2i1FWhtFTsyYyFzuRm2k36',\n # pylint: enable=line-too-long\n}\n\n_RECAP = 'recap'\n_TRANSCRIPT = 'transcript'\n_RECAP_SOURCE_FULL_NAMES = {\n 'fd': 'ForeverDreaming',\n 'tms': 'TVMegaSite',\n}\n_SPLITS = ['train', 'dev', 'test']\n\n\ndef _load_file(path):\n with tf.io.gfile.GFile(path, 'r') as f:\n return f.read()\n\n\ndef _load_json(path):\n return json.loads(_load_file(path))\n\n\ndef _load_jsonl(path):\n return [json.loads(line) for line in _load_file(path).strip().splitlines()]\n\n\ndef _get_filenames_dict(tokenized_path, recap_source: str):\n \"\"\"Get dictionary of filenames for each split.\"\"\"\n filenames_dict = {}\n for split in _SPLITS:\n tokenized_data = _load_jsonl(\n os.path.join(tokenized_path, 'SummScreen',\n _RECAP_SOURCE_FULL_NAMES[recap_source],\n f'{recap_source}_{split}.json'))\n filenames_dict[split] = [row['filename'] for row in tokenized_data]\n return filenames_dict\n\n\ndef _get_paths_dict(untokenized_path, recap_source, filenames_dict):\n \"\"\"Get dictionary of example paths for each split.\"\"\"\n paths_dict = {}\n for split, filenames in filenames_dict.items():\n paths_dict[split] = [\n os.path.join(untokenized_path, 'SummScreen_raw', recap_source, filename)\n for filename in filenames\n ]\n return paths_dict\n\n\nclass SummscreenConfig(tfds.core.BuilderConfig):\n \"\"\"BuilderConfig for Summscreen.\"\"\"\n\n def __init__(self, *, recap_source=None, **kwargs):\n \"\"\"BuilderConfig for Summscreen.\n\n Args:\n recap_source: str. The directory for the source of recaps to read.\n **kwargs: keyword arguments forwarded to super.\n \"\"\"\n super(SummscreenConfig, self).__init__(**kwargs)\n self.recap_source = recap_source\n\n\nclass Summscreen(tfds.core.GeneratorBasedBuilder):\n \"\"\"DatasetBuilder for non-tokenized, non-anonymized SummScreen dataset.\"\"\"\n\n VERSION = tfds.core.Version('1.0.0')\n RELEASE_NOTES = {\n '1.0.0': 'Initial release.',\n }\n\n BUILDER_CONFIGS = [\n SummscreenConfig(\n name='fd',\n description='ForeverDreaming',\n recap_source='fd',\n ),\n SummscreenConfig(\n name='tms',\n description='TVMegaSite',\n recap_source='tms',\n ),\n ]\n\n def _info(self):\n # Should return a tfds.core.DatasetInfo object\n if self._builder_config.recap_source == 'fd':\n features = tfds.features.FeaturesDict({\n _TRANSCRIPT: tfds.features.Text(),\n _RECAP: tfds.features.Text(),\n 'episode_number': tfds.features.Text(),\n 'episode_title': tfds.features.Text(),\n 'show_title': tfds.features.Text(),\n 'transcript_author': tfds.features.Text(),\n })\n elif self._builder_config.recap_source == 'tms':\n features = tfds.features.FeaturesDict({\n _TRANSCRIPT:\n tfds.features.Text(),\n _RECAP:\n tfds.features.Text(),\n 'episode_summary':\n tfds.features.Text(),\n 'show_title':\n tfds.features.Text(),\n 'transcript_author':\n tfds.features.Tensor(shape=(None,), dtype=tf.string),\n 'recap_author':\n tfds.features.Text(),\n })\n else:\n raise KeyError(\n f'Unknown recap_source {self._builder_config.recap_source}')\n\n return tfds.core.DatasetInfo(\n builder=self,\n description=_DESCRIPTION,\n features=features,\n supervised_keys=(_TRANSCRIPT, _RECAP),\n homepage='https://github.com/mingdachen/SummScreen',\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager):\n dl_paths = dl_manager.download_and_extract(_DL_URLS)\n filenames_dict = _get_filenames_dict(\n tokenized_path=dl_paths['tokenized'],\n recap_source=self._builder_config.recap_source,\n )\n paths_dict = _get_paths_dict(\n untokenized_path=dl_paths['untokenized'],\n recap_source=self._builder_config.recap_source,\n filenames_dict=filenames_dict,\n )\n return {\n 'train': self._generate_examples(paths=paths_dict['train']),\n 'validation': self._generate_examples(paths=paths_dict['dev']),\n 'test': self._generate_examples(paths=paths_dict['test']),\n }\n\n def _generate_examples(self, paths):\n for path in paths:\n example = _load_json(path)\n fname = os.path.basename(path)\n if self._builder_config.recap_source == 'fd':\n yield fname, {\n _TRANSCRIPT: '\\n'.join(example['Transcript']),\n _RECAP: '\\n'.join(example['Recap']),\n 'episode_number': example['Episode Number'],\n 'episode_title': example['Episode Title'],\n 'show_title': example['Show Title'],\n 'transcript_author': example['Transcript Author'],\n }\n elif self._builder_config.recap_source == 'tms':\n yield fname, {\n _TRANSCRIPT: '\\n'.join(example['Transcript']),\n _RECAP: '\\n'.join(example['Recap']),\n 'episode_summary': '\\n'.join(example['Episode Summary']),\n 'show_title': example['Show Title'],\n 'transcript_author': example['Transcript Author'],\n 'recap_author': example['Recap Author'],\n }\n else:\n raise KeyError(\n f'Unknown recap_source {self._builder_config.recap_source}')\n", "# coding=utf-8\n# Copyright 2022 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"FUSS dataset.\"\"\"\n\nimport os\nfrom absl import logging\nimport tensorflow as tf\nimport tensorflow_datasets.public_api as tfds\n\n_CITATION = r\"\"\"\\\n@inproceedings{wisdom2020fuss,\n title = {What's All the {FUSS} About Free Universal Sound Separation Data?},\n author = {Scott Wisdom and Hakan Erdogan and Daniel P. W. Ellis and Romain Serizel and Nicolas Turpault and Eduardo Fonseca and Justin Salamon and Prem Seetharaman and John R. Hershey},\n year = {2020},\n url = {https://arxiv.org/abs/2011.00803},\n}\n\n@inproceedings{fonseca2020fsd50k,\n author = {Eduardo Fonseca and Xavier Favory and Jordi Pons and Frederic Font Corbera and Xavier Serra},\n title = {{FSD}50k: an open dataset of human-labeled sound events},\n year = {2020},\n url = {https://arxiv.org/abs/2010.00475},\n}\n\"\"\"\n\n_DESCRIPTION = \"\"\"\\\nThe Free Universal Sound Separation (FUSS) Dataset is a database of arbitrary\nsound mixtures and source-level references, for use in experiments on arbitrary\nsound separation.\n\nThis is the official sound separation data for the DCASE2020 Challenge Task 4:\nSound Event Detection and Separation in Domestic Environments.\n\nOverview: FUSS audio data is sourced from a pre-release of Freesound dataset\nknown as (FSD50k), a sound event dataset composed of Freesound content annotated\nwith labels from the AudioSet Ontology. Using the FSD50K labels, these source\nfiles have been screened such that they likely only contain a single type of\nsound. Labels are not provided for these source files, and are not considered\npart of the challenge. For the purpose of the DCASE Task4 Sound Separation and\nEvent Detection challenge, systems should not use FSD50K labels, even though\nthey may become available upon FSD50K release.\n\nTo create mixtures, 10 second clips of sources are convolved with simulated room\nimpulse responses and added together. Each 10 second mixture contains between\n1 and 4 sources. Source files longer than 10 seconds are considered \"background\"\nsources. Every mixture contains one background source, which is active for the\nentire duration. We provide: a software recipe to create the dataset, the room\nimpulse responses, and the original source audio.\n\"\"\"\n\n_URL = \"https://github.com/google-research/sound-separation/blob/master/datasets/fuss/FUSS_license_doc/README.md\"\n_DL_METADATA = {\n \"reverberant\":\n (\"https://zenodo.org/record/3743844/files/FUSS_ssdata_reverb.tar.gz\",\n \"ssdata_reverb\"),\n \"unprocessed\":\n (\"https://zenodo.org/record/3743844/files/FUSS_ssdata.tar.gz\", \"ssdata\"\n ),\n}\n\n\nclass Fuss(tfds.core.GeneratorBasedBuilder):\n \"\"\"FUSS: Free Universal Sound Separation dataset.\"\"\"\n\n BUILDER_CONFIGS = [\n tfds.core.BuilderConfig(\n name=\"reverberant\",\n description=\"Default reverberated audio.\",\n version=tfds.core.Version(\"1.2.0\")),\n tfds.core.BuilderConfig(\n name=\"unprocessed\",\n description=\"Unprocessed audio without additional reverberation.\",\n version=tfds.core.Version(\"1.2.0\")),\n ]\n\n def _info(self):\n source_labels = [\"background0\", \"foreground0\", \"foreground1\", \"foreground2\"]\n return tfds.core.DatasetInfo(\n builder=self,\n description=_DESCRIPTION,\n features=tfds.features.FeaturesDict({\n \"mixture_audio\":\n tfds.features.Audio(\n file_format=\"wav\",\n shape=(160000,),\n sample_rate=16000,\n dtype=tf.int16),\n \"sources\":\n tfds.features.Sequence({\n \"audio\":\n tfds.features.Audio(\n file_format=\"wav\",\n shape=(160000,),\n sample_rate=16000,\n dtype=tf.int16),\n \"label\":\n tfds.features.ClassLabel(names=source_labels),\n }),\n \"segments\":\n tfds.features.Sequence({\n \"start_time_seconds\": tf.float32,\n \"end_time_seconds\": tf.float32,\n \"label\": tf.string\n }),\n \"jams\":\n tf.string,\n \"id\":\n tf.string,\n }),\n supervised_keys=(\"mixture_audio\", \"sources\"),\n homepage=_URL,\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager):\n url, extracted_dirname = _DL_METADATA[self.builder_config.name]\n base_dir = dl_manager.download_and_extract(url)\n splits = []\n for split_name, split_dir in [(tfds.Split.TRAIN, \"train\"),\n (tfds.Split.VALIDATION, \"validation\"),\n (tfds.Split.TEST, \"eval\")]:\n splits.append(\n tfds.core.SplitGenerator(\n name=split_name,\n gen_kwargs={\n \"base_dir\": os.path.join(base_dir, extracted_dirname),\n \"split\": split_dir,\n }))\n return splits\n\n def _parse_segments(self, path):\n segments = []\n if not tf.io.gfile.exists(path):\n # Some segments files are missing in the \"unprocessed\" set.\n logging.info(\"Missing segments file: %s\", path)\n return segments\n with tf.io.gfile.GFile(path) as f:\n for l in f:\n try:\n start, end, label = l.split()\n except ValueError:\n continue\n segments.append({\n \"start_time_seconds\": float(start),\n \"end_time_seconds\": float(end),\n \"label\": label\n })\n return segments\n\n def _generate_examples(self, base_dir, split):\n \"\"\"Generates examples for the given split.\"\"\"\n path = os.path.join(base_dir, \"%s_example_list.txt\" % split)\n split_dir = os.path.join(base_dir, split)\n with tf.io.gfile.GFile(path) as example_list:\n for line in example_list:\n paths = line.split()\n key = _basename_without_ext(paths[0])\n sources = []\n for p in paths[1:]:\n sources.append({\n \"audio\": os.path.join(base_dir, p),\n \"label\": _basename_without_ext(p).split(\"_\")[0],\n })\n segments = self._parse_segments(os.path.join(split_dir, \"%s.txt\" % key))\n jams = tf.io.gfile.GFile(os.path.join(split_dir,\n \"%s.jams\" % key)).read()\n example = {\n \"mixture_audio\": os.path.join(base_dir, paths[0]),\n \"sources\": sources,\n \"segments\": segments,\n \"jams\": jams,\n \"id\": key,\n }\n yield key, example\n\n\ndef _basename_without_ext(p):\n basename, _ = os.path.splitext(os.path.basename(p))\n return basename\n", "# coding=utf-8\n# Copyright 2022 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Kitti dataset.\"\"\"\n\nimport collections\nimport csv\nimport os\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_datasets.public_api as tfds\n\n_CITATION = \"\"\"\\\n@inproceedings{Geiger2012CVPR,\n author = {Andreas Geiger and Philip Lenz and Raquel Urtasun},\n title = {Are we ready for Autonomous Driving? The KITTI Vision Benchmark Suite},\n booktitle = {Conference on Computer Vision and Pattern Recognition (CVPR)},\n year = {2012}\n}\n\"\"\"\n_DESCRIPTION = \"\"\"\\\nKitti contains a suite of vision tasks built using an autonomous driving\nplatform. The full benchmark contains many tasks such as stereo, optical flow,\nvisual odometry, etc. This dataset contains the object detection dataset,\nincluding the monocular images and bounding boxes. The dataset contains 7481\ntraining images annotated with 3D bounding boxes. A full description of the\nannotations can be found in the readme of the object development kit readme on\nthe Kitti homepage.\n\"\"\"\n_HOMEPAGE_URL = \"http://www.cvlibs.net/datasets/kitti/\"\n_DATA_URL = \"https://s3.eu-central-1.amazonaws.com/avg-kitti\"\n_IMAGES_FNAME = \"data_object_image_2.zip\"\n_LABELS_FNAME = \"data_object_label_2.zip\"\n_DEVKIT_FNAME = \"devkit_object.zip\"\n_OBJECT_LABELS = [\n \"Car\",\n \"Van\",\n \"Truck\",\n \"Pedestrian\",\n \"Person_sitting\",\n \"Cyclist\",\n \"Tram\",\n \"Misc\",\n]\n# The percentage of trainset videos to put into validation and test sets.\n# The released test images do not have labels.\n_VALIDATION_SPLIT_PERCENT_VIDEOS = 10\n_TEST_SPLIT_PERCENT_VIDEOS = 10\n\n# Raw Kitti representation of a bounding box. Coordinates are in pixels,\n# measured from the top-left hand corner.\nRawBoundingBox = collections.namedtuple(\"RawBoundingBox\",\n [\"top\", \"bottom\", \"left\", \"right\"])\n\n\nclass Kitti(tfds.core.GeneratorBasedBuilder):\n \"\"\"Kitti dataset.\"\"\"\n\n VERSION = tfds.core.Version(\"3.2.0\")\n SUPPORTED_VERSIONS = [\n tfds.core.Version(\"3.1.0\"),\n ]\n RELEASE_NOTES = {\"3.2.0\": \"Devkit updated.\"}\n\n def _info(self):\n # Annotation descriptions are in the object development kit.\n annotations = {\n \"type\": tfds.features.ClassLabel(names=_OBJECT_LABELS),\n \"truncated\": tfds.features.Tensor(shape=(), dtype=tf.float32),\n \"occluded\": tfds.features.ClassLabel(num_classes=4),\n \"alpha\": tfds.features.Tensor(shape=(), dtype=tf.float32),\n \"bbox\": tfds.features.BBoxFeature(),\n \"dimensions\": tfds.features.Tensor(shape=(3,), dtype=tf.float32),\n \"location\": tfds.features.Tensor(shape=(3,), dtype=tf.float32),\n \"rotation_y\": tfds.features.Tensor(shape=(), dtype=tf.float32),\n }\n return tfds.core.DatasetInfo(\n builder=self,\n description=_DESCRIPTION,\n features=tfds.features.FeaturesDict({\n \"image\": tfds.features.Image(),\n \"image/file_name\": tfds.features.Text(), # E.g. \"000001.png\".\n \"objects\": tfds.features.Sequence(annotations),\n }),\n homepage=_HOMEPAGE_URL,\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager):\n filenames = {\n \"images\": _DATA_URL + \"/\" + _IMAGES_FNAME,\n \"annotations\": _DATA_URL + \"/\" + _LABELS_FNAME,\n \"devkit\": _DATA_URL + \"/\" + _DEVKIT_FNAME,\n }\n files = dl_manager.download(filenames)\n train_images, validation_images, test_images = _build_splits(\n dl_manager.iter_archive(files[\"devkit\"]))\n\n return [\n tfds.core.SplitGenerator(\n name=tfds.Split.TRAIN,\n gen_kwargs={\n \"images\": dl_manager.iter_archive(files[\"images\"]),\n \"annotations\": dl_manager.iter_archive(files[\"annotations\"]),\n \"subdir\": \"training\",\n \"image_ids\": train_images,\n }),\n tfds.core.SplitGenerator(\n name=tfds.Split.VALIDATION,\n gen_kwargs={\n \"images\": dl_manager.iter_archive(files[\"images\"]),\n \"annotations\": dl_manager.iter_archive(files[\"annotations\"]),\n \"subdir\": \"training\",\n \"image_ids\": validation_images,\n }),\n tfds.core.SplitGenerator(\n name=tfds.Split.TEST,\n gen_kwargs={\n \"images\": dl_manager.iter_archive(files[\"images\"]),\n \"annotations\": dl_manager.iter_archive(files[\"annotations\"]),\n \"subdir\": \"training\",\n \"image_ids\": test_images,\n }),\n ]\n\n def _generate_examples(self, images, annotations, subdir, image_ids):\n \"\"\"Yields images and annotations.\n\n Args:\n images: object that iterates over the archive of images.\n annotations: object that iterates over the archive of annotations.\n subdir: subdirectory from which to extract images and annotations, e.g.\n training or testing.\n image_ids: file ids for images in this split.\n\n Yields:\n A tuple containing the example's key, and the example.\n \"\"\"\n cv2 = tfds.core.lazy_imports.cv2\n\n all_annotations = dict()\n for fpath, fobj in annotations:\n prefix, ext = os.path.splitext(fpath)\n if ext != \".txt\":\n continue\n if prefix.split(os.path.sep)[0] != subdir:\n continue\n\n # Key is the datapoint id. E.g. training/label_2/label_000016 -> 16.\n all_annotations[int(prefix[-6:])] = _parse_kitti_annotations(fobj)\n\n for fpath, fobj in images:\n prefix, ext = os.path.splitext(fpath)\n if ext != \".png\":\n continue\n if prefix.split(os.path.sep)[0] != subdir:\n continue\n image_id = int(prefix[-6:])\n if image_id not in image_ids:\n continue\n annotations = all_annotations[image_id]\n img = cv2.imdecode(\n np.frombuffer(fobj.read(), dtype=np.uint8), cv2.IMREAD_COLOR)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n height, width, _ = img.shape\n for obj in annotations:\n obj[\"bbox\"] = _build_bounding_box(obj[\"bbox_raw\"], height, width)\n del obj[\"bbox_raw\"]\n _, fname = os.path.split(fpath)\n record = {\"image\": img, \"image/file_name\": fname, \"objects\": annotations}\n yield fname, record\n\n\ndef _build_bounding_box(bbox, height, width):\n \"\"\"Builds and returns TFDS bounding box.\n\n Args:\n bbox: RawBoundingBox, bounding box in Kitti coordinates (origin top left).\n height: Image height in pixels.\n width: Image width in pixels.\n\n Returns:\n A TFDS BBox (origin bottom left).\n \"\"\"\n return tfds.features.BBox(\n ymin=(height - bbox.bottom) / height,\n ymax=(height - bbox.top) / height,\n xmin=bbox.left / width,\n xmax=bbox.right / width,\n )\n\n\ndef _parse_kitti_annotations(annotations_csv):\n \"\"\"Loads and parses the Kitti object annotations.\n\n Args:\n annotations_csv: csv file containing annotations for a single image.\n\n Returns:\n A list of labelled bounding boxes. Each bounding box is stored as a\n dictionary of features.\n \"\"\"\n annotations = []\n for line in annotations_csv:\n (obj_type, truncated, occluded, alpha, left, top, right, bottom, height,\n width, length, x, y, z,\n rotation_y) = list(csv.reader([line.decode()], delimiter=\" \"))[0]\n # DontCare objects lack annotations, so skip them.\n if obj_type == \"DontCare\":\n continue\n annotations.append({\n \"type\":\n obj_type,\n \"truncated\":\n float(truncated),\n \"occluded\":\n int(occluded),\n \"alpha\":\n float(alpha),\n \"bbox_raw\":\n RawBoundingBox(\n top=float(top),\n bottom=float(bottom),\n left=float(left),\n right=float(right)),\n \"dimensions\": [float(v) for v in [height, width, length]],\n \"location\": [float(v) for v in [x, y, z]],\n \"rotation_y\":\n float(rotation_y),\n })\n return annotations\n\n\ndef _build_splits(devkit):\n \"\"\"Splits the train data into train/val/test by video.\n\n Ensures that images from the same video do not traverse the splits.\n\n Args:\n devkit: object that iterates over the devkit archive.\n\n Returns:\n train_images: File ids for the training set images.\n validation_images: File ids for the validation set images.\n test_images: File ids for the test set images.\n \"\"\"\n mapping_line_ids = None\n mapping_lines = None\n for fpath, fobj in devkit:\n if fpath == os.path.join(\"mapping\", \"train_rand.txt\"):\n # Converts 1-based line index to 0-based line index.\n mapping_line_ids = [\n int(x.strip()) - 1 for x in fobj.read().decode(\"utf-8\").split(\",\")\n ]\n elif fpath == os.path.join(\"mapping\", \"train_mapping.txt\"):\n mapping_lines = fobj.read().splitlines()\n mapping_lines = [x.decode(\"utf-8\") for x in mapping_lines]\n\n assert mapping_line_ids\n assert mapping_lines\n\n video_to_image = collections.defaultdict(list)\n for image_id, mapping_lineid in enumerate(mapping_line_ids):\n line = mapping_lines[mapping_lineid]\n video_id = line.split(\" \")[1]\n video_to_image[video_id].append(image_id)\n\n # Sets numpy random state.\n numpy_original_state = np.random.get_state()\n np.random.seed(seed=123)\n\n # Max 1 for testing.\n num_test_videos = max(1,\n _TEST_SPLIT_PERCENT_VIDEOS * len(video_to_image) // 100)\n num_validation_videos = max(\n 1,\n _VALIDATION_SPLIT_PERCENT_VIDEOS * len(video_to_image) // 100)\n test_videos = set(\n np.random.choice(\n sorted(list(video_to_image.keys())), num_test_videos, replace=False))\n validation_videos = set(\n np.random.choice(\n sorted(list(set(video_to_image.keys()) - set(test_videos))),\n num_validation_videos,\n replace=False))\n test_images = []\n validation_images = []\n train_images = []\n for k, v in video_to_image.items():\n if k in test_videos:\n test_images.extend(v)\n elif k in validation_videos:\n validation_images.extend(v)\n else:\n train_images.extend(v)\n\n # Resets numpy random state.\n np.random.set_state(numpy_original_state)\n return train_images, validation_images, test_images\n", "# coding=utf-8\n# Copyright 2022 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"TensorFlow dataset for Binary Alphadigits.\"\"\"\nimport six.moves.urllib as urllib\nimport tensorflow as tf\nimport tensorflow_datasets.public_api as tfds\n\n_URL = 'https://cs.nyu.edu/~roweis/data/'\n\n_DESCRIPTION = (\"Binary 20x16 digits of '0' through '9' and capital 'A' \"\n \"through 'Z'. 39 examples of each class.\")\n\n_IMAGE_SHAPE = (20, 16, 1)\n\n_NAMES = [\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',\n 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',\n 'U', 'V', 'W', 'X', 'Y', 'Z'\n]\n\n_CITATION = \"\"\"\\\n\n\"\"\"\n\n\nclass BinaryAlphaDigits(tfds.core.GeneratorBasedBuilder):\n \"\"\"Binary alphadigits dataset.\"\"\"\n\n VERSION = tfds.core.Version('1.0.0')\n\n def _info(self):\n \"\"\"Define the Dataset info.\"\"\"\n\n return tfds.core.DatasetInfo(\n builder=self,\n description=(_DESCRIPTION),\n features=tfds.features.FeaturesDict({\n 'image': tfds.features.Image(shape=_IMAGE_SHAPE),\n 'label': tfds.features.ClassLabel(names=_NAMES),\n }),\n supervised_keys=('image', 'label'),\n homepage=_URL,\n citation=_CITATION)\n\n def _split_generators(self, dl_manager):\n \"\"\"Define Splits for training data.\"\"\"\n\n path = dl_manager.download(\n {'train': urllib.parse.urljoin(_URL, 'binaryalphadigs.mat')})\n\n return [\n tfds.core.SplitGenerator(\n name='train',\n gen_kwargs={\n 'data_dir_path': path['train'],\n },\n )\n ]\n\n def _generate_examples(self, data_dir_path):\n \"\"\"Generate Splits for training data.\"\"\"\n\n with tf.io.gfile.GFile(data_dir_path, 'rb') as f:\n mat = tfds.core.lazy_imports.scipy.io.loadmat(f)\n for i in range(len(mat['dat'])):\n label = mat['classlabels'][0][i].item()\n for j in range(len(mat['dat'][i])):\n image = mat['dat'][i][j].reshape(20, 16, 1)\n yield '%d_%d' % (i, j), {'label': label, 'image': image}\n", "# coding=utf-8\n# Copyright 2022 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Eurosat remote sensing benchmarking dataset.\"\"\"\n\nimport io\nimport os\n\nimport tensorflow as tf\nimport tensorflow_datasets.public_api as tfds\n\n_CITATION = \"\"\"\n@misc{helber2017eurosat,\n title={EuroSAT: A Novel Dataset and Deep Learning Benchmark for Land Use and Land Cover Classification},\n author={Patrick Helber and Benjamin Bischke and Andreas Dengel and Damian Borth},\n year={2017},\n eprint={1709.00029},\n archivePrefix={arXiv},\n primaryClass={cs.CV}\n}\n\"\"\"\n\n_DESCRIPTION = \"\"\"\\\nEuroSAT dataset is based on Sentinel-2 satellite images covering 13 spectral\nbands and consisting of 10 classes with 27000 labeled and\ngeo-referenced samples.\n\nTwo datasets are offered:\n- rgb: Contains only the optical R, G, B frequency bands encoded as JPEG image.\n- all: Contains all 13 bands in the original value range (float32).\n\nURL: https://github.com/phelber/eurosat\n\"\"\"\n\n_LABELS = [\n 'AnnualCrop', 'Forest', 'HerbaceousVegetation', 'Highway', 'Industrial',\n 'Pasture', 'PermanentCrop', 'Residential', 'River', 'SeaLake'\n]\n\n_URL = 'https://github.com/phelber/eurosat'\n\n_DATA_OPTIONS = ['rgb', 'all']\n\n\nclass EurosatConfig(tfds.core.BuilderConfig):\n \"\"\"BuilderConfig for eurosat.\"\"\"\n\n def __init__(self, selection=None, download_url=None, subdir=None, **kwargs):\n \"\"\"Constructs a EurosatConfig.\n\n Args:\n selection: `str`, one of `_DATA_OPTIONS`.\n download_url: `str`, download URL to the zip file.\n subdir: `str`, subdir within the zip file.\n **kwargs: keyword arguments forwarded to super.\n \"\"\"\n if selection not in _DATA_OPTIONS:\n raise ValueError('selection must be one of %s' % _DATA_OPTIONS)\n\n super(EurosatConfig, self).__init__(\n version=tfds.core.Version('2.0.0'), **kwargs)\n self.selection = selection\n self.download_url = download_url\n self.subdir = subdir\n\n\nclass Eurosat(tfds.core.GeneratorBasedBuilder):\n \"\"\"Eurosat remote sensing benchmarking dataset.\"\"\"\n\n BUILDER_CONFIGS = [\n EurosatConfig(\n selection='rgb',\n name='rgb',\n download_url='http://madm.dfki.de/files/sentinel/EuroSAT.zip',\n subdir='2750',\n description='Sentinel-2 RGB channels'),\n EurosatConfig(\n selection='all',\n name='all',\n download_url='http://madm.dfki.de/files/sentinel/EuroSATallBands.zip',\n subdir='ds/images/remote_sensing/otherDatasets/sentinel_2/tif',\n description='13 Sentinel-2 channels'),\n ]\n\n def _info(self):\n if self.builder_config.selection == 'rgb':\n features = tfds.features.FeaturesDict({\n 'image': tfds.features.Image(shape=[64, 64, 3]),\n 'label': tfds.features.ClassLabel(names=_LABELS),\n 'filename': tfds.features.Text(),\n })\n supervised_keys = ('image', 'label')\n elif self.builder_config.selection == 'all':\n features = tfds.features.FeaturesDict({\n 'sentinel2':\n tfds.features.Tensor(shape=[64, 64, 13], dtype=tf.float32),\n 'label':\n tfds.features.ClassLabel(names=_LABELS),\n 'filename':\n tfds.features.Text(),\n })\n supervised_keys = ('sentinel2', 'label')\n\n return tfds.core.DatasetInfo(\n builder=self,\n description=_DESCRIPTION,\n features=features,\n supervised_keys=supervised_keys,\n homepage=_URL,\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager):\n \"\"\"Returns SplitGenerators.\"\"\"\n path = dl_manager.download_and_extract(self.builder_config.download_url)\n path = os.path.join(path, self.builder_config.subdir)\n return [\n tfds.core.SplitGenerator(\n name=tfds.Split.TRAIN,\n gen_kwargs={\n 'path': path,\n 'selection': self.builder_config.selection\n },\n ),\n ]\n\n def _generate_examples(self, path, selection):\n \"\"\"Yields examples.\"\"\"\n for filename in tf.io.gfile.glob(os.path.join(path, '*', '*')):\n label = os.path.split(filename)[-1].split('_')[0]\n if selection == 'rgb':\n record = {\n 'image': filename,\n 'label': label,\n 'filename': os.path.basename(filename)\n }\n else:\n record = {\n 'sentinel2': _extract_channels(filename),\n 'label': label,\n 'filename': os.path.basename(filename)\n }\n yield f'{label}_{os.path.basename(filename)}', record\n\n\ndef _extract_channels(filename):\n with tf.io.gfile.GFile(filename, 'rb') as f:\n arr = tfds.core.lazy_imports.tifffile.imread(io.BytesIO(f.read()))\n\n arr = arr.astype('float32')\n return arr\n", "# coding=utf-8\n# Copyright 2022 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"cardiotox dataset.\"\"\"\nimport os\nimport tensorflow as tf\nimport tensorflow_datasets.public_api as tfds\n\n_DESCRIPTION = \"\"\"\nDrug Cardiotoxicity dataset [1-2] is a molecule classification task to detect\ncardiotoxicity caused by binding hERG target, a protein associated with heart\nbeat rhythm. The data covers over 9000 molecules with hERG activity.\n\nNote:\n\n1. The data is split into four splits: train, test-iid, test-ood1, test-ood2.\n\n2. Each molecule in the dataset has 2D graph annotations which is designed to\nfacilitate graph neural network modeling. Nodes are the atoms of the molecule\nand edges are the bonds. Each atom is represented as a vector encoding basic\natom information such as atom type. Similar logic applies to bonds.\n\n3. We include Tanimoto fingerprint distance (to training data) for each molecule\nin the test sets to facilitate research on distributional shift in graph domain.\n\nFor each example, the features include:\n atoms: a 2D tensor with shape (60, 27) storing node features. Molecules with\n less than 60 atoms are padded with zeros. Each atom has 27 atom features.\n pairs: a 3D tensor with shape (60, 60, 12) storing edge features. Each edge\n has 12 edge features.\n atom_mask: a 1D tensor with shape (60, ) storing node masks. 1 indicates the\n corresponding atom is real, othewise a padded one.\n pair_mask: a 2D tensor with shape (60, 60) storing edge masks. 1 indicates the\n corresponding edge is real, othewise a padded one.\n active: a one-hot vector indicating if the molecule is toxic or not. [0, 1]\n indicates it's toxic, otherwise [1, 0] non-toxic.\n\n\n## References\n[1]: V. B. Siramshetty et al. Critical Assessment of Artificial Intelligence\nMethods for Prediction of hERG Channel Inhibition in the Big Data Era.\n JCIM, 2020. https://pubs.acs.org/doi/10.1021/acs.jcim.0c00884\n\n[2]: K. Han et al. Reliable Graph Neural Networks for Drug Discovery Under\nDistributional Shift.\n NeurIPS DistShift Workshop 2021. https://arxiv.org/abs/2111.12951\n\"\"\"\n\n_CITATION = \"\"\"\n@ARTICLE{Han2021-tu,\n title = \"Reliable Graph Neural Networks for Drug Discovery Under\n Distributional Shift\",\n author = \"Han, Kehang and Lakshminarayanan, Balaji and Liu, Jeremiah\",\n month = nov,\n year = 2021,\n archivePrefix = \"arXiv\",\n primaryClass = \"cs.LG\",\n eprint = \"2111.12951\"\n}\n\n\"\"\"\n\n_LABEL_NAME = 'active'\n_NODES_FEATURE_NAME = 'atoms'\n_EDGES_FEATURE_NAME = 'pairs'\n_NODE_MASK_FEATURE_NAME = 'atom_mask'\n_EDGE_MASK_FEATURE_NAME = 'pair_mask'\n_DISTANCE_TO_TRAIN_NAME = 'dist2topk_nbs'\n_EXAMPLE_NAME = 'molecule_id'\n\n_MAX_NODES = 60\n_NODE_FEATURE_LENGTH = 27\n_EDGE_FEATURE_LENGTH = 12\n_NUM_CLASSES = 2\n\n_DATA_URL = tfds.core.gcs_path('downloads/cardiotox')\n_FILENAME_TRAIN = 'train_*.tfrecords*'\n_FILENAME_VAL = 'test_iid.tfrecords'\n_FILENAME_TEST = 'test_ood1.tfrecords'\n_FILENAME_TEST2 = 'test_ood2.tfrecords'\n\n\nclass Cardiotox(tfds.core.GeneratorBasedBuilder):\n \"\"\"DatasetBuilder for cardiotox dataset.\"\"\"\n\n VERSION = tfds.core.Version('1.0.0')\n RELEASE_NOTES = {\n '1.0.0': 'Initial release.',\n }\n\n def _info(self) -> tfds.core.DatasetInfo:\n \"\"\"Returns the dataset metadata.\"\"\"\n features = {\n _LABEL_NAME:\n tfds.features.Tensor(shape=[_NUM_CLASSES], dtype=tf.int64),\n _NODES_FEATURE_NAME:\n tfds.features.Tensor(\n shape=[_MAX_NODES, _NODE_FEATURE_LENGTH], dtype=tf.float32),\n _EDGES_FEATURE_NAME:\n tfds.features.Tensor(\n shape=[_MAX_NODES, _MAX_NODES, _EDGE_FEATURE_LENGTH],\n dtype=tf.float32),\n _NODE_MASK_FEATURE_NAME:\n tfds.features.Tensor(shape=[_MAX_NODES], dtype=tf.float32),\n _EDGE_MASK_FEATURE_NAME:\n tfds.features.Tensor(\n shape=[_MAX_NODES, _MAX_NODES], dtype=tf.float32),\n _DISTANCE_TO_TRAIN_NAME:\n tfds.features.Tensor(shape=[1], dtype=tf.float32),\n _EXAMPLE_NAME:\n tfds.features.Tensor(shape=[], dtype=tf.string),\n }\n return tfds.core.DatasetInfo(\n builder=self,\n description=_DESCRIPTION,\n features=tfds.features.FeaturesDict(features),\n supervised_keys=None,\n homepage='https://github.com/google/uncertainty-baselines/tree/main/baselines/drug_cardiotoxicity',\n citation=_CITATION,\n metadata=tfds.core.MetadataDict(\n max_nodes=_MAX_NODES,\n node_features=_NODE_FEATURE_LENGTH,\n edge_features=_EDGE_FEATURE_LENGTH))\n\n def _split_generators(self, dl_manager: tfds.download.DownloadManager):\n \"\"\"Returns SplitGenerators.\"\"\"\n\n return {\n tfds.Split.TRAIN:\n self._generate_examples(\n os.path.join(_DATA_URL, _FILENAME_TRAIN), is_training=True),\n tfds.Split.VALIDATION:\n self._generate_examples(\n os.path.join(_DATA_URL, _FILENAME_VAL), is_training=False),\n tfds.Split.TEST:\n self._generate_examples(\n os.path.join(_DATA_URL, _FILENAME_TEST), is_training=False),\n tfds.Split('test2'):\n self._generate_examples(\n os.path.join(_DATA_URL, _FILENAME_TEST2), is_training=False),\n }\n\n def _generate_examples(self, path, is_training):\n \"\"\"Yields examples.\"\"\"\n cycle_len = 10 if is_training else 1\n dataset = tf.data.Dataset.list_files(path)\n dataset = dataset.interleave(\n tf.data.TFRecordDataset, cycle_length=cycle_len)\n dataset = dataset.map(\n self.info.features.deserialize_example,\n num_parallel_calls=tf.data.experimental.AUTOTUNE)\n\n dataset = tfds.as_numpy(dataset)\n for example in dataset:\n yield example[_EXAMPLE_NAME], example\n", "# coding=utf-8\n# Copyright 2022 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"MIT Scene Parsing Benchmark (SceneParse150).\"\"\"\n\nimport os\nimport tensorflow as tf\nimport tensorflow_datasets.public_api as tfds\n\n_CITATION = \"\"\"\n@inproceedings{zhou2017scene,\ntitle={Scene Parsing through ADE20K Dataset},\nauthor={Zhou, Bolei and Zhao, Hang and Puig, Xavier and Fidler, Sanja and Barriuso, Adela and Torralba, Antonio},\nbooktitle={Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition},\nyear={2017}\n}\n\"\"\"\n\n_DESCRIPTION = \"\"\"\nScene parsing is to segment and parse an image into different image regions\nassociated with semantic categories, such as sky, road, person, and bed.\nMIT Scene Parsing Benchmark (SceneParse150) provides a standard training and\nevaluation platform for the algorithms of scene parsing.\n\"\"\"\n\n_TRAIN_URL = {\n \"images\":\n \"http://placeschallenge.csail.mit.edu/data/ChallengeData2017/images.tar\",\n \"annotations\":\n \"http://placeschallenge.csail.mit.edu/data/ChallengeData2017/annotations_instance.tar\"\n}\n\n\nclass SceneParse150(tfds.core.GeneratorBasedBuilder):\n \"\"\"MIT Scene Parsing Benchmark dataset.\"\"\"\n\n VERSION = tfds.core.Version(\"1.0.0\")\n\n def _info(self):\n\n return tfds.core.DatasetInfo(\n builder=self,\n description=_DESCRIPTION,\n features=tfds.features.FeaturesDict({\n \"image\": tfds.features.Image(encoding_format=\"jpeg\"),\n \"annotation\": tfds.features.Image(encoding_format=\"png\")\n }),\n supervised_keys=(\"image\", \"annotation\"),\n homepage=\"http://sceneparsing.csail.mit.edu/\",\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager):\n dl_paths = dl_manager.download_and_extract({\n \"images\": _TRAIN_URL[\"images\"],\n \"annotations\": _TRAIN_URL[\"annotations\"],\n })\n\n return [\n tfds.core.SplitGenerator(\n name=tfds.Split.TRAIN,\n gen_kwargs={\n \"images_dir_path\":\n os.path.join(dl_paths[\"images\"], \"images/training\"),\n \"annotations_dir_path\":\n os.path.join(dl_paths[\"annotations\"],\n \"annotations_instance/training\")\n },\n ),\n tfds.core.SplitGenerator(\n name=tfds.Split.TEST,\n gen_kwargs={\n \"images_dir_path\":\n os.path.join(dl_paths[\"images\"], \"images/validation\"),\n \"annotations_dir_path\":\n os.path.join(dl_paths[\"annotations\"],\n \"annotations_instance/validation\")\n },\n ),\n ]\n\n def _generate_examples(self, images_dir_path, annotations_dir_path):\n for image_file in tf.io.gfile.listdir(images_dir_path):\n # get the filename\n image_id = os.path.split(image_file)[1].split(\".\")[0]\n yield image_id, {\n \"image\":\n os.path.join(images_dir_path, \"{}.jpg\".format(image_id)),\n \"annotation\":\n os.path.join(annotations_dir_path, \"{}.png\".format(image_id))\n }\n", "# coding=utf-8\n# Copyright 2022 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"WebQuestions Benchmark for Question Answering.\"\"\"\n\nimport json\nimport re\n\nimport tensorflow as tf\nimport tensorflow_datasets.public_api as tfds\n\n_CITATION = \"\"\"\n@inproceedings{berant-etal-2013-semantic,\n title = \"Semantic Parsing on {F}reebase from Question-Answer Pairs\",\n author = \"Berant, Jonathan and\n Chou, Andrew and\n Frostig, Roy and\n Liang, Percy\",\n booktitle = \"Proceedings of the 2013 Conference on Empirical Methods in Natural Language Processing\",\n month = oct,\n year = \"2013\",\n address = \"Seattle, Washington, USA\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/D13-1160\",\n pages = \"1533--1544\",\n}\n\"\"\"\n_SPLIT_DOWNLOAD_URL = {\n 'train':\n 'https://worksheets.codalab.org/rest/bundles/0x4a763f8cde224c2da592b75f29e2f5c2/contents/blob/',\n 'test':\n 'https://worksheets.codalab.org/rest/bundles/0xe7bac352fce7448c9ef238fb0a297ec2/contents/blob/',\n}\n\n_DESCRIPTION = \"\"\"\\\nThis dataset consists of 6,642 question/answer pairs.\nThe questions are supposed to be answerable by Freebase, a large knowledge graph.\nThe questions are mostly centered around a single named entity.\nThe questions are popular ones asked on the web (at least in 2013).\n\"\"\"\n\n\nclass WebQuestions(tfds.core.GeneratorBasedBuilder):\n \"\"\"WebQuestions Benchmark for Question Answering.\"\"\"\n\n VERSION = tfds.core.Version('1.0.0')\n\n def _info(self):\n return tfds.core.DatasetInfo(\n builder=self,\n description=_DESCRIPTION,\n features=tfds.features.FeaturesDict({\n 'url': tfds.features.Text(),\n 'question': tfds.features.Text(),\n 'answers': tfds.features.Sequence(tfds.features.Text()),\n }),\n supervised_keys=None,\n homepage='https://worksheets.codalab.org/worksheets/0xba659fe363cb46e7a505c5b6a774dc8a',\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager):\n \"\"\"Returns SplitGenerators.\"\"\"\n file_paths = dl_manager.download(_SPLIT_DOWNLOAD_URL)\n\n return [\n tfds.core.SplitGenerator(\n name=split, gen_kwargs={'file_path': file_path})\n for split, file_path in file_paths.items()\n ]\n\n def _generate_examples(self, file_path):\n \"\"\"Parses split file and yields examples.\"\"\"\n\n def _target_to_answers(target):\n target = re.sub(r'^\\(list |\\)$', '', target)\n return [\n ''.join(ans) for ans in re.findall(\n r'\\(description (?:\"([^\"]+?)\"|([^)]+?))\\)\\w*', target)\n ]\n\n with tf.io.gfile.GFile(file_path) as f:\n examples = json.load(f)\n for i, ex in enumerate(examples):\n yield i, {\n 'url': ex['url'],\n 'question': ex['utterance'],\n 'answers': _target_to_answers(ex['targetValue']),\n }\n", "# coding=utf-8\n# Copyright 2022 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"assin2 dataset.\"\"\"\n\nimport tensorflow as tf\nimport tensorflow_datasets.public_api as tfds\nfrom tensorflow_datasets.text.assin2.assin2_utils import parse_xml_string\n\n_HOMEPAGE = 'https://sites.google.com/view/assin2/english'\n\n# pylint: disable=line-too-long\n_DESCRIPTION = f\"\"\"\\\n## Contextualization\nASSIN 2 is the second edition of the Avaliação de Similaridade Semântica e\nInferência Textual (Evaluating Semantic Similarity and Textual Entailment),\nand was a workshop collocated with [STIL 2019](http://www.google.com/url?q=http%3A%2F%2Fcomissoes.sbc.org.br%2Fce-pln%2Fstil2019%2F&sa=D&sntz=1&usg=AFQjCNHN8DosAsJ-gd48TfkXFX5YD6xM7g). It follows the [first edition of ASSIN](http://www.google.com/url?q=http%3A%2F%2Fpropor2016.di.fc.ul.pt%2F%3Fpage_id%3D381&sa=D&sntz=1&usg=AFQjCNHV7ySeNzH4k6MWKBLqO9yUkqiUqw),\nproposing a new shared task with new data.\n\nThe workshop evaluated systems that assess two types of relations between\ntwo sentences: Semantic Textual Similarity and Textual Entailment.\n\nSemantic Textual Similarity consists of quantifying the level of semantic\nequivalence between sentences, while Textual Entailment Recognition consists of\nclassifying whether the first sentence entails the second.\n\n## Data\nThe corpus used in ASSIN 2 is composed of rather simple sentences. Following\nthe procedures of SemEval 2014 Task 1, we tried to remove from the corpus named\nentities and indirect speech, and tried to have all verbs in the present tense.\nThe [annotation instructions](https://drive.google.com/open?id=1aUPhywEHD0r_pxPiTqZwS0fRj-1Xda2w)\ngiven to annotators are available (in Portuguese).\n\nThe training and validation data are composed, respectively, of 6,500 and 500\nsentence pairs in Brazilian Portuguese, annotated for entailment and\nsemantic similarity. Semantic similarity values range from 1 to 5, and text\nentailment classes are either entailment or none. The test data are composed of\napproximately 3,000 sentence pairs with the same annotation. All data were\nmanually annotated.\n\n## Evaluation\nEvaluation\nThe evaluation of submissions to ASSIN 2 was with the same metrics as the first\nASSIN, with the F1 of precision and recall as the main metric for text\nentailment and Pearson correlation for semantic similarity.\nThe [evaluation scripts](https://github.com/erickrf/assin) are the same as in\nthe last edition.\n\nPS.: Description is extracted from [official homepage]({_HOMEPAGE}).\n\"\"\"\n\n# pylint: disable=line-too-longm anomalous-backslash-in-string\n_CITATION = r\"\"\"\n@inproceedings{DBLP:conf/propor/RealFO20,\n author = {Livy Real and\n Erick Fonseca and\n Hugo Gon{\\c{c}}alo Oliveira},\n editor = {Paulo Quaresma and\n Renata Vieira and\n Sandra M. Alu{\\'{\\i}}sio and\n Helena Moniz and\n Fernando Batista and\n Teresa Gon{\\c{c}}alves},\n title = {The {ASSIN} 2 Shared Task: {A} Quick Overview},\n booktitle = {Computational Processing of the Portuguese Language - 14th International\n Conference, {PROPOR} 2020, Evora, Portugal, March 2-4, 2020, Proceedings},\n series = {Lecture Notes in Computer Science},\n volume = {12037},\n pages = {406--412},\n publisher = {Springer},\n year = {2020},\n url = {https://doi.org/10.1007/978-3-030-41505-1_39},\n doi = {10.1007/978-3-030-41505-1_39},\n timestamp = {Tue, 03 Mar 2020 09:40:18 +0100},\n biburl = {https://dblp.org/rec/conf/propor/RealFO20.bib},\n bibsource = {dblp computer science bibliography, https://dblp.org}\n}\n\"\"\"\n\n_DOWNLOAD_URLS = {\n 'train':\n 'https://drive.google.com/u/0/uc?id=1Q9j1a83CuKzsHCGaNulSkNxBm7Dkn7Ln&export=download',\n 'validation':\n 'https://drive.google.com/u/0/uc?id=1kb7xq6Mb3eaqe9cOAo70BaG9ypwkIqEU&export=download',\n 'test':\n 'https://drive.google.com/u/0/uc?id=1J3FpQaHxpM-FDfBUyooh-sZF-B-bM_lU&export=download',\n}\n\n\nclass Assin2(tfds.core.GeneratorBasedBuilder):\n \"\"\"DatasetBuilder for assin2 dataset.\"\"\"\n\n VERSION = tfds.core.Version('1.0.0')\n RELEASE_NOTES = {\n '1.0.0': 'Initial release.',\n }\n\n def _info(self) -> tfds.core.DatasetInfo:\n \"\"\"Returns the dataset metadata.\"\"\"\n return tfds.core.DatasetInfo(\n builder=self,\n description=_DESCRIPTION,\n features=tfds.features.FeaturesDict({\n 'text':\n tfds.features.Text(),\n 'hypothesis':\n tfds.features.Text(),\n 'id':\n tf.int32,\n 'entailment':\n tfds.features.ClassLabel(names=['None', 'Entailment']),\n 'similarity':\n tf.float32\n }),\n supervised_keys=None,\n homepage=_HOMEPAGE,\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager: tfds.download.DownloadManager):\n \"\"\"Returns SplitGenerators.\"\"\"\n path = dl_manager.download_and_extract(_DOWNLOAD_URLS)\n return {\n 'train': self._generate_examples(path['train']),\n 'validation': self._generate_examples(path['validation']),\n 'test': self._generate_examples(path['test'])\n }\n\n def _generate_examples(self, path):\n \"\"\"Yields examples.\"\"\"\n with tf.io.gfile.GFile(path) as f:\n pairs = parse_xml_string(f.read())\n\n for pair in pairs:\n yield pair.id, {\n 'text': pair.text,\n 'hypothesis': pair.hypothesis,\n 'id': pair.id,\n 'entailment': pair.entailment,\n 'similarity': pair.similarity\n }\n", "# coding=utf-8\n# Copyright 2022 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"TriviaQA: A Reading Comprehension Dataset.\"\"\"\n\nimport json\nimport os\n\nfrom absl import logging\nimport six\nimport tensorflow as tf\nimport tensorflow_datasets.public_api as tfds\n\n_CITATION = \"\"\"\n@article{2017arXivtriviaqa,\n author = {{Joshi}, Mandar and {Choi}, Eunsol and {Weld},\n Daniel and {Zettlemoyer}, Luke},\n title = \"{triviaqa: A Large Scale Distantly Supervised Challenge Dataset for Reading Comprehension}\",\n journal = {arXiv e-prints},\n year = 2017,\n eid = {arXiv:1705.03551},\n pages = {arXiv:1705.03551},\narchivePrefix = {arXiv},\n eprint = {1705.03551},\n}\n\"\"\"\n_DOWNLOAD_URL_TMPL = (\n \"http://nlp.cs.washington.edu/triviaqa/data/triviaqa-{}.tar.gz\")\n_TRAIN_FILE_FORMAT = \"*-train.json\"\n_VALIDATION_FILE_FORMAT = \"*-dev.json\"\n_TEST_FILE_FORMAT = \"*test-without-answers.json\"\n_WEB_EVIDENCE_DIR = \"evidence/web\"\n_WIKI_EVIDENCE_DIR = \"evidence/wikipedia\"\n\n_DESCRIPTION = \"\"\"\\\nTriviaqQA is a reading comprehension dataset containing over 650K\nquestion-answer-evidence triples. TriviaqQA includes 95K question-answer\npairs authored by trivia enthusiasts and independently gathered evidence\ndocuments, six per question on average, that provide high quality distant\nsupervision for answering the questions.\n\"\"\"\n\n_RC_DESCRIPTION = \"\"\"\\\nQuestion-answer pairs where all documents for a given question contain the\nanswer string(s).\n\"\"\"\n\n_UNFILTERED_DESCRIPTION = \"\"\"\\\n110k question-answer pairs for open domain QA where not all documents for a\ngiven question contain the answer string(s). This makes the unfiltered dataset\nmore appropriate for IR-style QA.\n\"\"\"\n\n_CONTEXT_ADDENDUM = \"Includes context from Wikipedia and search results.\"\n\n\ndef _web_evidence_dir(tmp_dir):\n return tf.io.gfile.glob(os.path.join(tmp_dir, _WEB_EVIDENCE_DIR))\n\n\ndef _wiki_evidence_dir(tmp_dir):\n return tf.io.gfile.glob(os.path.join(tmp_dir, _WIKI_EVIDENCE_DIR))\n\n\nclass TriviaQAConfig(tfds.core.BuilderConfig):\n \"\"\"BuilderConfig for TriviaQA.\"\"\"\n\n def __init__(self, *, unfiltered=False, exclude_context=False, **kwargs):\n \"\"\"BuilderConfig for TriviaQA.\n\n Args:\n unfiltered: bool, whether to use the unfiltered version of the dataset,\n intended for open-domain QA.\n exclude_context: bool, whether to exclude Wikipedia and search context for\n reduced size.\n **kwargs: keyword arguments forwarded to super.\n \"\"\"\n name = \"unfiltered\" if unfiltered else \"rc\"\n if exclude_context:\n name += \".nocontext\"\n description = _UNFILTERED_DESCRIPTION if unfiltered else _RC_DESCRIPTION\n if not exclude_context:\n description += _CONTEXT_ADDENDUM\n super(TriviaQAConfig, self).__init__(\n name=name,\n description=description,\n version=tfds.core.Version(\"1.1.0\"),\n **kwargs)\n self.unfiltered = unfiltered\n self.exclude_context = exclude_context\n\n\nclass TriviaQA(tfds.core.GeneratorBasedBuilder):\n \"\"\"TriviaQA is a reading comprehension dataset.\n\n It containss over 650K question-answer-evidence triples.\n \"\"\"\n\n BUILDER_CONFIGS = [\n TriviaQAConfig(unfiltered=False, exclude_context=False), # rc\n TriviaQAConfig(unfiltered=False, exclude_context=True), # rc.nocontext\n TriviaQAConfig(unfiltered=True, exclude_context=False), # unfiltered\n TriviaQAConfig(unfiltered=True, exclude_context=True),\n # unfilered.nocontext\n ]\n\n def _info(self):\n return tfds.core.DatasetInfo(\n builder=self,\n description=_DESCRIPTION,\n features=tfds.features.FeaturesDict({\n \"question\":\n tfds.features.Text(),\n \"question_id\":\n tfds.features.Text(),\n \"question_source\":\n tfds.features.Text(),\n \"entity_pages\":\n tfds.features.Sequence({\n \"doc_source\": tfds.features.Text(),\n \"filename\": tfds.features.Text(),\n \"title\": tfds.features.Text(),\n \"wiki_context\": tfds.features.Text(),\n }),\n \"search_results\":\n tfds.features.Sequence({\n \"description\": tfds.features.Text(),\n \"filename\": tfds.features.Text(),\n \"rank\": tf.int32,\n \"title\": tfds.features.Text(),\n \"url\": tfds.features.Text(),\n \"search_context\": tfds.features.Text(),\n }),\n \"answer\":\n tfds.features.FeaturesDict({\n \"aliases\":\n tfds.features.Sequence(tfds.features.Text()),\n \"normalized_aliases\":\n tfds.features.Sequence(tfds.features.Text()),\n \"matched_wiki_entity_name\":\n tfds.features.Text(),\n \"normalized_matched_wiki_entity_name\":\n tfds.features.Text(),\n \"normalized_value\":\n tfds.features.Text(),\n \"type\":\n tfds.features.Text(),\n \"value\":\n tfds.features.Text(),\n }),\n }),\n supervised_keys=None,\n homepage=\"http://nlp.cs.washington.edu/triviaqa/\",\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager):\n \"\"\"Returns SplitGenerators.\"\"\"\n cfg = self.builder_config\n download_urls = dict()\n if not (cfg.unfiltered and cfg.exclude_context):\n download_urls[\"rc\"] = _DOWNLOAD_URL_TMPL.format(\"rc\")\n if cfg.unfiltered:\n download_urls[\"unfiltered\"] = _DOWNLOAD_URL_TMPL.format(\"unfiltered\")\n file_paths = dl_manager.download_and_extract(download_urls)\n\n qa_dir = (\n os.path.join(file_paths[\"unfiltered\"], \"triviaqa-unfiltered\")\n if cfg.unfiltered else os.path.join(file_paths[\"rc\"], \"qa\"))\n train_files = tf.io.gfile.glob(os.path.join(qa_dir, _TRAIN_FILE_FORMAT))\n valid_files = tf.io.gfile.glob(\n os.path.join(qa_dir, _VALIDATION_FILE_FORMAT))\n test_files = tf.io.gfile.glob(os.path.join(qa_dir, _TEST_FILE_FORMAT))\n\n if cfg.exclude_context:\n web_evidence_dir = None\n wiki_evidence_dir = None\n else:\n web_evidence_dir = os.path.join(file_paths[\"rc\"], _WEB_EVIDENCE_DIR)\n wiki_evidence_dir = os.path.join(file_paths[\"rc\"], _WIKI_EVIDENCE_DIR)\n\n return [\n tfds.core.SplitGenerator(\n name=tfds.Split.TRAIN,\n gen_kwargs={\n \"files\": train_files,\n \"web_dir\": web_evidence_dir,\n \"wiki_dir\": wiki_evidence_dir\n }),\n tfds.core.SplitGenerator(\n name=tfds.Split.VALIDATION,\n gen_kwargs={\n \"files\": valid_files,\n \"web_dir\": web_evidence_dir,\n \"wiki_dir\": wiki_evidence_dir\n }),\n tfds.core.SplitGenerator(\n name=tfds.Split.TEST,\n gen_kwargs={\n \"files\": test_files,\n \"web_dir\": web_evidence_dir,\n \"wiki_dir\": wiki_evidence_dir\n }),\n ]\n\n def _generate_examples(self, files, web_dir, wiki_dir):\n \"\"\"This function returns the examples.\"\"\"\n\n def parse_example(article):\n \"\"\"Return a single example from an article JSON record.\"\"\"\n\n def _strip(collection):\n return [item.strip() for item in collection]\n\n if \"Answer\" in article:\n answer = article[\"Answer\"]\n answer_dict = {\n \"aliases\":\n _strip(answer[\"Aliases\"]),\n \"normalized_aliases\":\n _strip(answer[\"NormalizedAliases\"]),\n \"matched_wiki_entity_name\":\n answer.get(\"MatchedWikiEntryName\", \"\").strip(),\n \"normalized_matched_wiki_entity_name\":\n answer.get(\"NormalizedMatchedWikiEntryName\", \"\").strip(),\n \"normalized_value\":\n answer[\"NormalizedValue\"].strip(),\n \"type\":\n answer[\"Type\"].strip(),\n \"value\":\n answer[\"Value\"].strip(),\n }\n else:\n answer_dict = {\n \"aliases\": [],\n \"normalized_aliases\": [],\n \"matched_wiki_entity_name\": \"<unk>\",\n \"normalized_matched_wiki_entity_name\": \"<unk>\",\n \"normalized_value\": \"<unk>\",\n \"type\": \"\",\n \"value\": \"<unk>\",\n }\n\n if self.builder_config.exclude_context:\n article[\"SearchResults\"] = []\n article[\"EntityPages\"] = []\n\n def _add_context(collection, context_field, file_dir):\n \"\"\"Adds context from file, or skips if file does not exist.\"\"\"\n new_items = []\n for item in collection:\n if \"Filename\" not in item:\n logging.info(\"Missing context 'Filename', skipping.\")\n continue\n\n new_item = item.copy()\n fname = item[\"Filename\"]\n try:\n with tf.io.gfile.GFile(os.path.join(file_dir, fname)) as f:\n new_item[context_field] = f.read()\n except (IOError, tf.errors.NotFoundError):\n logging.info(\"File does not exist, skipping: %s\", fname)\n continue\n new_items.append(new_item)\n return new_items\n\n def _strip_if_str(v):\n return v.strip() if isinstance(v, six.string_types) else v\n\n def _transpose_and_strip_dicts(dicts, field_names):\n return {\n tfds.core.naming.camelcase_to_snakecase(k):\n [_strip_if_str(d[k]) for d in dicts] for k in field_names\n }\n\n search_results = _transpose_and_strip_dicts(\n _add_context(\n article.get(\"SearchResults\", []), \"SearchContext\", web_dir),\n [\"Description\", \"Filename\", \"Rank\", \"Title\", \"Url\", \"SearchContext\"])\n\n entity_pages = _transpose_and_strip_dicts(\n _add_context(article.get(\"EntityPages\", []), \"WikiContext\", wiki_dir),\n [\"DocSource\", \"Filename\", \"Title\", \"WikiContext\"])\n\n question = article[\"Question\"].strip()\n question_id = article[\"QuestionId\"]\n question_source = article[\"QuestionSource\"].strip()\n\n return {\n \"entity_pages\": entity_pages,\n \"search_results\": search_results,\n \"question\": question,\n \"question_id\": question_id,\n \"question_source\": question_source,\n \"answer\": answer_dict,\n }\n\n for filepath in files:\n logging.info(\"generating examples from = %s\", filepath)\n fname = os.path.basename(filepath)\n\n with tf.io.gfile.GFile(filepath) as f:\n current_record = \"\"\n for line in f:\n if line == \" {\\n\":\n current_record = line\n elif line.startswith(\" }\"): # Handles final record as well.\n article = json.loads(current_record + \"}\")\n current_record = \"\"\n example = parse_example(article)\n yield \"%s_%s\" % (fname, example[\"question_id\"]), example\n else:\n current_record += line\n", "# coding=utf-8\n# Copyright 2022 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"TED talk high/low-resource paired language data set from Qi, et al. 2018.\"\"\"\n\nimport os\n\nimport tensorflow as tf\nimport tensorflow_datasets.public_api as tfds\n\n_DESCRIPTION = \"\"\"\\\nData sets derived from TED talk transcripts for comparing similar language pairs\nwhere one is high resource and the other is low resource.\n\"\"\"\n\n_CITATION = \"\"\"\\\n@inproceedings{Ye2018WordEmbeddings,\n author = {Ye, Qi and Devendra, Sachan and Matthieu, Felix and Sarguna, Padmanabhan and Graham, Neubig},\n title = {When and Why are pre-trained word embeddings useful for Neural Machine Translation},\n booktitle = {HLT-NAACL},\n year = {2018},\n }\n\"\"\"\n\n_DATA_URL = \"http://www.phontron.com/data/qi18naacl-dataset.tar.gz\"\n\n_VALID_LANGUAGE_PAIRS = (\n (\"az\", \"en\"),\n (\"az_tr\", \"en\"),\n (\"be\", \"en\"),\n (\"be_ru\", \"en\"),\n (\"es\", \"pt\"),\n (\"fr\", \"pt\"),\n (\"gl\", \"en\"),\n (\"gl_pt\", \"en\"),\n (\"he\", \"pt\"),\n (\"it\", \"pt\"),\n (\"pt\", \"en\"),\n (\"ru\", \"en\"),\n (\"ru\", \"pt\"),\n (\"tr\", \"en\"),\n)\n\n\nclass TedHrlrConfig(tfds.core.BuilderConfig):\n \"\"\"BuilderConfig for TED talk data comparing high/low resource languages.\"\"\"\n\n def __init__(self, *, language_pair=(None, None), **kwargs):\n \"\"\"BuilderConfig for TED talk data comparing high/low resource languages.\n\n The first language in `language_pair` should either be a 2-letter coded\n string or two such strings joined by an underscore (e.g., \"az\" or \"az_tr\").\n In cases where it contains two languages, the train data set will contain an\n (unlabelled) mix of the two languages and the validation and test sets\n will contain only the first language. This dataset will refer to the\n source language by the 5-letter string with the underscore. The second\n language in `language_pair` must be a 2-letter coded string.\n\n For example, to get pairings between Russian and English, specify\n `(\"ru\", \"en\")` as `language_pair`. To get a mix of Belarusian and Russian in\n the training set and purely Belarusian in the validation and test sets,\n specify `(\"be_ru\", \"en\")`.\n\n Args:\n language_pair: pair of languages that will be used for translation. The\n first will be used as source and second as target in supervised mode.\n **kwargs: keyword arguments forwarded to super.\n \"\"\"\n name = \"%s_to_%s\" % (language_pair[0].replace(\"_\", \"\"), language_pair[1])\n\n description = (\"Translation dataset from %s to %s in plain text.\") % (\n language_pair[0], language_pair[1])\n super(TedHrlrConfig, self).__init__(\n name=name, description=description, **kwargs)\n\n # Validate language pair.\n assert language_pair in _VALID_LANGUAGE_PAIRS, (\n \"Config language pair (%s, \"\n \"%s) not supported\") % language_pair\n\n self.language_pair = language_pair\n\n\nclass TedHrlrTranslate(tfds.core.GeneratorBasedBuilder):\n \"\"\"TED talk data set for comparing high and low resource languages.\"\"\"\n\n BUILDER_CONFIGS = [\n TedHrlrConfig( # pylint: disable=g-complex-comprehension\n language_pair=pair,\n version=tfds.core.Version(\"1.0.0\"),\n release_notes={\n \"1.0.0\": \"New split API (https://tensorflow.org/datasets/splits)\",\n },\n ) for pair in _VALID_LANGUAGE_PAIRS\n ]\n\n def _info(self):\n return tfds.core.DatasetInfo(\n builder=self,\n description=_DESCRIPTION,\n features=tfds.features.Translation(\n languages=self.builder_config.language_pair),\n homepage=\"https://github.com/neulab/word-embeddings-for-nmt\",\n supervised_keys=self.builder_config.language_pair,\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager):\n dl_dir = dl_manager.download_and_extract(_DATA_URL)\n source, target = self.builder_config.language_pair\n\n data_dir = os.path.join(dl_dir, \"datasets\", \"%s_to_%s\" % (source, target))\n\n return [\n tfds.core.SplitGenerator(\n name=tfds.Split.TRAIN,\n gen_kwargs={\n \"source_file\":\n os.path.join(data_dir,\n \"{}.train\".format(source.replace(\"_\", \"-\"))),\n \"target_file\":\n os.path.join(data_dir, \"{}.train\".format(target))\n }),\n tfds.core.SplitGenerator(\n name=tfds.Split.VALIDATION,\n gen_kwargs={\n \"source_file\":\n os.path.join(data_dir,\n \"{}.dev\".format(source.split(\"_\")[0])),\n \"target_file\":\n os.path.join(data_dir, \"{}.dev\".format(target))\n }),\n tfds.core.SplitGenerator(\n name=tfds.Split.TEST,\n gen_kwargs={\n \"source_file\":\n os.path.join(data_dir,\n \"{}.test\".format(source.split(\"_\")[0])),\n \"target_file\":\n os.path.join(data_dir, \"{}.test\".format(target))\n }),\n ]\n\n def _generate_examples(self, source_file, target_file):\n \"\"\"This function returns the examples in the raw (text) form.\"\"\"\n with tf.io.gfile.GFile(source_file) as f:\n source_sentences = f.read().split(\"\\n\")\n with tf.io.gfile.GFile(target_file) as f:\n target_sentences = f.read().split(\"\\n\")\n\n assert len(target_sentences) == len(\n source_sentences), \"Sizes do not match: %d vs %d for %s vs %s.\" % (len(\n source_sentences), len(target_sentences), source_file, target_file)\n\n source, target = self.builder_config.language_pair\n for idx, (l1, l2) in enumerate(zip(source_sentences, target_sentences)):\n result = {source: l1, target: l2}\n # Make sure that both translations are non-empty.\n if all(result.values()):\n yield idx, result\n", "# coding=utf-8\n# Copyright 2022 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for mujoco_build_configs.\"\"\"\n\nimport tensorflow as tf\nfrom tensorflow_datasets.d4rl import dataset_builder\n\n\ndef _mujoco_replay_datasets():\n \"\"\"Set of Mujoco datasets with replay.\"\"\"\n return {\n 'v1-medium-replay', 'v1-full-replay', 'v2-medium-replay', 'v2-full-replay'\n }\n\n\ndef _mujoco_full_metadata_datasets():\n \"\"\"Set of Mujoco datasets that contain all of the metadata fields.\"\"\"\n return {'v1-expert', 'v2-expert', 'v1-medium', 'v2-medium'}\n\n\nclass MujocoDatasetTest(tf.test.TestCase):\n\n def test_builder_config_step_metadata(self):\n for config in dataset_builder.MUJOCO_BUILDER_CONFIGS:\n if config.name in _mujoco_replay_datasets():\n self.assertEqual(config.float_type, tf.float64)\n else:\n self.assertEqual(config.float_type, tf.float32)\n\n def test_builder_config_float_type(self):\n for config in dataset_builder.MUJOCO_BUILDER_CONFIGS:\n if config.dataset_dir != 'gym_mujoco':\n self.assertTrue(config.step_metadata_keys,\n f'Config {config.name} should contain step metadata.')\n else:\n self.assertFalse(\n config.step_metadata_keys,\n f'Config {config.name} should NOT contain step metadata.')\n\n def test_builder_config_episode_metadata(self):\n for config in dataset_builder.MUJOCO_BUILDER_CONFIGS:\n if config.name in _mujoco_replay_datasets():\n self.assertTrue(\n config.episode_metadata_keys,\n f'Config {config.name} should contain episode metadata.')\n self.assertFalse(\n config.has_policy_metadata,\n f'Config {config.name} should NOT contain policy metadata.')\n self.assertFalse(\n config.has_policy_last_fc_log_std,\n f'Config {config.name} should NOT contain policy values for last_fc_log_std.'\n )\n elif config.name in _mujoco_full_metadata_datasets():\n self.assertTrue(\n config.episode_metadata_keys,\n f'Config {config.name} should contain episode metadata.')\n self.assertTrue(\n config.has_policy_metadata,\n f'Config {config.name} should contain policy metadata.')\n self.assertTrue(\n config.has_policy_last_fc_log_std,\n f'Config {config.name} should contain policy values for last_fc_log_std.'\n )\n else:\n self.assertFalse(\n config.episode_metadata_keys,\n f'Config {config.name} should NOT contain episode metadata.')\n self.assertFalse(\n config.has_policy_metadata,\n f'Config {config.name} should NOT contain policy metadata.')\n self.assertFalse(\n config.has_policy_last_fc_log_std,\n f'Config {config.name} should NOT contain policy values for last_fc_log_std.'\n )\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# coding=utf-8\n# Copyright 2022 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"The Multi-Genre NLI Corpus.\"\"\"\n\nimport os\n\nimport tensorflow as tf\nimport tensorflow_datasets.public_api as tfds\n\n_CITATION = \"\"\"\\\n@InProceedings{N18-1101,\n author = \"Williams, Adina\n and Nangia, Nikita\n and Bowman, Samuel\",\n title = \"A Broad-Coverage Challenge Corpus for\n Sentence Understanding through Inference\",\n booktitle = \"Proceedings of the 2018 Conference of\n the North American Chapter of the\n Association for Computational Linguistics:\n Human Language Technologies, Volume 1 (Long\n Papers)\",\n year = \"2018\",\n publisher = \"Association for Computational Linguistics\",\n pages = \"1112--1122\",\n location = \"New Orleans, Louisiana\",\n url = \"http://aclweb.org/anthology/N18-1101\"\n}\n\"\"\"\n\n_DESCRIPTION = \"\"\"\\\nThe Multi-Genre Natural Language Inference (MultiNLI) corpus is a\ncrowd-sourced collection of 433k sentence pairs annotated with textual\nentailment information. The corpus is modeled on the SNLI corpus, but differs in\nthat covers a range of genres of spoken and written text, and supports a\ndistinctive cross-genre generalization evaluation. The corpus served as the\nbasis for the shared task of the RepEval 2017 Workshop at EMNLP in Copenhagen.\n\"\"\"\n\n\nclass MultiNLI(tfds.core.GeneratorBasedBuilder):\n \"\"\"MultiNLI: The Stanford Question Answering Dataset. Version 1.1.\"\"\"\n\n VERSION = tfds.core.Version(\"1.1.0\")\n\n def _info(self):\n return tfds.core.DatasetInfo(\n builder=self,\n description=_DESCRIPTION,\n features=tfds.features.FeaturesDict({\n \"premise\":\n tfds.features.Text(),\n \"hypothesis\":\n tfds.features.Text(),\n \"label\":\n tfds.features.ClassLabel(\n names=[\"entailment\", \"neutral\", \"contradiction\"]),\n }),\n # No default supervised_keys (as we have to pass both premise\n # and hypothesis as input).\n supervised_keys=None,\n homepage=\"https://www.nyu.edu/projects/bowman/multinli/\",\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager):\n\n downloaded_dir = dl_manager.download_and_extract(\n \"https://cims.nyu.edu/~sbowman/multinli/multinli_1.0.zip\")\n mnli_path = os.path.join(downloaded_dir, \"multinli_1.0\")\n train_path = os.path.join(mnli_path, \"multinli_1.0_train.txt\")\n matched_validation_path = os.path.join(mnli_path,\n \"multinli_1.0_dev_matched.txt\")\n mismatched_validation_path = os.path.join(\n mnli_path, \"multinli_1.0_dev_mismatched.txt\")\n\n return [\n tfds.core.SplitGenerator(\n name=tfds.Split.TRAIN, gen_kwargs={\"filepath\": train_path}),\n tfds.core.SplitGenerator(\n name=\"validation_matched\",\n gen_kwargs={\"filepath\": matched_validation_path}),\n tfds.core.SplitGenerator(\n name=\"validation_mismatched\",\n gen_kwargs={\"filepath\": mismatched_validation_path}),\n ]\n\n def _generate_examples(self, filepath):\n \"\"\"Generate mnli examples.\n\n Args:\n filepath: a string\n\n Yields:\n dictionaries containing \"premise\", \"hypothesis\" and \"label\" strings\n \"\"\"\n for idx, line in enumerate(tf.io.gfile.GFile(filepath, \"rb\")):\n if idx == 0:\n continue # skip header\n line = tf.compat.as_text(line.strip())\n split_line = line.split(\"\\t\")\n # Examples not marked with a three out of five consensus are marked with\n # \"-\" and should not be used in standard evaluations.\n if split_line[0] == \"-\":\n continue\n # Works for both splits even though dev has some extra human labels.\n yield idx, {\n \"premise\": split_line[5],\n \"hypothesis\": split_line[6],\n \"label\": split_line[0]\n }\n" ]
[ [ "tensorflow.io.gfile.GFile" ], [ "tensorflow.io.gfile.exists", "tensorflow.io.gfile.GFile" ], [ "numpy.random.get_state", "numpy.random.set_state", "numpy.random.seed" ], [ "tensorflow.io.gfile.GFile" ], [ "tensorflow.io.gfile.GFile" ], [ "tensorflow.data.Dataset.list_files" ], [ "tensorflow.io.gfile.listdir" ], [ "tensorflow.io.gfile.GFile" ], [ "tensorflow.io.gfile.GFile" ], [ "tensorflow.io.gfile.GFile" ], [ "tensorflow.io.gfile.GFile" ], [ "tensorflow.test.main" ], [ "tensorflow.io.gfile.GFile" ] ]
[ { "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": [ "1.10" ] }, { "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": [] } ]
AK391/mt3
[ "d43c95ccbf9caa08d18e985ca2f2fc7e286a2f66" ]
[ "mt3/datasets.py" ]
[ "# Copyright 2021 The MT3 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\"\"\"Dataset configurations.\"\"\"\n\nimport dataclasses\nfrom typing import Mapping, Sequence, Union\n\nfrom mt3 import note_sequences\nimport tensorflow as tf\n\n\[email protected]\nclass InferEvalSplit:\n # key in dictionary containing all dataset splits\n name: str\n # task name suffix (each eval split is a separate task)\n suffix: str\n # whether or not to include in the mixture of all eval tasks\n include_in_mixture: bool = True\n\n\[email protected]\nclass DatasetConfig:\n \"\"\"Configuration for a transcription dataset.\"\"\"\n # dataset name\n name: str\n # mapping from split name to path\n paths: Mapping[str, str]\n # mapping from feature name to feature\n features: Mapping[str, Union[tf.io.FixedLenFeature,\n tf.io.FixedLenSequenceFeature]]\n # training split name\n train_split: str\n # training eval split name\n train_eval_split: str\n # list of infer eval split specs\n infer_eval_splits: Sequence[InferEvalSplit]\n # list of track specs to be used for metrics\n track_specs: Sequence[note_sequences.TrackSpec] = dataclasses.field(\n default_factory=list)\n\nMAESTROV1_CONFIG = DatasetConfig(\n name='maestrov1',\n paths={\n 'train':\n 'gs://magentadata/datasets/maestro/v1.0.0/maestro-v1.0.0_ns_wav_train.tfrecord-?????-of-00010',\n 'train_subset':\n 'gs://magentadata/datasets/maestro/v1.0.0/maestro-v1.0.0_ns_wav_train.tfrecord-00002-of-00010',\n 'validation':\n 'gs://magentadata/datasets/maestro/v1.0.0/maestro-v1.0.0_ns_wav_validation.tfrecord-?????-of-00010',\n 'validation_subset':\n 'gs://magentadata/datasets/maestro/v1.0.0/maestro-v1.0.0_ns_wav_validation.tfrecord-0000[06]-of-00010',\n 'test':\n 'gs://magentadata/datasets/maestro/v1.0.0/maestro-v1.0.0_ns_wav_test.tfrecord-?????-of-00010'\n },\n features={\n 'audio': tf.io.FixedLenFeature([], dtype=tf.string),\n 'sequence': tf.io.FixedLenFeature([], dtype=tf.string),\n 'id': tf.io.FixedLenFeature([], dtype=tf.string)\n },\n train_split='train',\n train_eval_split='validation_subset',\n infer_eval_splits=[\n InferEvalSplit(name='train', suffix='eval_train_full',\n include_in_mixture=False),\n InferEvalSplit(name='train_subset', suffix='eval_train'),\n InferEvalSplit(name='validation', suffix='validation_full',\n include_in_mixture=False),\n InferEvalSplit(name='validation_subset', suffix='validation'),\n InferEvalSplit(name='test', suffix='test', include_in_mixture=False)\n ])\n\n\nMAESTROV3_CONFIG = DatasetConfig(\n name='maestrov3',\n paths={\n 'train':\n 'gs://magentadata/datasets/maestro/v3.0.0/maestro-v3.0.0_ns_wav_train.tfrecord-?????-of-00025',\n 'train_subset':\n 'gs://magentadata/datasets/maestro/v3.0.0/maestro-v3.0.0_ns_wav_train.tfrecord-00004-of-00025',\n 'validation':\n 'gs://magentadata/datasets/maestro/v3.0.0/maestro-v3.0.0_ns_wav_validation.tfrecord-?????-of-00025',\n 'validation_subset':\n 'gs://magentadata/datasets/maestro/v3.0.0/maestro-v3.0.0_ns_wav_validation.tfrecord-0002?-of-00025',\n 'test':\n 'gs://magentadata/datasets/maestro/v3.0.0/maestro-v3.0.0_ns_wav_test.tfrecord-?????-of-00025'\n },\n features={\n 'audio': tf.io.FixedLenFeature([], dtype=tf.string),\n 'sequence': tf.io.FixedLenFeature([], dtype=tf.string),\n 'id': tf.io.FixedLenFeature([], dtype=tf.string)\n },\n train_split='train',\n train_eval_split='validation_subset',\n infer_eval_splits=[\n InferEvalSplit(name='train', suffix='eval_train_full',\n include_in_mixture=False),\n InferEvalSplit(name='train_subset', suffix='eval_train'),\n InferEvalSplit(name='validation', suffix='validation_full',\n include_in_mixture=False),\n InferEvalSplit(name='validation_subset', suffix='validation'),\n InferEvalSplit(name='test', suffix='test', include_in_mixture=False)\n ])\n\n\nGUITARSET_CONFIG = DatasetConfig(\n name='guitarset',\n paths={\n 'train':\n 'gs://mt3/data/datasets/guitarset/train.tfrecord-?????-of-00019',\n 'validation':\n 'gs://mt3/data/datasets/guitarset/validation.tfrecord-?????-of-00006',\n },\n features={\n 'sequence': tf.io.FixedLenFeature([], dtype=tf.string),\n 'audio': tf.io.FixedLenFeature([], dtype=tf.string),\n 'velocity_range': tf.io.FixedLenFeature([], dtype=tf.string),\n 'id': tf.io.FixedLenFeature([], dtype=tf.string),\n },\n train_split='train',\n train_eval_split='validation',\n infer_eval_splits=[\n InferEvalSplit(name='train', suffix='eval_train'),\n InferEvalSplit(name='validation', suffix='validation'),\n ])\n\n\nURMP_CONFIG = DatasetConfig(\n name='urmp',\n paths={\n 'train': 'gs://mt3/data/datasets/urmp/train.tfrecord',\n 'validation': 'gs://mt3/data/datasets/urmp/validation.tfrecord',\n },\n features={\n 'id': tf.io.FixedLenFeature([], dtype=tf.string),\n 'tracks': tf.io.FixedLenSequenceFeature(\n [], dtype=tf.int64, allow_missing=True),\n 'inst_names': tf.io.FixedLenSequenceFeature(\n [], dtype=tf.string, allow_missing=True),\n 'audio': tf.io.FixedLenFeature([], dtype=tf.string),\n 'sequence': tf.io.FixedLenFeature([], dtype=tf.string),\n 'instrument_sequences': tf.io.FixedLenSequenceFeature(\n [], dtype=tf.string, allow_missing=True),\n },\n train_split='train',\n train_eval_split='validation',\n infer_eval_splits=[\n InferEvalSplit(name='train', suffix='eval_train'),\n InferEvalSplit(name='validation', suffix='validation')\n ])\n\n\nMUSICNET_CONFIG = DatasetConfig(\n name='musicnet',\n paths={\n 'train':\n 'gs://mt3/data/datasets/musicnet/musicnet-train.tfrecord-?????-of-00036',\n 'validation':\n 'gs://mt3/data/datasets/musicnet/musicnet-validation.tfrecord-?????-of-00005',\n 'test':\n 'gs://mt3/data/datasets/musicnet/musicnet-test.tfrecord-?????-of-00003'\n },\n features={\n 'id': tf.io.FixedLenFeature([], dtype=tf.string),\n 'sample_rate': tf.io.FixedLenFeature([], dtype=tf.float32),\n 'audio': tf.io.FixedLenSequenceFeature(\n [], dtype=tf.float32, allow_missing=True),\n 'sequence': tf.io.FixedLenFeature([], dtype=tf.string)\n },\n train_split='train',\n train_eval_split='validation',\n infer_eval_splits=[\n InferEvalSplit(name='train', suffix='eval_train'),\n InferEvalSplit(name='validation', suffix='validation'),\n InferEvalSplit(name='test', suffix='test', include_in_mixture=False)\n ])\n\n\nCERBERUS4_CONFIG = DatasetConfig(\n name='cerberus4',\n paths={\n 'train':\n 'gs://mt3/data/datasets/cerberus4/slakh_multi_cerberus_train_bass:drums:guitar:piano.tfrecord-?????-of-00286',\n 'train_subset':\n 'gs://mt3/data/datasets/cerberus4/slakh_multi_cerberus_train_bass:drums:guitar:piano.tfrecord-00000-of-00286',\n 'validation':\n 'gs://mt3/data/datasets/cerberus4/slakh_multi_cerberus_validation_bass:drums:guitar:piano.tfrecord-?????-of-00212',\n 'validation_subset':\n 'gs://mt3/data/datasets/cerberus4/slakh_multi_cerberus_validation_bass:drums:guitar:piano.tfrecord-0000?-of-00212',\n 'test':\n 'gs://mt3/data/datasets/cerberus4/slakh_multi_cerberus_test_bass:drums:guitar:piano.tfrecord-?????-of-00106'\n },\n features={\n 'audio_sample_rate': tf.io.FixedLenFeature([], dtype=tf.int64),\n 'inst_names': tf.io.FixedLenSequenceFeature(\n [], dtype=tf.string, allow_missing=True),\n 'midi_class': tf.io.FixedLenSequenceFeature(\n [], dtype=tf.int64, allow_missing=True),\n 'mix': tf.io.FixedLenSequenceFeature(\n [], dtype=tf.float32, allow_missing=True),\n 'note_sequences': tf.io.FixedLenSequenceFeature(\n [], dtype=tf.string, allow_missing=True),\n 'plugin_name': tf.io.FixedLenSequenceFeature(\n [], dtype=tf.int64, allow_missing=True),\n 'program_num': tf.io.FixedLenSequenceFeature(\n [], dtype=tf.int64, allow_missing=True),\n 'slakh_class': tf.io.FixedLenSequenceFeature(\n [], dtype=tf.int64, allow_missing=True),\n 'src_ids': tf.io.FixedLenSequenceFeature(\n [], dtype=tf.string, allow_missing=True),\n 'stems': tf.io.FixedLenSequenceFeature(\n [], dtype=tf.float32, allow_missing=True),\n 'stems_shape': tf.io.FixedLenFeature([2], dtype=tf.int64),\n 'target_type': tf.io.FixedLenFeature([], dtype=tf.string),\n 'track_id': tf.io.FixedLenFeature([], dtype=tf.string),\n },\n train_split='train',\n train_eval_split='validation_subset',\n infer_eval_splits=[\n InferEvalSplit(name='train', suffix='eval_train_full',\n include_in_mixture=False),\n InferEvalSplit(name='train_subset', suffix='eval_train'),\n InferEvalSplit(name='validation', suffix='validation_full',\n include_in_mixture=False),\n InferEvalSplit(name='validation_subset', suffix='validation'),\n InferEvalSplit(name='test', suffix='test', include_in_mixture=False)\n ],\n track_specs=[\n note_sequences.TrackSpec('bass', program=32),\n note_sequences.TrackSpec('drums', is_drum=True),\n note_sequences.TrackSpec('guitar', program=24),\n note_sequences.TrackSpec('piano', program=0)\n ])\n\n\nSLAKH_CONFIG = DatasetConfig(\n name='slakh',\n paths={\n 'train':\n 'gs://mt3/data/datasets/slakh/slakh_multi_full_subsets_10_train_all_inst.tfrecord-?????-of-02307',\n 'train_subset':\n 'gs://mt3/data/datasets/slakh/slakh_multi_full_subsets_10_train_all_inst.tfrecord-00000-of-02307',\n 'validation':\n 'gs://mt3/data/datasets/slakh/slakh_multi_full_validation_all_inst.tfrecord-?????-of-00168',\n 'validation_subset':\n 'gs://mt3/data/datasets/slakh/slakh_multi_full_validation_all_inst.tfrecord-0000?-of-00168',\n 'test':\n 'gs://mt3/data/datasets/slakh/slakh_multi_full_test_all_inst.tfrecord-?????-of-00109'\n },\n features={\n 'audio_sample_rate': tf.io.FixedLenFeature([], dtype=tf.int64),\n 'inst_names': tf.io.FixedLenSequenceFeature([], dtype=tf.string,\n allow_missing=True),\n 'midi_class': tf.io.FixedLenSequenceFeature([], dtype=tf.int64,\n allow_missing=True),\n 'mix': tf.io.FixedLenSequenceFeature([], dtype=tf.float32,\n allow_missing=True),\n 'note_sequences': tf.io.FixedLenSequenceFeature([], dtype=tf.string,\n allow_missing=True),\n 'plugin_name': tf.io.FixedLenSequenceFeature([], dtype=tf.int64,\n allow_missing=True),\n 'program_num': tf.io.FixedLenSequenceFeature([], dtype=tf.int64,\n allow_missing=True),\n 'slakh_class': tf.io.FixedLenSequenceFeature([], dtype=tf.int64,\n allow_missing=True),\n 'src_ids': tf.io.FixedLenSequenceFeature([], dtype=tf.string,\n allow_missing=True),\n 'stems': tf.io.FixedLenSequenceFeature([], dtype=tf.float32,\n allow_missing=True),\n 'stems_shape': tf.io.FixedLenFeature([2], dtype=tf.int64),\n 'target_type': tf.io.FixedLenFeature([], dtype=tf.string),\n 'track_id': tf.io.FixedLenFeature([], dtype=tf.string),\n },\n train_split='train',\n train_eval_split='validation_subset',\n infer_eval_splits=[\n InferEvalSplit(name='train', suffix='eval_train_full',\n include_in_mixture=False),\n InferEvalSplit(name='train_subset', suffix='eval_train'),\n InferEvalSplit(name='validation', suffix='validation_full',\n include_in_mixture=False),\n InferEvalSplit(name='validation_subset', suffix='validation'),\n InferEvalSplit(name='test', suffix='test', include_in_mixture=False)\n ])\n" ]
[ [ "tensorflow.io.FixedLenFeature", "tensorflow.io.FixedLenSequenceFeature" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Leonardodsch/house-rocket-insights
[ "dd8405b776e223ec5ff8392a027d4b0116fcd7ca" ]
[ "house_rocket_app.py" ]
[ "import pandas as pd\nimport numpy as np\nimport streamlit as st\nimport plotly.express as px\nimport ipywidgets as widgets\nfrom ipywidgets import fixed\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nsns.set_style('whitegrid')\n\nst.set_page_config(layout='wide')\n\[email protected](allow_output_mutation=True)\ndef get_data(path):\n data = pd.read_csv(path)\n\n return data\n\ndef barplot(a,b, aux):\n plot = sns.barplot(x=a, y=b, data=aux, edgecolor='k', palette='Blues')\n sns.despine()\n return plot\n\n# get data\npath = 'data/df_sugestions01.csv'\npath2 = 'data/df_sugestions02.csv'\npath3 = 'data/df_full.csv'\n\ndata = get_data(path)\ndf = get_data(path2)\ndf1 = get_data(path3)\n\nst.sidebar.write()\nf_zipcode = st.sidebar.multiselect('Select Zipcode', data['zipcode'].unique())\nf_condition = st.sidebar.multiselect('Select Condition', data['condition'].sort_values(ascending=True).unique())\nf_buy = st.sidebar.multiselect('Select buy option', data['buy'].unique())\nf_season = st.sidebar.multiselect('Select season', df['season'].unique())\n\nmin_price = int(df['price'].min())\nmax_price = int(df['price'].max())\nmedian_price = int(df['price'].median())\n\n\n\nst.title('House Rocket')\nst.write('A House Rocket é uma empresa focada na compra e venda de imóveis, buscando avaliar e encontrar bons negócios para constituir seu portfólio e oferecer também bons'\n ' negocios para seus clientes. Diante disso foi realizada uma análise onde diversos imóveis foram explorados e avaliados buscando o que poderia se tornar uma boa oportunidade para a empresa'\n ' e alguns insights interessantes foram descobertos, algo que se tornará de extremo valor caso seja bem utilizado.'\n 'Para detalhes mais técnicos e visualização do projeto completo acessar:' ' [GitHub](https://github.com/Leonardodsch/house-rocket-insights)')\n\nst.title('Business Questions')\nst.write('As tabelas são interativas e podem ser filtradas a partir das opções na barra lateral, permitindo assim que os imóveis'\n ' possam ser exibidos de acordo com a preferência.')\nst.header(' Quais são os imóveis que a House Rocket deveria comprar e por qual preço ?')\nst.write(' Na primeita tabela estão os imóveis agrupados por região (zipcode), com os preços médios de cada região. Estes são avaliados juntamente com o valor'\n ' da coluna condition de cada imóvel, para assim ser feita uma sugestão de compra ou não')\nst.header(' Uma vez a casa comprada, qual o melhor momento para vendê-las e por qual preço ?')\nst.write('Na segunda tabela é possivel filtrar os imóveis pela região mas também pela sazonalidade, o que permite ver as melhores opções de compra em cada estação do ano'\n ' e o valor da venda baseado nas premissas de assumidas no começo do projeto')\n\n\n\nif (f_zipcode != []) & (f_condition == []) & (f_buy == []) & (f_season == []):\n st.write(data.loc[data['zipcode'].isin(f_zipcode)])\n st.write(df.loc[(df['zipcode'].isin(f_zipcode))])\n\nelif (f_condition != []) & (f_zipcode != []) & (f_buy != []) & (f_season != []):\n st.write(data.loc[(data['condition'].isin(f_condition)) & (data['zipcode'].isin(f_zipcode)) & (data['buy'].isin(f_buy))])\n st.write(df.loc[(df['season'].isin(f_season)) & (df['zipcode'].isin(f_zipcode))])\n\nelif (f_condition != []) & (f_zipcode == []) & (f_buy == []) & (f_season == []):\n st.write(data.loc[data['condition'].isin(f_condition)])\n st.dataframe(df)\n\nelif (f_buy != []) & (f_zipcode == []) & (f_condition == []) & (f_season == []):\n st.write(data.loc[data['buy'].isin(f_buy)])\n st.dataframe(df)\n\nelif (f_condition != []) & (f_zipcode != []) & (f_buy == []) & (f_season != []):\n st.write(data.loc[(data['condition'].isin(f_condition)) & (data['zipcode'].isin(f_zipcode))])\n st.write(df.loc[(df['season'].isin(f_season)) & (df['zipcode'].isin(f_zipcode))])\n\nelif (f_condition == []) & (f_zipcode != []) & (f_buy != []) & (f_season == []):\n st.write(data.loc[(data['zipcode'].isin(f_zipcode)) & (data['buy'].isin(f_buy))])\n st.write(df.loc[(df['zipcode'].isin(f_zipcode))])\n\nelif (f_season != []) & (f_zipcode == []) & (f_buy == []) & (f_condition == []):\n st.dataframe(data, height=400, width=700)\n st.write(df.loc[(df['season'].isin(f_season))])\n\nelif (f_season != []) & (f_zipcode == []) & (f_buy != []) & (f_condition == []):\n st.write(data.loc[data['buy'].isin(f_buy)])\n st.write(df.loc[df['season'].isin(f_season)])\n\nelif (f_season != []) & (f_zipcode == []) & (f_buy == []) & (f_condition != []):\n st.write(data.loc[data['condition'].isin(f_condition)])\n st.write(df.loc[df['season'].isin(f_season)])\n\nelif (f_season != []) & (f_zipcode == []) & (f_buy != []) & (f_condition != []):\n st.write(data.loc[data['condition'].isin(f_condition) & (data['buy'].isin(f_buy))])\n st.write(df.loc[df['season'].isin(f_season)])\n\nelif (f_zipcode != []) & (f_condition == []) & (f_buy == []) & (f_season != []):\n st.write(data.loc[data['zipcode'].isin(f_zipcode)])\n st.write(df.loc[(df['season'].isin(f_season)) & (df['zipcode'].isin(f_zipcode))])\n\nelif (f_condition == []) & (f_zipcode != []) & (f_buy != []) & (f_season != []):\n st.write(data.loc[(data['zipcode'].isin(f_zipcode)) & (data['buy'].isin(f_buy))])\n st.write(df.loc[(df['season'].isin(f_season)) & (df['zipcode'].isin(f_zipcode))])\n\nelif (f_condition != []) & (f_zipcode != []) & (f_buy == []) & (f_season == []):\n st.write(data.loc[(data['condition'].isin(f_condition)) & (data['zipcode'].isin(f_zipcode))])\n st.write(df.loc[(df['zipcode'].isin(f_zipcode))])\n\nelif (f_condition != []) & (f_zipcode != []) & (f_buy != []) & (f_season == []):\n st.write(data.loc[(data['condition'].isin(f_condition)) & (data['zipcode'].isin(f_zipcode)) & (data['buy'].isin(f_buy))])\n st.write(df.loc[(df['zipcode'].isin(f_zipcode))])\n\nelse:\n data = data.copy()\n df = df.copy()\n st.dataframe(data, height=400, width=700)\n st.dataframe(df)\n\nst.header('Mapa com as indicações de compra')\nis_check = st.checkbox('Show Map')\n\n\nif is_check:\n\n selected_price_range = st.slider('Select the price range', min_price, max_price, median_price)\n buy_select = st.multiselect('Buy option', df1['buy'].unique())\n\n if (buy_select != []):\n # select rows\n houses = df1[(df1['price'] < selected_price_range) & (df1['buy'].isin(buy_select))][['id','zipcode','price','median_price','condition', 'lat', 'long']]\n # draw map\n fig = px.scatter_mapbox(\n houses,\n lat='lat',\n lon='long',\n color=\"condition\",\n size=\"price\",\n color_continuous_scale=px.colors.cyclical.IceFire,\n size_max=15,\n zoom=10 )\n\n fig.update_layout(mapbox_style=\"open-street-map\")\n fig.update_layout(height=600, margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0})\n st.plotly_chart(fig)\n\n else:\n # select rows\n houses = df1[['id','zipcode','price','median_price','condition', 'lat', 'long']].copy()\n # draw map\n fig = px.scatter_mapbox(\n houses,\n lat='lat',\n lon='long',\n color=\"condition\",\n size=\"price\",\n color_continuous_scale=px.colors.cyclical.IceFire,\n size_max=15,\n zoom=10 )\n\n fig.update_layout(mapbox_style=\"open-street-map\")\n fig.update_layout(height=600, margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0})\n st.plotly_chart(fig)\n\nst.title('Business Hypothesis')\n\n# H1\nst.header('H1: Imóveis que possuem vista para água, são 30% mais caros, na média')\nst.text('Falsa! Imóveis com vista para a agua são 200% mais caros na mádia')\naux = df1[['price','waterfront']].groupby('waterfront').mean().reset_index()\nfig = plt.figure(figsize=(9,3))\nbarplot('waterfront','price',aux)\nst.pyplot(fig)\n\n#H2\nst.header('H2: Imóveis com data de construção menor que 1955, são 50% mais baratos, na média')\nst.text('Falsa! Imóveis com data de construção menot do que 1955 são aproximadamente 1,6% mais baratos')\naux2 = df1[['price','yr_built']].copy()\naux2['yr_built'] = aux2['yr_built'].apply(lambda x: '<= 1955' if x <= 1955 else '> 1955')\naux = aux2[['price','yr_built']].groupby('yr_built').mean().reset_index()\nfig2 = plt.figure(figsize=(9,3))\nbarplot('yr_built','price',aux)\nst.pyplot(fig2)\n\n# Evolution over the year\nst.header('Evolution over the years')\naux = df1[['price','yr_built']].loc[df1['yr_built'] <= 1955].groupby('yr_built').mean().reset_index()\naux2 = df1[['price','yr_built']].loc[df1['yr_built'] > 1955].groupby('yr_built').mean().reset_index()\n\nfig_ = plt.figure(figsize=(15,7))\nplt.subplot(2,1,1)\nbarplot('yr_built','price', aux)\nplt.xticks(rotation=60);\nplt.title('Yr_built <= 1955')\n\nplt.subplot(2,1,2)\nbarplot('yr_built','price',aux2)\nplt.xticks(rotation=60);\nplt.title('Yr_built > 1955')\nplt.tight_layout()\nst.pyplot(fig_)\n\n#H3\nst.header('H3: Imóveis sem porão possuem area total (sqrt_lot), são 50% maiores do que com porão')\nst.text('Falsa! Imóveis sem porão possuem uma area total 23% maior')\naux = df1[['sqft_basement','sqft_lot']].copy()\naux['sqft_basement'] = aux['sqft_basement'].apply(lambda x: 'yes' if x != 0 else 'no')\naux1 = aux[['sqft_basement','sqft_lot']].groupby('sqft_basement').mean().reset_index()\naux1.sort_values(by='sqft_lot', ascending=True, inplace=True)\nfig3 = plt.figure(figsize=(9,3))\nbarplot('sqft_basement','sqft_lot',aux1)\nst.pyplot(fig3)\n\n#4\nst.header('H4: O crescimento do preço dos imóveis YoY ( Year over Year ) é de 10%')\nst.text('Falsa O crescimento do preço dos imoveis YoY é de 2%')\naux = df1[['price','year']].loc[df1['month'] == 5].copy()\naux1 = aux[['price','year']].groupby('year').mean().reset_index()\nfig4 = plt.figure(figsize=(9,3))\nbarplot('year','price',aux1)\nst.pyplot(fig4)\n\n#5\nst.header('H5: Imóveis com 3 banheiros tem um crescimento MoM ( Month over Month ) de 15%')\nst.text('Falsa! Imóveis com 3 banheiros não possuem um crescimento MoM de 15%')\naux = df1[['price','month']].loc[df1['bathrooms'] == 3].groupby(['month']).mean().reset_index()\naux['growth'] = aux['price'].pct_change()\nfig5 = plt.figure(figsize=(9,3))\nplt.subplot(2,1,1)\nplt.plot('month','price', data=aux)\nplt.ylabel('Price')\nplt.subplot(2,1,2)\nbarplot('month','growth',aux)\nst.pyplot(fig5)\n\n#6\nst.header('H6: Imóveis com 3 ou mais banheiros são 30% mais caros, na média')\nst.text('Falsa! Impoveis com 3 ou mais banheiros são 100% mais caros na média')\naux = df1[['bathrooms','price']].copy()\naux['bathrooms'] = aux['bathrooms'].apply(lambda x: '>= 3' if x >=3 else '< 3')\naux1 = aux[['price','bathrooms']].groupby('bathrooms').mean().reset_index()\nfig6 = plt.figure(figsize=(9,3))\nbarplot('bathrooms','price',aux1)\nst.pyplot(fig6)\n\n#7\nst.header('H7: Imóveis com condition igual ou maior do que 4 são 40% mais caros, na média')\nst.text('Falsa! Imóveis com condition igual ou maior do que 4 são 0,5% mais caros, na média')\naux = df1[['price','condition']].copy()\naux['condition'] = aux['condition'].apply(lambda x: '< 4' if x < 4 else '>= 4')\naux1 = aux[['price','condition']].groupby('condition').mean().reset_index()\nfig7 = plt.figure(figsize=(9,3))\nbarplot('condition','price',aux1)\nst.pyplot(fig7)\n\n#8\nst.header('H8: Imóveis vendidos no inverno são 30% mais baratos na média do que imóveis vendidos no verão')\nst.text('Falsa! Imóveis vendidos no inverno são 4% mais baratos na média do que imóveis vendidos no verão')\naux = df1[['price','season']].loc[(df1['season'] == 'winter') | (df1['season'] == 'summer') ].copy()\naux1 = aux[['price','season']].groupby('season').mean().reset_index()\naux1.sort_values(by='price', ascending=True, inplace=True)\nfig8 = plt.figure(figsize=(9,3))\nbarplot('season','price',aux1)\nst.pyplot(fig8)\n\n#9\nst.header('H9: Imóveis com mais de 400m2 (m2_living) são 50% mais caros na media')\nst.text('Falsa! Imóveis com mais de 400m2 são 230% mais caros na média')\naux = df1[['price','m2_living']].copy()\naux['m2_living'] = aux['m2_living'].apply(lambda x: '< 400' if x < 400 else '> 400')\naux1= aux[['price','m2_living']].groupby('m2_living').mean().reset_index()\nfig9 = plt.figure(figsize=(9,3))\nbarplot('m2_living','price',aux1)\nst.pyplot(fig9)\n\n#10\nst.header('H10: Imóveis com menos de 100m2 tem um crescimento Mom ( Month over Month ) de 20%')\nst.text('Falsa! Imóveis com menos de 100m2 não possuem um crescimento MoM de 20%')\naux = df1[['price','month']].loc[df1['m2_living'] < 100 ].groupby('month').mean().reset_index()\naux['growth'] = aux['price'].pct_change()\nfig10 = plt.figure(figsize=(9,3))\nplt.subplot(2,1,1)\nplt.plot('month','price', data=aux)\nplt.ylabel('Price')\nplt.subplot(2,1,2)\nbarplot('month','growth',aux)\nst.pyplot(fig10)\n\n#11\nst.header('H11: Imóveis com 4 ou mais quartos são 50% mais caros, na média')\nst.text('Verdadeira! Imóveis com 4 ou mais quartos são 50% mais caros, na média')\naux = df1[['bedrooms','price']].copy()\naux['bedrooms'] = aux['bedrooms'].apply(lambda x: '< 4' if x < 4 else '>= 4')\naux1= aux[['price','bedrooms']].groupby('bedrooms').mean().reset_index()\nfig11 = plt.figure(figsize=(9,3))\nbarplot('bedrooms','price',aux1)\nst.pyplot(fig11)\n\n" ]
[ [ "matplotlib.pyplot.tight_layout", "pandas.read_csv", "matplotlib.pyplot.title", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.subplot", "matplotlib.pyplot.xticks", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
OSSDC/OSSDC-VisionBasedACC
[ "a9004c888e91b8becaebc22524f698ebb3c9746e" ]
[ "object_detection/test_mobilenet.py" ]
[ "import numpy as np\nimport os\nimport six.moves.urllib as urllib\nimport sys\nimport tarfile\nimport tensorflow as tf\nimport zipfile\n\nfrom collections import defaultdict\nfrom io import StringIO\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\n\nimport cv2\n\nfrom webcamvideostream import *\n\nvideoUrl = 1\nvideoUrl = \"/sharefolder/sdc/sdc-data/ossdc-simulator-TheCrew-PS4-30fps.mp4\"\n\nwebcam = False\n#webcam = True\n\nsct = None\n\nret = True\n\nif webcam:\n cap = WebcamVideoStream(videoUrl,(1280,720),30)\n cap.start()\nelse:\n cap = cv2.VideoCapture(videoUrl)\n\n# This is needed since the notebook is stored in the object_detection folder.\nsys.path.append(\"..\")\n\n\n# ## Object detection imports\n# Here are the imports from the object detection module.\n\n# In[3]:\n\nfrom utils import label_map_util\n\nfrom utils import visualization_utils as vis_util\n\n\n# # Model preparation \n\n# ## Variables\n# \n# Any model exported using the `export_inference_graph.py` tool can be loaded here simply by changing `PATH_TO_CKPT` to point to a new .pb file. \n# \n# By default we use an \"SSD with Mobilenet\" model here. See the [detection model zoo](https://github.com/tensorflow/models/blob/master/object_detection/g3doc/detection_model_zoo.md) for a list of other models that can be run out-of-the-box with varying speeds and accuracies.\n\n# In[4]:\n\n# What model to download.\nMODEL_NAME = 'ssd_mobilenet_v1_coco_11_06_2017'\nMODEL_FILE = MODEL_NAME + '.tar.gz'\nDOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'\n\n# Path to frozen detection graph. This is the actual model that is used for the object detection.\nPATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'\n\n# List of the strings that is used to add correct label for each box.\nPATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')\n\nNUM_CLASSES = 90\n\n\n# ## Download Model\n\n# In[5]:\n'''\nopener = urllib.request.URLopener()\nopener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)\ntar_file = tarfile.open(MODEL_FILE)\nfor file in tar_file.getmembers():\n file_name = os.path.basename(file.name)\n if 'frozen_inference_graph.pb' in file_name:\n tar_file.extract(file, os.getcwd())\n'''\n\n# ## Load a (frozen) Tensorflow model into memory.\n\n# In[6]:\n\ndetection_graph = tf.Graph()\nwith detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n\n\n# ## Loading label map\n# Label maps map indices to category names, so that when our convolution network predicts `5`, we know that this corresponds to `airplane`. Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine\n\n# In[7]:\n\nlabel_map = label_map_util.load_labelmap(PATH_TO_LABELS)\ncategories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)\ncategory_index = label_map_util.create_category_index(categories)\n\n\n# ## Helper code\n\n# In[8]:\n\ndef load_image_into_numpy_array(image):\n (im_width, im_height) = image.size\n return np.array(image.getdata()).reshape(\n (im_height, im_width, 3)).astype(np.uint8)\n\n\n# # Detection\n\n# In[9]:\n\n# For the sake of simplicity we will use only 2 images:\n# image1.jpg\n# image2.jpg\n# If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.\nPATH_TO_TEST_IMAGES_DIR = 'test_images'\nTEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3) ]\n\n# Size, in inches, of the output images.\nIMAGE_SIZE = (12, 8)\n\n# In[10]:\n\nfrom datetime import datetime\n\nprecision = 10\ndef getCurrentClock():\n #return time.clock()\n return datetime.now()\n\nframeCnt=0\nprevFrameCnt=0\nprevTime=getCurrentClock()\n\nwith detection_graph.as_default():\n with tf.Session(graph=detection_graph) as sess:\n while True:\n if sct is not None or webcam or cap.grab():\n if sct is not None:\n frame = numpy.asarray(sct.grab(mon))\n else:\n if webcam:\n frame = cap.read()\n else:\n flag, frame = cap.retrieve() \n if not flag:\n continue \n image_np = frame\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_np, axis=0)\n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n # Each box represents a part of the image where a particular object was detected.\n boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\n # Each score represent how level of confidence for each of the objects.\n # Score is shown on the result image, together with the class label.\n scores = detection_graph.get_tensor_by_name('detection_scores:0')\n classes = detection_graph.get_tensor_by_name('detection_classes:0')\n num_detections = detection_graph.get_tensor_by_name('num_detections:0')\n # Actual detection.\n (boxes, scores, classes, num_detections) = sess.run(\n [boxes, scores, classes, num_detections],\n feed_dict={image_tensor: image_np_expanded})\n # Visualization of the results of a detection.\n vis_util.visualize_boxes_and_labels_on_image_array(\n image_np,\n np.squeeze(boxes),\n np.squeeze(classes).astype(np.int32),\n np.squeeze(scores),\n category_index,\n use_normalized_coordinates=True,\n line_thickness=8)\n \n frameCnt=frameCnt+1\n nowMicro = getCurrentClock()\n delta = (nowMicro-prevTime).total_seconds()\n\n if delta>=1.0:\n fpsValue = ((frameCnt-prevFrameCnt)/delta) \n print(\"FPS = %3.2f, Frame = %6d\" % (fpsValue, frameCnt))\n prevFrameCnt=frameCnt\n\n cv2.imshow('object detection', cv2.resize(image_np, (800,600)))\n if cv2.waitKey(25) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n break" ]
[ [ "tensorflow.Graph", "tensorflow.import_graph_def", "numpy.expand_dims", "tensorflow.gfile.GFile", "numpy.squeeze", "tensorflow.Session", "tensorflow.GraphDef" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
UBC-MDS/eazieda
[ "214f3907e71ddbaa1b64c7a201cb0f07661263ac" ]
[ "tests/test_missing_impute.py" ]
[ "from eazieda.missing_impute import missing_impute\nimport pandas as pd\nimport numpy as np\nfrom pytest import raises, fixture\n\n\n@fixture\ndef df_miss():\n df = pd.DataFrame(\n [[1.0, \"x\"], [np.nan, \"y\"], [2.0, np.nan], [3.0, \"y\"]],\n columns=[\"a\", \"b\"],\n )\n return df\n\n\n@fixture\ndef df_miss_2():\n df = pd.DataFrame(\n [[1.0, \"x\"], [np.nan, \"y\"], [2.0, np.nan], [3.0, \"y\"], [4.0, \"y\"]],\n columns=[\"a\", \"b\"],\n )\n return df\n\n\ndef test_missing_impute(df_miss, df_miss_2):\n\n # Test with default arguments\n expected_output_default = pd.DataFrame(\n data={\"a\": [1.0, 2.0, 2.0, 3.0], \"b\": [\"x\", \"y\", \"y\", \"y\"]}\n ).reset_index(drop=True)\n\n missing_output_default = missing_impute(df_miss)\n\n assert pd.DataFrame.equals(missing_output_default, expected_output_default)\n\n # Test with two drop arguments selected at the same time\n expected_output_two_drop = pd.DataFrame(\n data={\"a\": [1.0, 3.0], \"b\": [\"x\", \"y\"]}\n ).reset_index(drop=True)\n\n missing_output_two_drop = missing_impute(\n df_miss, method_num=\"drop\", method_non_num=\"drop\"\n )\n\n assert pd.DataFrame.equals(\n missing_output_two_drop, expected_output_two_drop\n )\n\n # Test with method_num=\"mean\", method_non_num=\"drop\"\n expected_output_one_drop = pd.DataFrame(\n data={\"a\": [1.0, 2.0, 3.0], \"b\": [\"x\", \"y\", \"y\"]}\n ).reset_index(drop=True)\n\n missing_output_one_drop = missing_impute(df_miss, method_non_num=\"drop\")\n\n assert pd.DataFrame.equals(\n expected_output_one_drop, missing_output_one_drop\n )\n\n # Test with method_num=\"median\", method_non_num=\"most_frequent\"\n expected_output_median = pd.DataFrame(\n data={\"a\": [1.0, 2.0, 2.0, 3.0], \"b\": [\"x\", \"y\", \"y\", \"y\"]}\n ).reset_index(drop=True)\n missing_output_median = missing_impute(df_miss, method_num=\"median\")\n\n assert pd.DataFrame.equals(missing_output_median, expected_output_median)\n\n # Test with method_num=\"median\", method_non_num=\"drop\"\n expected_output_median_drop = pd.DataFrame(\n data={\"a\": [1.0, 2.0, 3.0], \"b\": [\"x\", \"y\", \"y\"]}\n ).reset_index(drop=True)\n missing_output_median_drop = missing_impute(\n df_miss, method_num=\"median\", method_non_num=\"drop\"\n )\n\n assert pd.DataFrame.equals(\n missing_output_median_drop, expected_output_median_drop\n )\n\n # Test with method_num=\"drop\", method_non_num=\"most_frequent\"\n expected_output_drop_freq = pd.DataFrame(\n [[1.0, \"x\"], [2.0, \"y\"], [3.0, \"y\"], [4.0, \"y\"]], columns=[\"a\", \"b\"],\n ).reset_index(drop=True)\n missing_output_drop_freq = missing_impute(\n df_miss_2, method_num=\"drop\", method_non_num=\"most_frequent\"\n )\n\n assert pd.DataFrame.equals(\n missing_output_drop_freq, expected_output_drop_freq\n )\n\n # Test whether a not dataframe input raises TypeError\n with raises(TypeError):\n missing_impute(5)\n\n # Test whether invaild input of method_num raises ValueError\n with raises(ValueError):\n missing_impute(df_miss, method_num=\"mea\")\n\n # Test whether invaild input of method_non_num raises ValueError\n with raises(ValueError):\n missing_impute(df_miss, method_num=\"mean\", method_non_num=\"most_freq\")\n" ]
[ [ "pandas.DataFrame.equals", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
hui2000ji/scETM
[ "0a34c345d70b262ebc38e033bae683fa4929ed3e" ]
[ "src/scETM/models/BatchClassifier.py" ]
[ "from typing import Sequence, Mapping\nfrom numpy import mod\nimport torch\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\n\nfrom .model_utils import get_fully_connected_layers\nfrom scETM.logging_utils import log_arguments\n\nclass BatchClassifier(nn.Module):\n \"\"\"Docstring (TODO)\n \"\"\"\n\n @log_arguments\n def __init__(self,\n n_input: int,\n n_output: int,\n hidden_sizes: Sequence[int],\n bn: bool = False,\n bn_track_running_stats: bool = False,\n dropout_prob = 0.2,\n adversarial_loss = 'confuse',\n device=torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n ) -> None:\n \"\"\"Docstring (TODO)\n \"\"\"\n\n super().__init__()\n\n self.batch_clf = get_fully_connected_layers(\n n_trainable_input=n_input,\n n_trainable_output=n_output,\n hidden_sizes=hidden_sizes,\n bn=bn,\n bn_track_running_stats=bn_track_running_stats,\n dropout_prob=dropout_prob,\n ).to(device)\n self.n_output = n_output\n assert adversarial_loss in ('confuse', 'reverse')\n self.adversarial_loss = adversarial_loss\n\n def forward(self, X: torch.Tensor, y: torch.Tensor) -> Mapping[str, torch.Tensor]:\n \"\"\"Docstring (TODO)\n \"\"\"\n\n logit = self.batch_clf(X)\n if not self.training:\n return dict(logit=logit)\n\n clf_loss = F.cross_entropy(logit, y)\n if self.adversarial_loss == 'confuse':\n model_loss = (-F.log_softmax(logit, dim=-1) * torch.zeros_like(logit).fill_(1/self.n_output)).sum(-1).mean()\n else:\n model_loss = -clf_loss\n return clf_loss, dict(logit=logit, model_loss=model_loss), dict(clf_loss=clf_loss.detach().item())\n\n def train_step(self,\n optimizer: optim.Optimizer,\n X: torch.Tensor,\n y: torch.Tensor\n ) -> Mapping[str, torch.Tensor]:\n \"\"\"Docstring (TODO)\n \"\"\"\n\n self.train()\n optimizer.zero_grad()\n loss, fwd_dict, new_records = self(X, y)\n loss.backward()\n optimizer.step()\n new_records['clf_acc'] = (fwd_dict['logit'].argmax(1) == y).to(torch.float).mean().detach().item()\n return new_records" ]
[ [ "torch.nn.functional.log_softmax", "torch.nn.functional.cross_entropy", "torch.zeros_like", "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
traindb-project/traindb-model
[ "9ffdb8c0195051630692dbe6dfd8b9fe816a619f" ]
[ "models/TVAE.py" ]
[ "\"\"\"\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 logging\nimport rdt\nimport sdv\nfrom TrainDBBaseModel import TrainDBSynopsisModel\nimport pandas as pd\n\nimport torch\n\nLOGGER = logging.getLogger(__name__)\n\nclass TVAE(TrainDBSynopsisModel):\n\n def train(self, real_data, table_metadata):\n self.columns, _ = self.get_columns(real_data, table_metadata)\n\n LOGGER.info(\"Training %s\", self.__class__.__name__)\n model_kwargs = {}\n self.model = sdv.tabular.TVAE(table_metadata=table_metadata, **model_kwargs)\n self.model.fit(real_data)\n\n def save(self, output_path):\n self.model.save(output_path + '/model.pkl')\n torch.save({\n 'columns': self.columns\n }, output_path + '/model_info.pth')\n\n def load(self, input_path):\n self.model = sdv.tabular.TVAE.load(input_path + '/model.pkl')\n saved_model_info = torch.load(input_path + '/model_info.pth')\n self.columns = saved_model_info['columns']\n\n def synopsis(self, row_count):\n LOGGER.info(\"Synopsis Generating %s\", self.__class__.__name__)\n synthetic_data = self.model.sample(row_count)\n synthetic_data = pd.DataFrame(synthetic_data, columns=self.columns)\n\n return synthetic_data\n" ]
[ [ "torch.load", "pandas.DataFrame", "torch.save" ] ]
[ { "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": [] } ]
dan-zheng/tensorflow
[ "5e04065935920b0a07175283408297e73d2191fb" ]
[ "tensorflow/python/keras/engine/base_layer_test.py" ]
[ "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for TensorFlow 2.0 layer behavior.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport itertools as it\nimport os\nimport sys\nimport traceback\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python import keras\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_spec\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.keras import backend\nfrom tensorflow.python.keras import keras_parameterized\nfrom tensorflow.python.keras import testing_utils\nfrom tensorflow.python.keras.engine import base_layer\nfrom tensorflow.python.keras.mixed_precision.experimental import policy\nfrom tensorflow.python.keras.optimizer_v2 import rmsprop\nfrom tensorflow.python.keras.utils import tf_utils\nfrom tensorflow.python.layers import core as legacy_core\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops import summary_ops_v2\nfrom tensorflow.python.ops import tensor_array_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.platform import tf_logging\nfrom tensorflow.python.summary import summary_iterator\nfrom tensorflow.python.util import nest\n\n\nclass DynamicLayer(base_layer.Layer):\n\n def __init__(self, dynamic=False, **kwargs):\n super(DynamicLayer, self).__init__(dynamic=dynamic, **kwargs)\n\n def call(self, inputs):\n samples = tensor_array_ops.TensorArray(\n dtype=dtypes.float32, size=array_ops.shape(inputs)[0])\n for idx, sample in enumerate(inputs):\n samples = samples.write(idx, math_ops.square(sample))\n return samples.stack()\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n\nclass InvalidLayer(base_layer.Layer):\n\n def call(self, inputs):\n raise ValueError('You did something wrong!')\n\n\nclass BaseLayerTest(keras_parameterized.TestCase):\n\n @keras_parameterized.run_with_all_model_types\n def test_dynamic_layer(self):\n model = testing_utils.get_model_from_layers([DynamicLayer(dynamic=True)],\n input_shape=(3,))\n self.assertEqual(model.dynamic, True)\n model.compile(rmsprop.RMSprop(0.001), loss='mse')\n self.assertEqual(model.run_eagerly, True)\n model.train_on_batch(np.random.random((2, 3)), np.random.random((2, 3)))\n\n @keras_parameterized.run_with_all_model_types\n def test_dynamic_layer_error(self):\n with self.assertRaisesRegexp(TypeError,\n 'attempting to use Python control flow'):\n model = testing_utils.get_model_from_layers([DynamicLayer()],\n input_shape=(3,))\n model.compile(rmsprop.RMSprop(0.001), loss='mse')\n model.train_on_batch(np.random.random((2, 3)), np.random.random((2, 3)))\n\n @keras_parameterized.run_with_all_model_types\n def test_dynamic_layer_error_running_in_graph_mode(self):\n with context.graph_mode():\n model = testing_utils.get_model_from_layers([DynamicLayer(dynamic=True)],\n input_shape=(3,))\n self.assertEqual(model.dynamic, True)\n # But then you cannot run the model since you're in a graph scope.\n with self.assertRaisesRegexp(\n ValueError, 'You must enable eager execution'):\n model.compile(rmsprop.RMSprop(0.001), loss='mse')\n\n def test_manual_compute_output_shape(self):\n class BuildCounter(keras.layers.Layer):\n\n def __init__(self, *args, **kwargs): # pylint: disable=redefined-outer-name\n super(BuildCounter, self).__init__(*args, **kwargs)\n self.build_counter = 0\n\n def build(self, input_shape):\n self.build_counter += 1\n\n def call(self, inputs):\n return inputs\n\n with context.eager_mode():\n layer = BuildCounter(dtype=dtypes.float64)\n output_shape = layer.compute_output_shape((None, 10))\n self.assertEqual(layer.build_counter, 1)\n self.assertEqual(output_shape.as_list(), [None, 10])\n output_signature = layer.compute_output_signature(\n tensor_spec.TensorSpec(dtype=dtypes.float64, shape=[None, 10]))\n self.assertEqual(layer.build_counter, 1)\n self.assertEqual(output_signature.dtype, dtypes.float64)\n self.assertEqual(output_signature.shape.as_list(), [None, 10])\n layer(np.ones((5, 10)))\n self.assertEqual(layer.build_counter, 1)\n\n def test_dynamic_layer_with_deferred_sequential_model(self):\n model = keras.Sequential(\n [DynamicLayer(dynamic=True),\n keras.layers.Dense(3)])\n self.assertEqual(model.dynamic, True)\n model.compile(rmsprop.RMSprop(0.001), loss='mse')\n self.assertEqual(model.run_eagerly, True)\n model.train_on_batch(np.random.random((2, 3)), np.random.random((2, 3)))\n\n def test_nested_dynamic_layers_in_eager_mode(self):\n inputs = keras.Input((3,))\n outputs = DynamicLayer(dynamic=True)(inputs)\n inner_model = keras.Model(inputs, outputs)\n self.assertEqual(inner_model.dynamic, True)\n\n inputs = keras.Input((3,))\n x = DynamicLayer(dynamic=True)(inputs)\n outputs = inner_model(x)\n\n model = keras.Model(inputs, outputs)\n self.assertEqual(model.dynamic, True)\n model.compile(rmsprop.RMSprop(0.001), loss='mse')\n self.assertEqual(model.run_eagerly, True)\n model.train_on_batch(np.random.random((2, 3)), np.random.random((2, 3)))\n\n def test_dynamic_subclassed_model_no_shape_inference(self):\n\n class MyModel(keras.Model):\n\n def __init__(self):\n super(MyModel, self).__init__(dynamic=True)\n self.layer1 = keras.layers.Dense(3)\n self.layer2 = keras.layers.Dense(3)\n\n def call(self, inputs):\n if math_ops.reduce_sum(inputs) > 0:\n return self.layer1(inputs)\n else:\n return self.layer2(inputs)\n\n model = MyModel()\n self.assertEqual(model.dynamic, True)\n model.compile(rmsprop.RMSprop(0.001), loss='mse')\n self.assertEqual(model.run_eagerly, True)\n model.train_on_batch(np.random.random((2, 3)), np.random.random((2, 3)))\n self.assertEqual(model.outputs, [None])\n\n def test_dynamic_subclassed_model_with_shape_inference(self):\n\n class MyModel(keras.Model):\n\n def __init__(self):\n super(MyModel, self).__init__(dynamic=True)\n self.layer1 = keras.layers.Dense(3)\n self.layer2 = keras.layers.Dense(3)\n\n def call(self, inputs):\n if math_ops.reduce_sum(inputs) > 0:\n return self.layer1(inputs)\n else:\n return self.layer2(inputs)\n\n def compute_output_shape(self, input_shape):\n return tensor_shape.TensorShape(\n tuple(input_shape[:-1].as_list()) + (3,))\n\n model = MyModel()\n self.assertEqual(model.dynamic, True)\n model.compile(rmsprop.RMSprop(0.001), loss='mse')\n model.train_on_batch(np.random.random((2, 3)), np.random.random((2, 3)))\n self.assertEqual(model.outputs[0].shape.as_list(), [None, 3])\n\n @keras_parameterized.run_all_keras_modes\n def test_add_loss_correctness(self):\n\n class MyLayer(keras.layers.Layer):\n\n def call(self, inputs, training=None):\n self.add_loss(math_ops.reduce_sum(inputs))\n return inputs\n\n inputs = keras.Input((3,))\n layer = MyLayer()\n outputs = layer(inputs)\n model = keras.Model(inputs, outputs)\n self.assertEqual(len(model.losses), 1)\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n loss = model.train_on_batch(np.ones((2, 3)), np.ones((2, 3)))\n self.assertEqual(loss, 2 * 3)\n\n @test_util.run_in_graph_and_eager_modes\n def test_invalid_forward_pass(self):\n inputs = keras.Input((3,))\n with self.assertRaisesRegexp(ValueError, 'You did something wrong!'):\n _ = InvalidLayer()(inputs)\n\n def test_no_legacy_model(self):\n inputs = keras.Input((1,))\n legacy_dense_0 = legacy_core.Dense(1, name='legacy_dense_0')\n legacy_dense_1 = legacy_core.Dense(1, name='legacy_dense_1')\n\n layer = legacy_dense_0(inputs)\n layer = keras.layers.Dense(1)(layer)\n layer = legacy_dense_1(layer)\n\n expected_regex = (r'The following are legacy tf\\.layers\\.Layers:\\n '\n '{}\\n {}'.format(legacy_dense_0, legacy_dense_1))\n\n with self.assertRaisesRegexp(TypeError, expected_regex):\n _ = keras.models.Model(inputs=[inputs], outputs=[layer])\n\n model = keras.models.Model(inputs=[inputs], outputs=[inputs])\n with self.assertRaisesRegexp(TypeError, expected_regex):\n model._insert_layers([legacy_dense_0, legacy_dense_1])\n\n def test_no_legacy_sequential(self):\n layers = [\n keras.layers.Dense(1),\n legacy_core.Dense(1, name='legacy_dense_0')\n ]\n\n expected_regex = r'legacy tf\\.layers\\.Layers:\\n {}'.format(layers[1])\n with self.assertRaisesRegexp(TypeError, expected_regex):\n _ = keras.models.Sequential(layers)\n\n with self.assertRaisesRegexp(TypeError, expected_regex):\n _ = keras.models.Sequential([keras.layers.Input(shape=(4,))] + layers)\n\n model = keras.models.Sequential()\n with self.assertRaisesRegexp(TypeError, expected_regex):\n for l in layers:\n model.add(l)\n\n @keras_parameterized.run_with_all_model_types\n @test_util.run_in_graph_and_eager_modes\n def test_build_with_numpy_data(self):\n model_layers = [\n keras.layers.Dense(3, activation='relu', kernel_initializer='ones'),\n keras.layers.Dense(1, activation='sigmoid', kernel_initializer='ones')\n ]\n model = testing_utils.get_model_from_layers(model_layers, input_shape=(4,))\n model(np.zeros((2, 4), dtype='float32'))\n self.assertTrue(model.built)\n\n @test_util.run_in_graph_and_eager_modes\n def test_default_add_weight(self):\n\n class TestLayer(keras.layers.Layer):\n\n def __init__(self):\n super(TestLayer, self).__init__()\n self.default_weight = self.add_weight()\n self.weight_without_name = self.add_weight(shape=(3, 4))\n self.regularized_weight_without_name = self.add_weight(\n shape=(3, 4), regularizer='l2')\n\n layer = TestLayer()\n self.assertEqual(layer.default_weight.shape.as_list(), [])\n self.assertEqual(layer.weight_without_name.shape.as_list(), [3, 4])\n self.assertEqual(layer.default_weight.dtype.name, 'float32')\n self.assertEqual(layer.weight_without_name.dtype.name, 'float32')\n self.assertEqual(len(layer.losses), 1)\n if not context.executing_eagerly():\n # Cannot access tensor.name in eager execution.\n self.assertTrue('Variable_2/Regularizer' in layer.losses[0].name)\n\n @keras_parameterized.run_all_keras_modes(always_skip_v1=True)\n def test_learning_phase_freezing_for_layers(self):\n class LearningPhaseLayer(keras.layers.Layer):\n\n def call(self, inputs):\n return keras.backend.in_train_phase(\n lambda: array_ops.ones_like(inputs),\n lambda: array_ops.zeros_like(inputs))\n\n def get_learning_phase_value():\n model = keras.models.Sequential([LearningPhaseLayer(input_shape=(1,))])\n model._run_eagerly = testing_utils.should_run_eagerly()\n model._experimental_run_tf_function = (\n testing_utils.should_run_tf_function())\n return np.sum(model(np.ones((1, 1))))\n\n self.assertEqual(get_learning_phase_value(), 0)\n\n # Test scope.\n with keras.backend.learning_phase_scope(1):\n self.assertEqual(get_learning_phase_value(), 1)\n\n # The effects of the scope end after exiting it.\n self.assertEqual(get_learning_phase_value(), 0)\n\n # Test setting.\n keras.backend.set_learning_phase(1)\n self.assertEqual(get_learning_phase_value(), 1)\n keras.backend.set_learning_phase(0)\n self.assertEqual(get_learning_phase_value(), 0)\n\n @keras_parameterized.run_all_keras_modes\n def test_learning_phase_freezing_for_layers_in_predict(self):\n if not (testing_utils.should_run_eagerly() or\n testing_utils.should_run_tf_function()):\n self.skipTest('Predict fails to override the outer learning phase in'\n 'the FuncGraph path.')\n\n class LearningPhaseLayer(keras.layers.Layer):\n\n def call(self, inputs):\n return keras.backend.in_train_phase(\n lambda: array_ops.ones_like(inputs),\n lambda: array_ops.zeros_like(inputs))\n\n def get_learning_phase_value():\n model = keras.models.Sequential([LearningPhaseLayer(input_shape=(1,))])\n model._run_eagerly = testing_utils.should_run_eagerly()\n model._experimental_run_tf_function = (\n testing_utils.should_run_tf_function())\n return np.sum(model.predict(np.ones((1, 1))))\n\n self.assertEqual(get_learning_phase_value(), 0)\n\n # Test scope.\n with keras.backend.learning_phase_scope(1):\n self.assertEqual(get_learning_phase_value(), 0)\n\n # The effects of the scope end after exiting it.\n self.assertEqual(get_learning_phase_value(), 0)\n\n # Test setting.\n keras.backend.set_learning_phase(1)\n self.assertEqual(get_learning_phase_value(), 0)\n keras.backend.set_learning_phase(0)\n self.assertEqual(get_learning_phase_value(), 0)\n\n # Cannot be enabled with `run_eagerly=True`, see b/123904578\n @test_util.run_all_in_graph_and_eager_modes\n def test_layer_can_return_variable(self):\n\n class ComputeSum(keras.layers.Layer):\n\n def __init__(self):\n super(ComputeSum, self).__init__()\n self.total = variables.Variable(\n initial_value=array_ops.zeros((1, 1)), trainable=False)\n if not context.executing_eagerly():\n keras.backend.get_session().run(self.total.initializer)\n\n def call(self, inputs):\n self.total.assign_add(inputs)\n return self.total\n\n inputs = keras.Input(shape=(1,))\n model = keras.Model(inputs, ComputeSum()(inputs))\n model.predict(np.ones((1, 1)))\n\n def _get_layer_with_training_arg(self):\n\n class TrainingLayer(keras.layers.Layer):\n \"\"\"A layer with a `training` argument in a defuned `call`.\"\"\"\n\n @def_function.function\n def call(self, inputs, training=None):\n if training is None:\n training = keras.backend.learning_phase()\n return tf_utils.smart_cond(training,\n lambda: array_ops.ones_like(inputs),\n lambda: array_ops.zeros_like(inputs))\n\n return TrainingLayer()\n\n @keras_parameterized.run_with_all_model_types\n # b/124459427: can't test with `run_eagerly=True` for now.\n @test_util.run_in_graph_and_eager_modes\n def test_training_arg_in_defun(self):\n layer = self._get_layer_with_training_arg()\n model = testing_utils.get_model_from_layers([layer], input_shape=(1,))\n model.compile(rmsprop.RMSprop(0.),\n loss='mae')\n history = model.fit(np.zeros((1, 1)), np.zeros((1, 1)))\n self.assertEqual(history.history['loss'][0], 1.)\n loss = model.evaluate(np.zeros((1, 1)), np.zeros((1, 1)))\n self.assertEqual(loss, 0.)\n\n # Test that the argument injection performed in `call` is not active\n # when the argument is passed explicitly.\n layer = self._get_layer_with_training_arg()\n inputs = keras.Input(shape=(1,))\n # Pass `training` by name\n outputs = layer(inputs, training=False)\n model = keras.Model(inputs, outputs)\n model.compile(rmsprop.RMSprop(0.),\n loss='mae')\n history = model.fit(np.zeros((1, 1)), np.zeros((1, 1)))\n self.assertEqual(history.history['loss'][0], 0.)\n\n @keras_parameterized.run_with_all_model_types\n @keras_parameterized.run_all_keras_modes\n def test_raw_variable_assignment(self):\n\n class RawVariableLayer(keras.layers.Layer):\n\n def __init__(self, **kwargs):\n super(RawVariableLayer, self).__init__(**kwargs)\n # Test variables in nested structure.\n self.var_list = [variables.Variable(1.), {'a': variables.Variable(2.)}]\n\n def call(self, inputs):\n return inputs * self.var_list[0] * self.var_list[1]['a']\n\n model = testing_utils.get_model_from_layers([RawVariableLayer()],\n input_shape=(10,))\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n x, y = np.ones((10, 10)), np.ones((10, 10))\n # Checks that variables get initialized.\n model.fit(x, y, batch_size=2, epochs=2)\n\n @test_util.run_in_graph_and_eager_modes\n def test_layer_names(self):\n inputs = keras.layers.Input(shape=[2])\n add1 = inputs + inputs\n add2 = keras.layers.Add()([inputs, inputs])\n add3 = inputs + inputs\n add4 = keras.layers.Add()([inputs, inputs])\n model = keras.models.Model(\n inputs=[inputs], outputs=[add1, add2, add3, add4])\n self.assertEqual(\n [l.name for l in model.layers],\n ['input_1', 'tf_op_layer_add', 'add', 'tf_op_layer_add_2', 'add_1'])\n\n def test_add_trainable_weight_on_frozen_layer(self):\n\n class TestLayer(keras.layers.Layer):\n\n def build(self, input_shape):\n self.w = self.add_weight(shape=(), trainable=True)\n\n def call(self, inputs):\n return self.w * inputs\n\n layer = TestLayer()\n layer.trainable = False\n layer.build(None)\n layer.trainable = True\n self.assertListEqual(layer.trainable_weights, [layer.w])\n\n @keras_parameterized.run_with_all_model_types\n @keras_parameterized.run_all_keras_modes\n def test_passing_initial_weights_values(self):\n kernel_value = np.random.random((10, 2))\n layer_with_weights = keras.layers.Dense(\n 2, use_bias=False, weights=[kernel_value])\n\n model = testing_utils.get_model_from_layers([layer_with_weights],\n input_shape=(10,))\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n inputs = np.random.random((3, 10))\n out = model.predict(inputs)\n self.assertAllClose(model.layers[-1].get_weights()[0], kernel_value)\n self.assertAllClose(out, np.dot(inputs, kernel_value))\n\n @test_util.run_in_graph_and_eager_modes\n def test_set_weights_and_get_weights(self):\n layer = keras.layers.Dense(2)\n layer.build((None, 10))\n kernel = np.random.random((10, 2))\n bias = np.random.random((2,))\n layer.set_weights([kernel, bias])\n weights = layer.get_weights()\n self.assertEqual(len(weights), 2)\n self.assertAllClose(weights[0], kernel)\n self.assertAllClose(weights[1], bias)\n with self.assertRaisesRegexp(\n ValueError, 'but the layer was expecting 2 weights'):\n layer.set_weights([1, 2, 3])\n with self.assertRaisesRegexp(\n ValueError, 'not compatible with provided weight shape'):\n layer.set_weights([kernel.T, bias])\n\n def test_get_config_error(self):\n\n class MyLayer(keras.layers.Layer):\n\n def __init__(self, my_kwarg='default', **kwargs):\n super(MyLayer, self).__init__(**kwargs)\n self.my_kwarg = my_kwarg\n\n # `__init__` includes kwargs but `get_config` is not overridden, so\n # an error should be thrown:\n with self.assertRaises(NotImplementedError):\n MyLayer('custom').get_config()\n\n class MyLayerNew(keras.layers.Layer):\n\n def __init__(self, my_kwarg='default', **kwargs):\n super(MyLayerNew, self).__init__(**kwargs)\n self.my_kwarg = my_kwarg\n\n def get_config(self):\n config = super(MyLayerNew, self).get_config()\n config['my_kwarg'] = self.my_kwarg\n return config\n\n # Test to make sure that error is not raised if the method call is\n # from an overridden `get_config`:\n self.assertEqual(MyLayerNew('custom').get_config()['my_kwarg'], 'custom')\n\n class MyLayerNew2(keras.layers.Layer):\n\n def __init__(self, name='MyLayerName', dtype=None, **kwargs): # pylint:disable=redefined-outer-name\n super(MyLayerNew2, self).__init__(name=name, dtype=dtype, **kwargs)\n\n # Check that if the kwargs in `__init__` are base layer constructor\n # arguments, no error is thrown:\n self.assertEqual(MyLayerNew2(name='New').get_config()['name'], 'New')\n\n\nclass SymbolicSupportTest(test.TestCase):\n\n def test_using_symbolic_tensors_with_tf_ops(self):\n # Single-input.\n x = keras.Input((3,))\n y = math_ops.square(x)\n self.assertEqual(y.graph, keras.backend.get_graph())\n\n # Multi-inputs.\n x1, x2 = keras.Input((3,)), keras.Input((3,))\n y = array_ops.concat([x1, x2], axis=1)\n self.assertEqual(y.graph, keras.backend.get_graph())\n\n # Mixing Keras symbolic tensors and graph tensors from the same graph works.\n with keras.backend.get_graph().as_default():\n x1 = keras.Input((3,))\n x2 = keras.Input((3,))\n y = math_ops.matmul(x1, x2)\n self.assertEqual(y.graph, keras.backend.get_graph())\n\n # Creating same op type (matmul) multiple times in the Keras graph works.\n x1 = keras.Input((3,))\n x2 = keras.Input((3,))\n y = math_ops.matmul(x1, x2)\n self.assertEqual(y.graph, keras.backend.get_graph())\n\n def test_mixing_eager_and_graph_tensors(self):\n with ops.Graph().as_default():\n x1 = array_ops.ones((3, 3))\n x2 = array_ops.ones((3, 3))\n self.assertIsInstance(x2, ops.EagerTensor)\n with self.assertRaisesRegexp(TypeError, 'Graph tensors'):\n math_ops.matmul(x1, x2)\n\n def test_mixing_numpy_arrays_and_graph_tensors(self):\n with ops.Graph().as_default():\n x1 = array_ops.ones((3, 3))\n x2 = np.ones((3, 3), dtype='float32')\n with self.assertRaisesRegexp(TypeError, 'Graph tensors'):\n math_ops.matmul(x1, x2)\n\n @test_util.run_in_graph_and_eager_modes\n def test_mixing_keras_symbolic_tensors_and_eager_tensors(self):\n x1 = keras.Input((3,))\n x2 = array_ops.ones((3, 3))\n y = math_ops.matmul(x1, x2)\n self.assertEqual(y.graph, keras.backend.get_graph())\n fn = keras.backend.function(inputs=[x1], outputs=[y])\n x_val = np.random.random((3, 3))\n y_val = np.ones((3, 3))\n self.assertAllClose(fn([x_val])[0],\n np.matmul(x_val, y_val),\n atol=1e-5)\n\n @test_util.run_in_graph_and_eager_modes\n def test_mixing_keras_symbolic_tensors_and_numpy_arrays(self):\n x1 = keras.Input((3,))\n x2 = np.ones((3, 3), dtype='float32')\n y = math_ops.matmul(x1, x2)\n self.assertEqual(y.graph, keras.backend.get_graph())\n fn = keras.backend.function(inputs=[x1], outputs=[y])\n x_val = np.random.random((3, 3))\n y_val = np.ones((3, 3))\n self.assertAllClose(fn([x_val])[0],\n np.matmul(x_val, y_val),\n atol=1e-5)\n\n @test_util.run_in_graph_and_eager_modes\n def test_reraising_exception(self):\n # When layer is not dynamic, we have some pattern matching during exception\n # handling to detect when the user is trying to use python control flow.\n # When an exception is thrown but the pattern doesn't match, we want to\n # preserve the originating stack trace. An early implementation of this\n # logic lost the stack trace. We test the correct behavior here.\n\n class TypeErrorLayer(base_layer.Layer):\n\n def call(self, inputs):\n def easily_identifiable_name():\n raise TypeError('Non-matching TypeError message.')\n easily_identifiable_name()\n\n inputs = keras.Input((3,))\n\n try:\n _ = TypeErrorLayer()(inputs)\n except TypeError as e:\n if hasattr(e, 'ag_error_metadata'):\n self.assertIn('easily_identifiable_name', str(e))\n # See ErrorMetadataBase in autograph/pyct/errors.py\n # Topmost frame corresponds to `call` itself.\n function_name = e.ag_error_metadata.translated_stack[-2].function_name\n else:\n tb = traceback.extract_tb(sys.exc_info()[2])\n last_entry = tb[-1]\n function_name = last_entry[2]\n self.assertEqual(function_name, 'easily_identifiable_name')\n\n @test_util.run_in_graph_and_eager_modes\n def test_summaries_in_tf_function(self):\n if not context.executing_eagerly():\n return\n\n class MyLayer(keras.layers.Layer):\n\n def call(self, inputs):\n summary_ops_v2.scalar('mean', math_ops.reduce_mean(inputs))\n return inputs\n\n tmp_dir = self.get_temp_dir()\n writer = summary_ops_v2.create_file_writer_v2(tmp_dir)\n with writer.as_default(), summary_ops_v2.always_record_summaries():\n my_layer = MyLayer()\n x = array_ops.ones((10, 10))\n\n def my_fn(x):\n return my_layer(x)\n\n _ = my_fn(x)\n\n event_file = gfile.Glob(os.path.join(tmp_dir, 'events*'))\n self.assertLen(event_file, 1)\n event_file = event_file[0]\n tags = set()\n for e in summary_iterator.summary_iterator(event_file):\n for val in e.summary.value:\n tags.add(val.tag)\n self.assertEqual(set(['my_layer/mean']), tags)\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass NestedTrackingTest(test.TestCase):\n\n def test_nested_layer_variable_tracking(self):\n # Test that variables from nested sublayers are\n # being tracked by subclassed layers.\n\n class MyLayer(keras.layers.Layer):\n\n def __init__(self):\n super(MyLayer, self).__init__()\n self.dense1 = keras.layers.Dense(1)\n self.dense2 = keras.layers.BatchNormalization()\n\n def build(self, input_shape):\n self.v1 = self.add_weight('v1', shape=input_shape[1:].as_list())\n self.v2 = variables.Variable(\n name='v2',\n initial_value=np.zeros(input_shape[1:].as_list(), dtype='float32'),\n trainable=False)\n\n def call(self, inputs):\n x = self.dense1(inputs) + self.dense2(inputs)\n return x + self.v1 + self.v2\n\n layer = MyLayer()\n inputs = keras.Input((1,))\n _ = layer(inputs)\n\n self.assertEqual(len(layer.weights), 8)\n self.assertEqual(len(layer.trainable_weights), 5)\n self.assertEqual(len(layer.non_trainable_weights), 3)\n\n layer.dense1.trainable = False\n self.assertEqual(len(layer.weights), 8)\n self.assertEqual(len(layer.trainable_weights), 3)\n self.assertEqual(len(layer.non_trainable_weights), 5)\n\n layer.trainable = False\n self.assertEqual(len(layer.weights), 8)\n self.assertEqual(len(layer.trainable_weights), 0)\n self.assertEqual(len(layer.non_trainable_weights), 8)\n self.assertEqual(\n set([layer.dense1, layer.dense2, layer.v1, layer.v2]),\n set([obj for unused_name, obj in layer._checkpoint_dependencies]))\n\n def test_nested_layer_updates_losses_tracking(self):\n # Test that updates and losses from nested sublayers are\n # being tracked by subclassed layers.\n\n class UpdateAndLossLayer(keras.layers.Layer):\n\n def build(self, _):\n self.v1 = self.add_weight('v1', shape=())\n\n def call(self, inputs):\n self.add_loss(math_ops.reduce_sum(inputs))\n self.add_update(state_ops.assign_add(self.v1, 1))\n return inputs + 1\n\n class MyLayer(keras.layers.Layer):\n\n def build(self, _):\n self.v1 = self.add_weight('v1', shape=())\n\n def __init__(self):\n super(MyLayer, self).__init__()\n self.ul1 = UpdateAndLossLayer()\n self.ul2 = UpdateAndLossLayer()\n\n def call(self, inputs):\n self.add_loss(math_ops.reduce_sum(inputs))\n self.add_update(state_ops.assign_add(self.v1, 1))\n x = self.ul1(inputs)\n return self.ul2(x)\n\n layer = MyLayer()\n\n if context.executing_eagerly():\n inputs = array_ops.ones((3, 1))\n _ = layer(inputs)\n self.assertEqual(len(layer.losses), 3)\n self.assertLen(layer.get_losses_for(None), 3)\n else:\n inputs = keras.Input((1,))\n _ = layer(inputs)\n self.assertEqual(len(layer.losses), 3)\n self.assertEqual(len(layer.updates), 3)\n self.assertLen(layer.get_losses_for(None), 3)\n\n def test_attribute_reassignment(self):\n l = keras.layers.Layer()\n l.a = keras.layers.Layer()\n l.a = []\n l.a = variables.Variable(1.)\n l.a = keras.layers.Layer()\n last_assignment = keras.layers.Layer()\n l.a = last_assignment\n l.b = variables.Variable(1.)\n del l.b\n l.c = keras.layers.Layer()\n del l.c\n l.d = last_assignment\n del l.d\n self.assertEqual([last_assignment], l._layers)\n self.assertEqual([], l.trainable_weights)\n self.assertEqual([], l.non_trainable_weights)\n self.assertEqual([], l.weights)\n del l.a\n self.assertEqual([], l._layers)\n\n def test_assign_op_not_tracked_as_variable(self):\n\n class LayerWithAssignAttr(keras.layers.Layer):\n\n def build(self, input_shape):\n self.v = variables.Variable(1.)\n self.v_assign = self.v.assign_add(2.)\n\n layer = LayerWithAssignAttr()\n layer.build((10, 10))\n\n self.assertEqual([layer.v], layer.variables)\n\n def test_layer_class_not_tracked_as_sublayer(self):\n # See https://github.com/tensorflow/tensorflow/issues/27431 for details.\n\n class LayerWithClassAttribute(keras.layers.Layer):\n\n def __init__(self):\n super(LayerWithClassAttribute, self).__init__()\n self.layer_fn = keras.layers.Dense\n\n layer = LayerWithClassAttribute()\n self.assertEmpty(layer.variables)\n self.assertEmpty(layer.submodules)\n\n def test_layer_call_fn_args(self):\n\n class NonDefunLayer(keras.layers.Layer):\n\n def call(self, inputs, a, mask, b=None, training=None):\n return inputs\n\n class DefunLayer(keras.layers.Layer):\n\n @def_function.function\n def call(self, x, mask, a, training=None, b=None):\n return x\n\n nondefun_layer = NonDefunLayer()\n self.assertEqual(nondefun_layer._call_fn_args,\n ['inputs', 'a', 'mask', 'b', 'training'])\n defun_layer = DefunLayer()\n self.assertEqual(defun_layer._call_fn_args,\n ['x', 'mask', 'a', 'training', 'b'])\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass NameScopingTest(keras_parameterized.TestCase):\n\n def test_name_scope_layer(self):\n x = keras.backend.placeholder(shape=(10, 10))\n layer = keras.layers.Dense(10, name='MyName')\n layer(x)\n self.assertEqual(layer.bias.name, 'MyName/bias:0')\n self.assertEqual(layer.kernel.name, 'MyName/kernel:0')\n\n def test_name_scope_sublayer(self):\n\n class NameScopeTracker(keras.layers.Layer):\n\n def call(self, inputs):\n self.active_name_scope = ops.get_name_scope()\n return inputs\n\n x = keras.backend.placeholder(shape=(10, 10))\n sublayer = NameScopeTracker(name='Sublayer')\n layer = keras.layers.Dense(10, activation=sublayer, name='MyName2')\n layer(x)\n self.assertEqual(layer.bias.name, 'MyName2/bias:0')\n self.assertEqual(layer.kernel.name, 'MyName2/kernel:0')\n self.assertEqual(sublayer.active_name_scope, 'MyName2/Sublayer')\n\n def test_name_scope_tf_tensor(self):\n x = ops.convert_to_tensor(np.ones((10, 10)))\n layer = keras.layers.Dense(\n 10, activation=keras.layers.ReLU(name='MyAct'), name='MyName3')\n layer(x)\n self.assertEqual(layer.bias.name, 'MyName3/bias:0')\n self.assertEqual(layer.kernel.name, 'MyName3/kernel:0')\n\n\n@keras_parameterized.run_all_keras_modes(always_skip_v1=True)\nclass AutographControlFlowTest(keras_parameterized.TestCase):\n\n def test_disabling_in_context_is_matched(self):\n\n test_obj = self\n\n class MyLayer(keras.layers.Layer):\n\n def call(self, inputs, training=None):\n with test_obj.assertRaisesRegex(TypeError, 'Tensor.*as.*bool'):\n if constant_op.constant(False):\n return inputs * 1.\n return inputs * 0.\n\n @def_function.function(autograph=False)\n def test_fn():\n return MyLayer()(constant_op.constant([[1., 2., 3.]]))\n\n test_fn()\n\n def test_if_training_pattern_output(self):\n\n class MyLayer(keras.layers.Layer):\n\n def call(self, inputs, training=None):\n if training:\n return inputs * 1.\n return inputs * 0.\n\n inputs = keras.Input((3,))\n outputs = MyLayer()(inputs)\n model = keras.Model(inputs, outputs)\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n train_loss = model.train_on_batch(np.ones((2, 3)), np.ones((2, 3)))\n self.assertEqual(train_loss, 0.)\n test_loss = model.test_on_batch(np.ones((2, 3)), np.ones((2, 3)))\n self.assertEqual(test_loss, 1.)\n\n def test_if_training_pattern_loss(self):\n\n class MyLayer(keras.layers.Layer):\n\n def call(self, inputs, training=None):\n if training:\n loss = math_ops.reduce_sum(inputs)\n else:\n loss = 0.\n self.add_loss(loss)\n return inputs\n\n inputs = keras.Input((3,))\n outputs = MyLayer()(inputs)\n model = keras.Model(inputs, outputs)\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n train_loss = model.train_on_batch(np.ones((2, 3)), np.ones((2, 3)))\n self.assertEqual(train_loss, 2 * 3)\n test_loss = model.test_on_batch(np.ones((2, 3)), np.ones((2, 3)))\n self.assertEqual(test_loss, 0)\n\n def test_if_training_pattern_metric(self):\n\n class MyLayer(keras.layers.Layer):\n\n def call(self, inputs, training=None):\n if training:\n metric = math_ops.reduce_sum(inputs)\n else:\n metric = 0.\n self.add_metric(metric, name='my_metric', aggregation='mean')\n return inputs\n\n inputs = keras.Input((3,))\n outputs = MyLayer()(inputs)\n model = keras.Model(inputs, outputs)\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n _, train_metric = model.train_on_batch(np.ones((2, 3)),\n np.ones((2, 3)))\n self.assertEqual(train_metric, 2 * 3)\n _, test_metric = model.test_on_batch(np.ones((2, 3)),\n np.ones((2, 3)))\n self.assertEqual(test_metric, 0)\n\n def test_if_training_pattern_update(self):\n\n class MyLayer(keras.layers.Layer):\n\n def build(self, input_shape):\n self.counter = self.add_weight(\n shape=(), trainable=False, initializer='zeros')\n\n def call(self, inputs, training=None):\n if training:\n increment = 1.\n else:\n increment = 0.\n self.counter.assign_add(increment)\n return inputs\n\n inputs = keras.Input((3,))\n layer = MyLayer()\n outputs = layer(inputs)\n model = keras.Model(inputs, outputs)\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n model.train_on_batch(np.ones((2, 3)), np.ones((2, 3)))\n self.assertEqual(keras.backend.get_value(layer.counter), 1.)\n\n def test_conditional_updates_in_call(self):\n\n class MyLayer(keras.layers.Layer):\n\n def __init__(self):\n super(MyLayer,\n self).__init__(dynamic=testing_utils.should_run_eagerly())\n\n def build(self, input_shape):\n self.counter = self.add_weight(\n shape=(), trainable=False, initializer='zeros')\n\n def call(self, inputs, training=None):\n if training:\n z = math_ops.reduce_sum(inputs)\n self.add_update(lambda: self.counter.assign_add(z))\n return inputs\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n if testing_utils.should_run_eagerly():\n inputs = keras.Input((3,))\n layer = MyLayer()\n outputs = layer(inputs)\n model = keras.Model(inputs, outputs)\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n model.train_on_batch(np.ones((2, 3)), np.ones((2, 3)))\n self.assertEqual(keras.backend.get_value(layer.counter), 6.)\n else:\n # TODO(fchollet): support the same workflow in graph mode.\n with self.assertRaisesRegexp(RuntimeError,\n '`add_update` in a control flow branch'):\n layer = MyLayer()\n layer(keras.Input((3,)))\n _ = layer.updates\n\n def test_conditional_losses_in_call(self):\n\n class MyLayer(keras.layers.Layer):\n\n def __init__(self):\n super(MyLayer,\n self).__init__(dynamic=testing_utils.should_run_eagerly())\n\n def call(self, inputs, training=None):\n if training:\n self.add_loss(math_ops.reduce_sum(inputs))\n return inputs\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n if testing_utils.should_run_eagerly():\n inputs = keras.Input((3,))\n layer = MyLayer()\n outputs = layer(inputs)\n model = keras.Model(inputs, outputs)\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n loss = model.train_on_batch(np.ones((2, 3)), np.ones((2, 3)))\n self.assertEqual(loss, 2 * 3)\n else:\n with self.assertRaisesRegexp(RuntimeError,\n '`add_loss` in a control flow branch'):\n layer = MyLayer()(keras.Input((3,)))\n\n def test_conditional_callable_losses(self):\n model = keras.Sequential([\n keras.layers.Dense(\n 1, kernel_regularizer=keras.regularizers.l2(1e-4), input_shape=(1,))\n ])\n model._run_eagerly = testing_utils.should_run_eagerly()\n model._experimental_run_tf_function = testing_utils.should_run_tf_function()\n\n def assert_graph(t):\n if not context.executing_eagerly():\n self.assertEqual(t.graph, ops.get_default_graph())\n\n @def_function.function\n def get_losses(t):\n if t < 0:\n return math_ops.reduce_sum(model.losses) * t\n else:\n return math_ops.reduce_sum(model.losses)\n\n assert_graph(get_losses(constant_op.constant(2.)))\n assert_graph(get_losses(constant_op.constant(0.5)))\n\n def test_conditional_metrics_in_call(self):\n\n class MyLayer(keras.layers.Layer):\n\n def __init__(self):\n super(MyLayer,\n self).__init__(dynamic=testing_utils.should_run_eagerly())\n\n def call(self, inputs, training=None):\n if training:\n self.add_metric(math_ops.reduce_sum(inputs),\n name='sum',\n aggregation='mean')\n return inputs\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n if testing_utils.should_run_eagerly():\n inputs = keras.Input((3,))\n layer = MyLayer()\n outputs = layer(inputs)\n model = keras.Model(inputs, outputs)\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n history = model.fit(np.ones((2, 3)), np.ones((2, 3)))\n self.assertEqual(history.history['sum'][-1], 2 * 3)\n else:\n # TODO(fchollet): support the same workflow in graph mode.\n with self.assertRaisesRegexp(RuntimeError,\n '`add_metric` in a control flow branch'):\n layer = MyLayer()(keras.Input((3,)))\n\n def test_conditional_activity_regularizer_in_call(self):\n\n class TestModel(keras.Model):\n\n def __init__(self):\n super(TestModel, self).__init__(\n name='test_model', dynamic=testing_utils.should_run_eagerly())\n self.layer = keras.layers.Dense(2, activity_regularizer='l2')\n\n def call(self, x, training=None):\n if math_ops.greater(math_ops.reduce_sum(x), 0.0):\n return self.layer(x)\n else:\n return self.layer(x)\n\n model = TestModel()\n model.compile(\n loss='mse',\n optimizer='sgd',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n\n x = np.ones(shape=(10, 1))\n y = np.ones(shape=(10, 2))\n\n if testing_utils.should_run_eagerly():\n model.fit(x, y, epochs=2, batch_size=5)\n else:\n with self.assertRaisesRegexp(\n RuntimeError, '`activity_regularizer` in a control flow branch'):\n model.fit(x, y, epochs=2, batch_size=5)\n\n def test_conditional_activity_regularizer_with_wrappers_in_call(self):\n\n class TestModel(keras.Model):\n\n def __init__(self):\n super(TestModel, self).__init__(\n name='test_model', dynamic=testing_utils.should_run_eagerly())\n self.layer = keras.layers.TimeDistributed(\n keras.layers.Dense(2, activity_regularizer='l2'),\n input_shape=(3, 4))\n\n def call(self, x, training=None):\n if math_ops.greater(math_ops.reduce_sum(x), 0.0):\n return self.layer(x)\n else:\n return self.layer(x)\n\n model = TestModel()\n model.compile(\n loss='mse',\n optimizer='sgd',\n run_eagerly=testing_utils.should_run_eagerly(),\n experimental_run_tf_function=testing_utils.should_run_tf_function())\n\n x = np.ones(shape=(10, 3, 4))\n y = np.ones(shape=(10, 3, 2))\n\n if testing_utils.should_run_eagerly():\n model.fit(x, y, epochs=2, batch_size=5)\n else:\n with self.assertRaisesRegexp(\n RuntimeError, '`activity_regularizer` in a control flow branch'):\n model.fit(x, y, epochs=2, batch_size=5)\n\n\nclass AddLayer(keras.layers.Layer):\n \"\"\"A layer which adds it's input to a variable.\n\n Useful for testing a layer with a variable\n \"\"\"\n\n def build(self, _):\n self.v = self.add_weight('v', (), initializer='ones')\n self.built = True\n\n def call(self, inputs):\n return inputs + self.v\n\n\nclass IdentityLayer(keras.layers.Layer):\n \"\"\"A layer that returns it's input.\n\n Useful for testing a layer without a variable.\n \"\"\"\n\n def call(self, inputs):\n return inputs\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass DTypeTest(keras_parameterized.TestCase):\n\n # This class only have tests relating to layer.dtype. Tests for dtype policies\n # are in mixed_precision/experimental/keras_test.py\n\n def _const(self, dtype):\n return array_ops.constant(1, dtype=dtype)\n\n @testing_utils.enable_v2_dtype_behavior\n def test_dtype_defaults_to_floatx(self):\n layer = AddLayer()\n self.assertEqual(layer.dtype, 'float32')\n layer(self._const('float64'))\n self.assertEqual(layer.dtype, 'float32') # dtype should not change\n\n try:\n backend.set_floatx('float64')\n layer = AddLayer()\n self.assertEqual(layer.dtype, 'float64')\n finally:\n backend.set_floatx('float32')\n\n @testing_utils.enable_v2_dtype_behavior\n def test_passing_dtype_to_constructor(self):\n layer = IdentityLayer(dtype='float64')\n layer(self._const('float32'))\n self.assertEqual(layer.dtype, 'float64')\n\n layer = IdentityLayer(dtype='int32')\n layer(self._const('float32'))\n self.assertEqual(layer.dtype, 'int32')\n\n layer = IdentityLayer(dtype=dtypes.float64)\n layer(self._const('float32'))\n self.assertEqual(layer.dtype, 'float64')\n\n @testing_utils.enable_v2_dtype_behavior\n def input_cast_to_dtype(self):\n layer = AddLayer()\n\n # Input should be cast to layer.dtype, so output should also be layer.dtype\n self.assertEqual(layer(self._const('float64')).dtype, 'float32')\n\n layer = AddLayer(dtype='float64')\n self.assertEqual(layer(self._const('float32')).dtype, 'float64')\n\n # Test inputs are not casted if layer.dtype is not floating-point\n layer = IdentityLayer(dtype='int32')\n self.assertEqual(layer(self._const('float64')).dtype, 'float64')\n\n # Test inputs are not casted if the inputs are not floating-point\n layer = IdentityLayer(dtype='float32')\n self.assertEqual(layer(self._const('int32')).dtype, 'int32')\n\n # Test Numpy arrays are casted\n layer = IdentityLayer(dtype='float64')\n self.assertEqual(layer(np.array(1, dtype='float32')).dtype, 'float64')\n\n # Test Python floats are casted\n layer = IdentityLayer(dtype='float64')\n self.assertEqual(layer(1.).dtype, 'float64')\n\n @testing_utils.enable_v2_dtype_behavior\n def multiple_inputs_cast_to_dtype(self):\n\n class MultiIdentityLayer(keras.layers.Layer):\n\n def call(self, inputs):\n return [array_ops.identity(x) for x in inputs]\n\n # Testing layer with default dtype of float32\n layer = MultiIdentityLayer()\n x, y = layer([self._const('float16'), self._const('float32')])\n self.assertEqual(x.dtype, 'float32')\n self.assertEqual(y.dtype, 'float32')\n\n # Test passing dtype to the constructor\n layer = MultiIdentityLayer(dtype='float64')\n x, y = layer([self._const('float16'), self._const('float32')])\n self.assertEqual(x.dtype, 'float64')\n self.assertEqual(y.dtype, 'float64')\n\n # Test several non-floating point types\n layer = MultiIdentityLayer(dtype='float64')\n x, y, z, w = layer([self._const('float16'), self._const('bool'),\n self._const('float64'), self._constant('complex64')])\n self.assertEqual(x.dtype, 'float64')\n self.assertEqual(y.dtype, 'bool')\n self.assertEqual(z.dtype, 'float64')\n self.assertEqual(w.dtype, 'complex64')\n\n @testing_utils.enable_v2_dtype_behavior\n def test_extra_args_and_kwargs_not_casted(self):\n\n class IdentityLayerWithArgs(keras.layers.Layer):\n\n def call(self, inputs, *args, **kwargs):\n return nest.flatten([inputs, args, kwargs])\n\n layer = IdentityLayerWithArgs(dtype='float64')\n x, y, z = layer(self._const('float16'), self._const('float16'),\n kwarg=self._const('float16'))\n self.assertEqual(x.dtype, 'float64')\n self.assertEqual(y.dtype, 'float16')\n self.assertEqual(z.dtype, 'float16')\n\n @testing_utils.enable_v2_dtype_behavior\n def test_layer_without_autocast(self):\n\n class IdentityLayerWithoutAutocast(IdentityLayer):\n\n def __init__(self, *args, **kwargs):\n kwargs['experimental_autocast'] = False\n super(IdentityLayerWithoutAutocast, self).__init__(*args, **kwargs)\n\n layer = IdentityLayerWithoutAutocast(dtype='float64')\n self.assertEqual(layer(self._const('float32')).dtype, 'float32')\n\n @testing_utils.enable_v2_dtype_behavior\n def test_dtype_warnings(self):\n # Test a layer warns when it casts inputs.\n layer = IdentityLayer()\n with test.mock.patch.object(tf_logging, 'warn') as mock_warn:\n layer(self._const('float64'))\n self.assertRegexpMatches(\n str(mock_warn.call_args),\n \".*from dtype float64 to the layer's dtype of float32.*\"\n \"The layer has dtype float32 because.*\")\n\n # Test a layer does not warn a second time\n with test.mock.patch.object(tf_logging, 'warn') as mock_warn:\n layer(self._const('float64'))\n mock_warn.assert_not_called()\n\n # Test a new layer can warn even if a different layer already warned\n layer = IdentityLayer()\n with test.mock.patch.object(tf_logging, 'warn') as mock_warn:\n layer(self._const('float64'))\n self.assertRegexpMatches(\n str(mock_warn.call_args),\n \".*from dtype float64 to the layer's dtype of float32.*\"\n \"The layer has dtype float32 because.*\")\n\n # Test a layer does not warn if a dtype is passed\n layer = IdentityLayer(dtype='float32')\n with test.mock.patch.object(tf_logging, 'warn') as mock_warn:\n layer(self._const('float64'))\n mock_warn.assert_not_called()\n\n # Test a layer does not warn if a Policy is set:\n with policy.policy_scope('float32'):\n layer = IdentityLayer()\n with test.mock.patch.object(tf_logging, 'warn') as mock_warn:\n layer(self._const('float64'))\n mock_warn.assert_not_called()\n\n @testing_utils.enable_v2_dtype_behavior\n def test_compute_output_signature(self):\n\n class IdentityLayerWithOutputShape(IdentityLayer):\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n layer = IdentityLayerWithOutputShape(dtype='float64')\n output_signature = layer.compute_output_signature(\n tensor_spec.TensorSpec(shape=(), dtype='float32'))\n self.assertEqual(output_signature.shape, ())\n self.assertEqual(output_signature.dtype, 'float64')\n\n @testing_utils.enable_v2_dtype_behavior\n def test_passing_non_tensor(self):\n layer = IdentityLayer()\n x = object()\n y = layer(x) # Layer should not cast 'x', as it's not a tensor\n self.assertIs(x, y)\n\n @testing_utils.disable_v2_dtype_behavior\n def test_v1_behavior(self):\n # Test dtype defaults to None and inferred from input\n layer = IdentityLayer()\n self.assertIsNone(layer.dtype)\n layer(self._const('float64'))\n self.assertEqual(layer.dtype, 'float64')\n\n # Test layer does not cast to dtype\n self.assertEqual(layer(self._const('float32')).dtype, 'float32')\n\n_LAYERS_TO_TEST = [\n (keras.layers.Dense, (1,), collections.OrderedDict(units=[1])),\n (keras.layers.Activation, (2, 2),\n collections.OrderedDict(activation=['relu'])),\n (keras.layers.Dropout, (16,), collections.OrderedDict(rate=[0.25])),\n (keras.layers.BatchNormalization, (8, 8, 3), collections.OrderedDict(\n axis=[3], center=[True, False], scale=[True, False])),\n (keras.layers.Conv1D, (8, 8), collections.OrderedDict(\n filters=[1], kernel_size=[1, 3], strides=[1, 2],\n padding=['valid', 'same'], use_bias=[True, False],\n kernel_regularizer=[None, 'l2'])),\n (keras.layers.Conv2D, (8, 8, 3), collections.OrderedDict(\n filters=[1], kernel_size=[1, 3], strides=[1, 2],\n padding=['valid', 'same'], use_bias=[True, False],\n kernel_regularizer=[None, 'l2'])),\n (keras.layers.LSTM, (8, 8), collections.OrderedDict(\n units=[1],\n activation=[None, 'relu'],\n kernel_regularizer=[None, 'l2'],\n dropout=[0, 0.5],\n stateful=[True, False],\n unroll=[True, False])),\n]\n\nOUTPUT_TEST_CASES = []\nfor layer_type, inp_shape, arg_dict in _LAYERS_TO_TEST:\n arg_combinations = [[(k, i) for i in v] for k, v in arg_dict.items()] # pylint: disable=g-complex-comprehension\n for arguments in it.product(*arg_combinations):\n name = '_{}_{}'.format(layer_type.__name__,\n '_'.join('{}_{}'.format(k, v) for k, v in arguments))\n OUTPUT_TEST_CASES.append(\n (name, layer_type, inp_shape, {k: v for k, v in arguments}))\n\n\nclass OutputTypeTest(keras_parameterized.TestCase):\n \"\"\"Test that layers and models produce the correct tensor types.\"\"\"\n\n # In v1 graph there are only symbolic tensors.\n @keras_parameterized.run_all_keras_modes(always_skip_v1=True)\n @parameterized.named_parameters(*OUTPUT_TEST_CASES)\n def test_layer_outputs(self, layer_to_test, input_shape, layer_kwargs):\n layer = layer_to_test(**layer_kwargs)\n\n input_data = np.ones(shape=(2,) + input_shape, dtype=np.float32)\n layer_result = layer(input_data)\n\n inp = keras.layers.Input(shape=input_shape, batch_size=2)\n model = keras.models.Model(inp, layer_to_test(**layer_kwargs)(inp))\n model_result = model(input_data)\n\n for x in [layer_result, model_result]:\n if not isinstance(x, ops.Tensor):\n raise ValueError('Tensor or EagerTensor expected, got type {}'\n .format(type(x)))\n\n if isinstance(x, ops.EagerTensor) != context.executing_eagerly():\n expected_type = (ops.EagerTensor if context.executing_eagerly()\n else ops.Tensor)\n raise ValueError('Expected type {}, got type {}'\n .format(expected_type, type(x)))\n\n\nif __name__ == '__main__':\n ops.enable_eager_execution()\n test.main()\n" ]
[ [ "tensorflow.python.keras.optimizer_v2.rmsprop.RMSprop", "tensorflow.python.ops.summary_ops_v2.create_file_writer_v2", "tensorflow.python.keras.testing_utils.get_model_from_layers", "tensorflow.python.ops.array_ops.constant", "numpy.dot", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.keras.layers.Dense", "tensorflow.python.ops.state_ops.assign_add", "tensorflow.python.keras.backend.placeholder", "tensorflow.python.ops.variables.Variable", "tensorflow.python.keras.backend.function", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.layers.core.Dense", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.framework.ops.enable_eager_execution", "tensorflow.python.keras.layers.BatchNormalization", "tensorflow.python.keras.layers.ReLU", "tensorflow.python.keras.backend.learning_phase_scope", "numpy.matmul", "tensorflow.python.keras.backend.set_floatx", "tensorflow.python.platform.test.main", "tensorflow.python.ops.array_ops.ones", "tensorflow.python.keras.backend.get_session", "tensorflow.python.ops.math_ops.matmul", "tensorflow.python.eager.context.graph_mode", "numpy.zeros", "tensorflow.python.eager.context.eager_mode", "tensorflow.python.summary.summary_iterator.summary_iterator", "tensorflow.python.keras.layers.Add", "tensorflow.python.ops.math_ops.reduce_sum", "tensorflow.python.keras.keras_parameterized.run_all_keras_modes", "tensorflow.python.keras.Model", "tensorflow.python.ops.math_ops.square", "tensorflow.python.eager.def_function.function", "tensorflow.python.keras.testing_utils.should_run_tf_function", "tensorflow.python.ops.array_ops.zeros_like", "tensorflow.python.keras.models.Sequential", "tensorflow.python.keras.regularizers.l2", "tensorflow.python.ops.math_ops.reduce_mean", "tensorflow.python.keras.backend.get_value", "tensorflow.python.keras.layers.Layer", "tensorflow.python.framework.ops.get_name_scope", "tensorflow.python.keras.layers.Input", "numpy.array", "tensorflow.python.keras.testing_utils.should_run_eagerly", "tensorflow.python.ops.array_ops.ones_like", "numpy.random.random", "tensorflow.python.keras.Input", "tensorflow.python.ops.array_ops.concat", "tensorflow.python.ops.summary_ops_v2.always_record_summaries", "tensorflow.python.framework.tensor_spec.TensorSpec", "tensorflow.python.framework.ops.Graph", "numpy.ones", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.keras.models.Model", "tensorflow.python.platform.test.mock.patch.object", "tensorflow.python.keras.backend.learning_phase", "tensorflow.python.keras.backend.set_learning_phase", "tensorflow.python.keras.mixed_precision.experimental.policy.policy_scope", "tensorflow.python.keras.backend.get_graph", "tensorflow.python.util.nest.flatten", "tensorflow.python.framework.constant_op.constant" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.3", "2.2" ] } ]
CRLarry/StyleTransfer
[ "ddea81f8570232743bd7b8dbd569cf77f7cb5a28" ]
[ "royg_train.py" ]
[ "import math, random, time, pygame, sys\nfrom pygame.locals import *\nfrom PIL import Image\nimport numpy as np\nimport json\n\nprint(\"i tried\")\n\ndef random_select(distribution, color, iteration):\n random_r = int(np.random.normal(color[0], distribution[0] * 60 / (20*(iteration+1))))\n random_g = int(np.random.normal(color[1], distribution[1] * 60 / (20*(iteration+1))))\n random_b = int(np.random.normal(color[2], distribution[2] * 60 / (20*(iteration+1))))\n if (random_r > 255):\n random_r = 255\n if (random_g > 255):\n random_g = 255\n if (random_b > 255):\n random_b = 255\n if (random_r < 0):\n random_r = 0\n if (random_g < 0):\n random_g = 0\n if (random_b < 0):\n random_b = 0\n return (random_r, random_g, random_b)\n\ndef generate_color(input_key, input_color, iteration):\n\treturn (random_select(color_model[input_key], input_color, iteration))\n\ndef generate_key(input_color):\n key = int(input_color[0]/32+1)*100 + int(input_color[1]/32+1)*10 + int(input_color[2]/32+1)\n return (key)\n\nwindow_size = 1024\nnum_iterations = 2\nvalid_input = False\ngrid_colors = []\n\nif __name__ == \"__main__\":\n if (len(sys.argv) == 2):\n training_image = sys.argv[1]\n\n im = Image.open(training_image)\n pix = im.load()\n\n rgb_values = []\n color_model = {}\n\n for x in range(im.size[0]):\n these_rgbs = []\n for y in range(im.size[1]):\n these_rgbs.append(pix[x,y])\n rgb_values.append(these_rgbs)\n\n for x in range(im.size[0] / 2):\n for y in range(im.size[1] / 2):\n rgb_mean = []\n rgb_mean.append(sum([rgb_values[x*2][y*2][0], rgb_values[x*2][y*2+1][0], rgb_values[x*2+1][y*2][0], rgb_values[x*2+1][y*2+1][0]]) / 4)\n rgb_mean.append(sum([rgb_values[x*2][y*2][1], rgb_values[x*2][y*2+1][1], rgb_values[x*2+1][y*2][1], rgb_values[x*2+1][y*2+1][1]]) / 4)\n rgb_mean.append(sum([rgb_values[x*2][y*2][2], rgb_values[x*2][y*2+1][2], rgb_values[x*2+1][y*2][2], rgb_values[x*2+1][y*2+1][2]]) / 4)\n\n rgb_std = []\n rgb_std.append(int(np.std([rgb_values[x*2][y*2][0], rgb_values[x*2][y*2+1][0], rgb_values[x*2+1][y*2][0], rgb_values[x*2+1][y*2+1][0]])))\n rgb_std.append(int(np.std([rgb_values[x*2][y*2][1], rgb_values[x*2][y*2+1][1], rgb_values[x*2+1][y*2][1], rgb_values[x*2+1][y*2+1][1]])))\n rgb_std.append(int(np.std([rgb_values[x*2][y*2][2], rgb_values[x*2][y*2+1][2], rgb_values[x*2+1][y*2][2], rgb_values[x*2+1][y*2+1][2]])))\n\n key = int(rgb_mean[0]/32+1)*100 + int(rgb_mean[1]/32+1)*10 + int(rgb_mean[2]/32+1)\n\n if (key not in color_model.keys()):\n color_model[key] = [rgb_std[0], rgb_std[1], rgb_std[2], 1]\n\n else:\n color_model[key] = [(color_model[key][0]*color_model[key][3]+rgb_std[0])/(color_model[key][3]+1), (color_model[key][1]*color_model[key][3]+rgb_std[1])/(color_model[key][3]+1), (color_model[key][2]*color_model[key][3]+rgb_std[2])/(color_model[key][3]+1), color_model[key][3]+1]\n\n for x in range(8):\n for y in range(8):\n for z in range(8):\n key = (x+1)*100 + (y+1)*10 + (z+1)\n if (key not in color_model.keys()):\n color_model[key] = [int(random.uniform(8, 15)), int(random.uniform(8, 15)), int(random.uniform(8, 15)), 1]\n if (color_model[key][0] < 6):\n color_model[key][0] = int(random.uniform(8, 15))\n if (color_model[key][1] < 6):\n color_model[key][1] = int(random.uniform(8, 15))\n if (color_model[key][2] < 6):\n color_model[key][2] = int(random.uniform(8, 15))\n\n valid_input = True\n\n if(valid_input):\n for i in range(im.size[0]):\n row_colors = []\n for j in range(im.size[1]):\n row_colors.append(pix[i,j])\n grid_colors.append(row_colors)\n\n for i in range(num_iterations):\n new_grid_colors = []\n grid_colors_list = []\n for j in range(len(grid_colors[0]) * 2):\n row_colors = []\n for k in range(len(grid_colors) * 2):\n row_colors.append(generate_color(generate_key(grid_colors[k/2][j/2]) ,grid_colors[k/2][j/2], i))\n grid_colors_list.append(generate_color(generate_key(grid_colors[k/2][j/2]) ,grid_colors[k/2][j/2], i))\n new_grid_colors.append(row_colors)\n grid_colors = new_grid_colors\n # img = Image.fromarray(grid_colors, 'RGB')\n im2 = Image.new('RGB',(len(grid_colors[0]),len(grid_colors)))\n im2.putdata(grid_colors_list)\n im2.save(\"up20.jpg\")\n" ]
[ [ "numpy.std", "numpy.random.normal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dominique120/12-steps-navier-stokes
[ "3e195bf7f7895f83f5f2248ef48dc13b76e8b5de" ]
[ "l3/plot.py" ]
[ "#!/usr/bin/env python\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nmatplotlib.rcParams[\"font.family\"] = \"Serif\"\nmatplotlib.rcParams[\"font.size\"] = 10\nmatplotlib.rcParams[\"axes.labelsize\"] = 10\nmatplotlib.rcParams[\"xtick.labelsize\"] = 10\nmatplotlib.rcParams[\"ytick.labelsize\"] = 10\nmatplotlib.rcParams[\"legend.fontsize\"] = 10\n\nfig = plt.figure(facecolor=\"white\")\nax = fig.gca()\nax.grid()\nax.set_axisbelow(True)\nax.set_xlabel(\"timestep\")\nax.set_title(\"Plot of u over time\")\n\nx = np.array([0.0000000000000000E+00,0.6283185482025147E-01,0.1256637096405029E+00,0.1884955644607544E+00,0.2513274192810059E+00,0.3141592741012573E+00,0.3769911289215088E+00,0.4398229837417603E+00,0.5026548385620118E+00,0.5654866933822632E+00,0.6283185482025146E+00,0.6911504030227662E+00,0.7539822578430176E+00,0.8168141126632691E+00,0.8796459674835206E+00,0.9424778223037721E+00,0.1005309677124024E+01,0.1068141531944275E+01,0.1130973386764526E+01,0.1193805241584778E+01,0.1256637096405029E+01,0.1319468951225281E+01,0.1382300806045532E+01,0.1445132660865784E+01,0.1507964515686035E+01,0.1570796370506287E+01,0.1633628225326538E+01,0.1696460080146790E+01,0.1759291934967041E+01,0.1822123789787293E+01,0.1884955644607544E+01,0.1947787499427795E+01,0.2010619354248047E+01,0.2073451209068299E+01,0.2136283063888550E+01,0.2199114918708801E+01,0.2261946773529053E+01,0.2324778628349304E+01,0.2387610483169556E+01,0.2450442337989807E+01,0.2513274192810059E+01,0.2576106047630310E+01,0.2638937902450562E+01,0.2701769757270813E+01,0.2764601612091065E+01,0.2827433466911316E+01,0.2890265321731567E+01,0.2953097176551819E+01,0.3015929031372071E+01,0.3078760886192322E+01,0.3141592741012574E+01,0.3204424595832825E+01,0.3267256450653076E+01,0.3330088305473328E+01,0.3392920160293579E+01,0.3455752015113831E+01,0.3518583869934083E+01,0.3581415724754334E+01,0.3644247579574585E+01,0.3707079434394837E+01,0.3769911289215088E+01,0.3832743144035340E+01,0.3895574998855591E+01,0.3958406853675843E+01,0.4021238708496094E+01,0.4084070563316345E+01,0.4146902418136597E+01,0.4209734272956848E+01,0.4272566127777100E+01,0.4335397982597351E+01,0.4398229837417603E+01,0.4461061692237855E+01,0.4523893547058106E+01,0.4586725401878358E+01,0.4649557256698609E+01,0.4712389111518860E+01,0.4775220966339112E+01,0.4838052821159363E+01,0.4900884675979615E+01,0.4963716530799866E+01,0.5026548385620117E+01,0.5089380240440369E+01,0.5152212095260620E+01,0.5215043950080872E+01,0.5277875804901123E+01,0.5340707659721375E+01,0.5403539514541627E+01,0.5466371369361878E+01,0.5529203224182130E+01,0.5592035079002381E+01,0.5654866933822633E+01,0.5717698788642884E+01,0.5780530643463135E+01,0.5843362498283387E+01,0.5906194353103638E+01,0.5969026207923890E+01,0.6031858062744141E+01,0.6094689917564392E+01,0.6157521772384644E+01,0.6220353627204895E+01,0.6283185482025147E+01])\ny = np.array([0.2727630972961541E+01,0.2771311269919911E+01,0.2814989285728558E+01,0.2858665849416731E+01,0.2902342189881139E+01,0.2946020124173951E+01,0.2989702300073073E+01,0.3033392493052979E+01,0.3077095949208672E+01,0.3120819754014078E+01,0.3164573192804217E+01,0.3208368054247055E+01,0.3252218815413303E+01,0.3296142639622408E+01,0.3340159119445302E+01,0.3384289709865549E+01,0.3428556821944811E+01,0.3472982584474947E+01,0.3517587326469731E+01,0.3562387880944926E+01,0.3607395852618360E+01,0.3652616021029425E+01,0.3698045059580436E+01,0.3743670736415854E+01,0.3789471724920397E+01,0.3835418093903271E+01,0.3881472477500543E+01,0.3927591851755142E+01,0.3973729778475908E+01,0.4019838926034867E+01,0.4065873647669411E+01,0.4111792394000463E+01,0.4157559757884302E+01,0.4203147993161763E+01,0.4248537908375252E+01,0.4293719104179188E+01,0.4338689590214909E+01,0.4383454875298046E+01,0.4428026667143412E+01,0.4472421340415166E+01,0.4516658333683488E+01,0.4560758619056785E+01,0.4604743357507668E+01,0.4648632814346878E+01,0.4692445569290600E+01,0.4736198019615245E+01,0.4779904146861352E+01,0.4823575499325555E+01,0.4867221334189969E+01,0.4910848863158982E+01,0.4954463551611633E+01,0.4998069430935068E+01,0.5041669394396616E+01,0.5085265456440628E+01,0.5128858961580264E+01,0.5172450729440230E+01,0.5216041112137861E+01,0.5259629908416969E+01,0.5303216001391483E+01,0.5346796407577470E+01,0.5390364016956128E+01,0.5433902378991060E+01,0.5477373796984951E+01,0.5520692266994955E+01,0.5563662148157763E+01,0.5605839543752792E+01,0.5646220063907935E+01,0.5682539434358074E+01,0.5709723746298654E+01,0.5716534126277256E+01,0.5678680622132141E+01,0.5546490436649654E+01,0.5230962954575717E+01,0.4621610920896421E+01,0.3723767827144663E+01,0.2832739161616575E+01,0.2256379481270987E+01,0.1991598349454642E+01,0.1903149542455375E+01,0.1893699549180197E+01,0.1916482260037323E+01,0.1951969308086713E+01,0.1992407559120753E+01,0.2034770635503815E+01,0.2077882429362218E+01,0.2121285847116006E+01,0.2164802982375364E+01,0.2208364483935747E+01,0.2251943284280958E+01,0.2295528801406756E+01,0.2339116851026652E+01,0.2382705607390911E+01,0.2426293674842139E+01,0.2469878109399315E+01,0.2513449360728478E+01,0.2556974307303974E+01,0.2600337207538654E+01,0.2643133334588122E+01,0.2683947826158554E+01,0.2717840319099818E+01,0.2727630972961541E+01])\n\nax.plot(x,y,\"b-o\",linewidth=1,markersize=3,label=\"value of u\")\n\nx = np.array([0.0000000000000000E+00,0.6283185482025147E-01,0.1256637096405029E+00,0.1884955644607544E+00,0.2513274192810059E+00,0.3141592741012573E+00,0.3769911289215088E+00,0.4398229837417603E+00,0.5026548385620118E+00,0.5654866933822632E+00,0.6283185482025146E+00,0.6911504030227662E+00,0.7539822578430176E+00,0.8168141126632691E+00,0.8796459674835206E+00,0.9424778223037721E+00,0.1005309677124024E+01,0.1068141531944275E+01,0.1130973386764526E+01,0.1193805241584778E+01,0.1256637096405029E+01,0.1319468951225281E+01,0.1382300806045532E+01,0.1445132660865784E+01,0.1507964515686035E+01,0.1570796370506287E+01,0.1633628225326538E+01,0.1696460080146790E+01,0.1759291934967041E+01,0.1822123789787293E+01,0.1884955644607544E+01,0.1947787499427795E+01,0.2010619354248047E+01,0.2073451209068299E+01,0.2136283063888550E+01,0.2199114918708801E+01,0.2261946773529053E+01,0.2324778628349304E+01,0.2387610483169556E+01,0.2450442337989807E+01,0.2513274192810059E+01,0.2576106047630310E+01,0.2638937902450562E+01,0.2701769757270813E+01,0.2764601612091065E+01,0.2827433466911316E+01,0.2890265321731567E+01,0.2953097176551819E+01,0.3015929031372071E+01,0.3078760886192322E+01,0.3141592741012574E+01,0.3204424595832825E+01,0.3267256450653076E+01,0.3330088305473328E+01,0.3392920160293579E+01,0.3455752015113831E+01,0.3518583869934083E+01,0.3581415724754334E+01,0.3644247579574585E+01,0.3707079434394837E+01,0.3769911289215088E+01,0.3832743144035340E+01,0.3895574998855591E+01,0.3958406853675843E+01,0.4021238708496094E+01,0.4084070563316345E+01,0.4146902418136597E+01,0.4209734272956848E+01,0.4272566127777100E+01,0.4335397982597351E+01,0.4398229837417603E+01,0.4461061692237855E+01,0.4523893547058106E+01,0.4586725401878358E+01,0.4649557256698609E+01,0.4712389111518860E+01,0.4775220966339112E+01,0.4838052821159363E+01,0.4900884675979615E+01,0.4963716530799866E+01,0.5026548385620117E+01,0.5089380240440369E+01,0.5152212095260620E+01,0.5215043950080872E+01,0.5277875804901123E+01,0.5340707659721375E+01,0.5403539514541627E+01,0.5466371369361878E+01,0.5529203224182130E+01,0.5592035079002381E+01,0.5654866933822633E+01,0.5717698788642884E+01,0.5780530643463135E+01,0.5843362498283387E+01,0.5906194353103638E+01,0.5969026207923890E+01,0.6031858062744141E+01,0.6094689917564392E+01,0.6157521772384644E+01,0.6220353627204895E+01,0.6283185482025147E+01])\ny = np.array([0.2736023075220947E+01,0.2779837164545836E+01,0.2823649045509257E+01,0.2867459600164973E+01,0.2911270141699394E+01,0.2955082615916199E+01,0.2998899859719867E+01,0.3042725915794919E+01,0.3086566393194455E+01,0.3130428850827616E+01,0.3174323165831663E+01,0.3218261833478449E+01,0.3262260132502555E+01,0.3306336083104996E+01,0.3350510127978347E+01,0.3394804482298916E+01,0.3439242127774091E+01,0.3483845467038330E+01,0.3528634703635678E+01,0.3573626062661065E+01,0.3618830009499543E+01,0.3664249650698246E+01,0.3709879505336173E+01,0.3755704814144340E+01,0.3801701508065813E+01,0.3847836893073130E+01,0.3894071032297831E+01,0.3940358730093159E+01,0.3986651955855555E+01,0.4032902497084348E+01,0.4079064607364045E+01,0.4125097418387960E+01,0.4170966914845689E+01,0.4216647322613483E+01,0.4262121827104219E+01,0.4307382610971990E+01,0.4352430269224261E+01,0.4397272716621099E+01,0.4441923740614247E+01,0.4486401369648815E+01,0.4530726221531711E+01,0.4574919973083936E+01,0.4619004056115172E+01,0.4662998642689007E+01,0.4706921941299771E+01,0.4750789790286371E+01,0.4794615508938744E+01,0.4838409951549534E+01,0.4882181704496955E+01,0.4925937369356523E+01,0.4969681883387789E+01,0.5013418839774710E+01,0.5057150781228563E+01,0.5100879449862473E+01,0.5144605981558732E+01,0.5188331031510512E+01,0.5232054803586364E+01,0.5275776916902560E+01,0.5319495949105908E+01,0.5363208279897092E+01,0.5406905366405161E+01,0.5450567464917623E+01,0.5494149280945163E+01,0.5537547298853238E+01,0.5580525607569766E+01,0.5622547965846030E+01,0.5662399018478118E+01,0.5697335399227216E+01,0.5721207407206272E+01,0.5720417383492038E+01,0.5665776539520547E+01,0.5498721631018602E+01,0.5119674798334109E+01,0.4425781384204654E+01,0.3486434650868969E+01,0.2650763109373032E+01,0.2160209517510828E+01,0.1951643566665702E+01,0.1890046900079447E+01,0.1891964276681970E+01,0.1919388886466590E+01,0.1956790527577951E+01,0.1998063161314609E+01,0.2040835692245308E+01,0.2084189902896408E+01,0.2127769988406669E+01,0.2171437866684961E+01,0.2215139874588584E+01,0.2258855136134518E+01,0.2302575516435228E+01,0.2346297799758990E+01,0.2390020545982250E+01,0.2433742519833124E+01,0.2477460863766740E+01,0.2521166124486849E+01,0.2564825375231745E+01,0.2608323275028774E+01,0.2651255604219204E+01,0.2692206176828820E+01,0.2726219167417408E+01,0.2736023075220947E+01])\n\nax.plot(x,y,\"b-o\",linewidth=1,markersize=3,label=\"value of un\")\n\nx = np.array([0.0000000000000000E+00,0.6283185482025147E-01,0.1256637096405029E+00,0.1884955644607544E+00,0.2513274192810059E+00,0.3141592741012573E+00,0.3769911289215088E+00,0.4398229837417603E+00,0.5026548385620118E+00,0.5654866933822632E+00,0.6283185482025146E+00,0.6911504030227662E+00,0.7539822578430176E+00,0.8168141126632691E+00,0.8796459674835206E+00,0.9424778223037721E+00,0.1005309677124024E+01,0.1068141531944275E+01,0.1130973386764526E+01,0.1193805241584778E+01,0.1256637096405029E+01,0.1319468951225281E+01,0.1382300806045532E+01,0.1445132660865784E+01,0.1507964515686035E+01,0.1570796370506287E+01,0.1633628225326538E+01,0.1696460080146790E+01,0.1759291934967041E+01,0.1822123789787293E+01,0.1884955644607544E+01,0.1947787499427795E+01,0.2010619354248047E+01,0.2073451209068299E+01,0.2136283063888550E+01,0.2199114918708801E+01,0.2261946773529053E+01,0.2324778628349304E+01,0.2387610483169556E+01,0.2450442337989807E+01,0.2513274192810059E+01,0.2576106047630310E+01,0.2638937902450562E+01,0.2701769757270813E+01,0.2764601612091065E+01,0.2827433466911316E+01,0.2890265321731567E+01,0.2953097176551819E+01,0.3015929031372071E+01,0.3078760886192322E+01,0.3141592741012574E+01,0.3204424595832825E+01,0.3267256450653076E+01,0.3330088305473328E+01,0.3392920160293579E+01,0.3455752015113831E+01,0.3518583869934083E+01,0.3581415724754334E+01,0.3644247579574585E+01,0.3707079434394837E+01,0.3769911289215088E+01,0.3832743144035340E+01,0.3895574998855591E+01,0.3958406853675843E+01,0.4021238708496094E+01,0.4084070563316345E+01,0.4146902418136597E+01,0.4209734272956848E+01,0.4272566127777100E+01,0.4335397982597351E+01,0.4398229837417603E+01,0.4461061692237855E+01,0.4523893547058106E+01,0.4586725401878358E+01,0.4649557256698609E+01,0.4712389111518860E+01,0.4775220966339112E+01,0.4838052821159363E+01,0.4900884675979615E+01,0.4963716530799866E+01,0.5026548385620117E+01,0.5089380240440369E+01,0.5152212095260620E+01,0.5215043950080872E+01,0.5277875804901123E+01,0.5340707659721375E+01,0.5403539514541627E+01,0.5466371369361878E+01,0.5529203224182130E+01,0.5592035079002381E+01,0.5654866933822633E+01,0.5717698788642884E+01,0.5780530643463135E+01,0.5843362498283387E+01,0.5906194353103638E+01,0.5969026207923890E+01,0.6031858062744141E+01,0.6094689917564392E+01,0.6157521772384644E+01,0.6220353627204895E+01,0.6283185482025147E+01])\ny = np.array([0.2778119282693222E+01,0.2821757879554102E+01,0.2865396476414983E+01,0.2909035073275863E+01,0.2952673670136744E+01,0.2996312266997624E+01,0.3039950863858505E+01,0.3083589460719385E+01,0.3127228057580266E+01,0.3170866654441146E+01,0.3214505251302026E+01,0.3258143848162907E+01,0.3301782445023787E+01,0.3345421041884667E+01,0.3389059638745548E+01,0.3432698235606428E+01,0.3476336832467309E+01,0.3519975429328189E+01,0.3563614026189069E+01,0.3607252623049950E+01,0.3650891219910831E+01,0.3694529816771711E+01,0.3738168413632591E+01,0.3781807010493472E+01,0.3825445607354352E+01,0.3869084204215233E+01,0.3912722801076113E+01,0.3956361397936993E+01,0.3999999994797874E+01,0.4043638591658754E+01,0.4087277188519635E+01,0.4130915785380515E+01,0.4174554382241396E+01,0.4218192979102276E+01,0.4261831575963156E+01,0.4305470172824037E+01,0.4349108769684917E+01,0.4392747366545797E+01,0.4436385963406678E+01,0.4480024560267559E+01,0.4523663157128439E+01,0.4567301753989319E+01,0.4610940350850200E+01,0.4654578947711080E+01,0.4698217544571961E+01,0.4741856141432841E+01,0.4785494738293721E+01,0.4829133335154602E+01,0.4872771932015482E+01,0.4916410528876363E+01,0.4960049125737243E+01,0.5003687722598123E+01,0.5047326319459004E+01,0.5090964916319884E+01,0.5134603513180765E+01,0.5178242110041645E+01,0.5221880706902526E+01,0.5265519303763406E+01,0.5309157900624286E+01,0.5352796497485167E+01,0.5396435094346045E+01,0.5440073691206913E+01,0.5483712288067701E+01,0.5527350884927927E+01,0.5570989481784174E+01,0.5614628078612207E+01,0.5658266675240245E+01,0.5701905270450581E+01,0.5745543855611327E+01,0.5789182369533984E+01,0.5832820378474495E+01,0.5876454807775165E+01,0.5920063862467133E+01,0.5963493056546985E+01,0.6005647845264028E+01,0.6038797098376929E+01,0.6009502348067070E+01,0.5598786339877734E+01,0.3999997337339063E+01,0.2401211415134112E+01,0.1990497346934744E+01,0.1961202951946962E+01,0.1994352257161830E+01,0.2036507053269433E+01,0.2079936248392683E+01,0.2123545303231861E+01,0.2167179732553298E+01,0.2210817741496738E+01,0.2254456255419809E+01,0.2298094840580612E+01,0.2341733435790958E+01,0.2385372032418996E+01,0.2429010629247029E+01,0.2472649226103276E+01,0.2516287822963503E+01,0.2559926419824292E+01,0.2603565016685159E+01,0.2647203613546037E+01,0.2690842210406918E+01,0.2734480807267798E+01,0.2778119404128678E+01])\n\nax.plot(x,y,\"b-o\",linewidth=1,markersize=3,label=\"value of u_analytical\")\n\nax.legend(loc=\"best\")\n\nplt.savefig(\"plot.png\", dpi=320)\n\n" ]
[ [ "numpy.array", "matplotlib.pyplot.savefig", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
romanbird/jeopardy-bot
[ "d47600d9261fefcb5f08d699ddf8b5fdcd072da1" ]
[ "assets/csv_counter.py" ]
[ "import csv\nimport pandas as pd\nfrom tqdm import tqdm\nfrom collections import Counter\ndbRead = open('db.csv', \"r\", newline='', encoding='utf8')\ndb = list(csv.reader(dbRead, delimiter=\",\"))\ncolumn = [row[-1] for row in db]\nfor row in tqdm(db):\n row[-2]=Counter(column)[row[-1]]\ndf=pd.DataFrame(data=db)\ndf.to_csv('db.csv', sep=\",\", encoding='utf8')" ]
[ [ "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": [] } ]
xumm94/2018_data_science_bowl
[ "9f7a6b60b7c1e933c30acd8abbdeeb7bd869a3f6" ]
[ "train_nuclei.py" ]
[ "# coding: utf-8\n\n\"\"\"\nMask R-CNN - Train on Nuclei Dataset (Updated from train_shape.ipynb)\n\nThis notebook shows how to train Mask R-CNN on your own dataset. \nTo keep things simple we use a synthetic dataset of shapes (squares, \ntriangles, and circles) which enables fast training. You'd still \nneed a GPU, though, because the network backbone is a Resnet101, \nwhich would be too slow to train on a CPU. On a GPU, you can start \nto get okay-ish results in a few minutes, and good results in less than an hour.\n\"\"\"\n\n\n\nimport os\nimport sys\nimport random\nimport math\nimport re\nimport time\nfrom tqdm import tqdm\nimport numpy as np\nimport pandas as pd\nimport cv2\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nfrom config import Config\nimport utils\nimport model as modellib\nimport visualize\nfrom model import log\nimport logging\nimport argparse\n\n\"\"\"\nConfigurations\n\nOverride form Config\n\"\"\"\n\nclass NucleiConfig(Config):\n \"\"\"Configuration for training on the toy shapes dataset.\n Derives from the base Config class and overrides values specific\n to the toy shapes dataset.\n \"\"\"\n # Give the configuration a recognizable name\n NAME = \"nuclei\"\n\n # Train on 1 GPU and 8 images per GPU. We can put multiple images on each\n # GPU because the images are small. Batch size is 8 (GPUs * images/GPU).\n GPU_COUNT = 2\n IMAGES_PER_GPU = 8\n\n # Number of classes (including background)\n NUM_CLASSES = 1 + 1 # background + 3 shapes\n\n # Use small images for faster training. Set the limits of the small side\n # the large side, and that determines the image shape.\n IMAGE_MIN_DIM = 512\n IMAGE_MAX_DIM = 512\n\n # Number of ROIs per image to feed to classifier/mask heads\n # The Mask RCNN paper uses 512 but often the RPN doesn't generate\n # enough positive proposals to fill this and keep a positive:negative\n # ratio of 1:3. You can increase the number of proposals by adjusting\n # the RPN NMS threshold.\n TRAIN_ROIS_PER_IMAGE = 300\n\n # Use smaller anchors because our image and objects are small\n RPN_ANCHOR_SCALES = (8, 16, 32, 64, 128) # anchor side in pixels\n\n # Reduce training ROIs per image because the images are small and have\n # few objects. Aim to allow ROI sampling to pick 33% positive ROIs.\n TRAIN_ROIS_PER_IMAGE = 32\n\n # Use a small epoch since the data is simple\n STEPS_PER_EPOCH = 50\n\n # use small validation steps since the epoch is small\n VALIDATION_STEPS = 5\n\n LEARNING_RATE = 0.001\n\n # Maximum number of ground truth instances to use in one image\n MAX_GT_INSTANCES = 200\n\n def display(self, logger):\n \"\"\"Display Configuration values.\"\"\"\n print(\"\\nConfigurations:\")\n logger.info('\\nConfigurations:')\n for a in dir(self):\n if not a.startswith(\"__\") and not callable(getattr(self, a)):\n print(\"{:30} {}\".format(a, getattr(self, a)))\n logger.info(\"{:30} {}\".format(a, getattr(self, a)))\n print(\"\\n\")\n\nclass NucleiDataset(utils.Dataset):\n\n \"\"\"Load the images and masks from dataset.\"\"\"\n\n def load_image_info(self, data_path, img_set = None):\n \"\"\"Get the picture names(ids) of the dataset.\"\"\"\n \n # Add classes\n self.add_class(\"nucleis\", 1, \"regular\")\n # TO DO : Three different image types into three classes\n \n # Add images\n # Get the images ids of training/testing set\n if img_set is None:\n train_ids = next(os.walk(data_path))[1]\n else:\n with open(img_set) as f:\n read_data = f.readlines()\n train_ids = [read_data[i][:-1] for i in range(0,len(read_data))] # Delete New line '\\n'\n # Get the info of the images\n for i, id_ in enumerate(train_ids):\n file_path = os.path.join(data_path, id_)\n img_path = os.path.join(file_path, \"images\")\n masks_path = os.path.join(file_path, \"masks\")\n img_name = id_ + \".png\"\n img = cv2.imread(os.path.join(img_path, img_name))\n width, height, _ = img.shape\n self.add_image(\"nucleis\", image_id=id_, path=file_path,\n img_path=img_path, masks_path=masks_path,\n width=width, height=height,\n nucleis=\"nucleis\") \n\n def load_image(self, image_id):\n \"\"\"Load image from file of the given image ID.\"\"\"\n info = self.image_info[image_id]\n img_path = info[\"img_path\"]\n img_name = info[\"id\"] + \".png\"\n image = cv2.imread(os.path.join(img_path, img_name))\n return image\n\n def image_reference(self, image_id):\n \"\"\"Return the path of the given image ID.\"\"\"\n info = self.image_info[image_id]\n if info[\"source\"] == \"nucleis\":\n return info[\"path\"]\n else:\n super(self.__class__).image_reference(self, image_id)\n\n def load_mask(self, image_id):\n \"\"\"Load the instance masks of the given image ID.\"\"\"\n info = self.image_info[image_id]\n mask_files = next(os.walk(info[\"masks_path\"]))[2]\n masks = np. zeros([info['width'], info['height'], len(mask_files)], dtype=np.uint8)\n for i, id_ in enumerate(mask_files):\n single_mask = cv2.imread(os.path.join(info[\"masks_path\"], id_), 0)\n masks[:, :, i:i+1] = single_mask[:, :, np.newaxis]\n class_ids = np.ones(len(mask_files))\n return masks, class_ids.astype(np.int32)\n\n # def test(self):\n # return \"1\"\n\ndef rle_encoding(x):\n dots = np.where(x.T.flatten() == 1)[0]\n run_lengths = []\n prev = -2\n for b in dots:\n if (b>prev+1): run_lengths.extend((b + 1, 0))\n run_lengths[-1] += 1\n prev = b\n return run_lengths\n\ndef parser_argument():\n # Parse command line arguments\n parser = argparse.ArgumentParser(\n description='Train Mask R-CNN on Nuclei Dataset.')\n parser.add_argument(\"command\",\n metavar=\"<command>\",\n help=\"'train' or 'evaluate' or predict\")\n parser.add_argument('--datapath',\n metavar=\"/path/to/data/\",\n default=\"./data\",\n help='Directory of the Nuclei dataset')\n parser.add_argument('--init_with',\n metavar=\"/init/type\",\n default=\"coco\",\n help=\"Initialize with the (\\\"coco\\\"/\\\"imagenet\\\"/\\\"last\\\") net\")\n parser.add_argument('--model',\n metavar=\"/path/to/weights.h5\",\n default=\"./models/mask_rcnn_coco.h5\",\n help=\"Path to weights .h5 file\")\n parser.add_argument('--ckpt',\n metavar=\"/path/to/save/checkpoint\",\n default=\"/data/lf/Nuclei/logs\",\n help=\"Directory of the checkpoint\")\n parser.add_argument('--epochs',\n metavar=\"/num/of/epochs\",\n default=\"50\",\n help=\"The number of the training epochs\")\n parser.add_argument('--finetune',\n metavar=\"/finetune/type\",\n default=\"heads\",\n help=\"The type of the finetune method(\\\"heads\\\" or \\\"all\\\")\")\n parser.add_argument('--lr_start',\n metavar=\"/value/of/start/lr\",\n default=\"0.001\",\n type=float,\n help=\"The Value of learning rate to start\")\n parser.add_argument('--train_dataset',\n metavar=\"train/imgs/names\",\n default=\"10-fold-train-1.txt\",\n help=\"The training set split of the data\")\n parser.add_argument('--val_dataset',\n metavar=\"val/imgs/names\",\n default=\"10-fold-val-1.txt\",\n help=\"The validation set split of the data\")\n\n return parser.parse_args()\n\nif __name__ == '__main__':\n \n args = parser_argument()\n logname = \"config-\" + time.strftime('%Y%m%d%H%M', time.localtime(time.time())) +\".log\"\n logging.basicConfig(filename=os.path.join(args.ckpt, logname), level=logging.INFO)\n logger = logging.getLogger('root')\n logger.info('\\nBasic Setting:')\n logger.info('\\nCommand: {} \\n Initialize: {} \\n Model: {} \\n Datapath: {} \\n Ckpt: {} \\n Epochs \\\n : {} \\n Finetune: {} \\n Train_dataset: {} \\n Val_dataset: {} \\n' \\\n .format(args.command, args.init_with, args.model, args.datapath, args.ckpt,\\\n args.epochs, args.finetune, args.train_dataset, args.val_dataset))\n\n # Train or evaluate or predict\n if args.command == \"train\":\n\n config = NucleiConfig()\n config.LEARNING_RATE = args.lr_start\n config.display(logger)\n model = modellib.MaskRCNN(mode=\"training\", config=config,\n model_dir=args.ckpt)\n \n # Select weights file to load\n print(\"Loading weights From \", args.model)\n\n if args.init_with == \"imagenet\":\n model.load_weights(model.get_imagenet_weights(), by_name=True)\n elif args.init_with == \"coco\":\n # Load weights trained on MS COCO, but skip layers that\n # are different due to the different number of classes\n # See README for instructions to download the COCO weights\n model.load_weights(args.model, by_name=True,\n exclude=[\"mrcnn_class_logits\", \"mrcnn_bbox_fc\", \n \"mrcnn_bbox\", \"mrcnn_mask\"])\n elif args.init_with == \"last\":\n # Load the last model you trained and continue training\n model.load_weights(args.model, by_name=True)\n\n # Training dataset. Use the training set and 35K from the\n # validation set, as as in the Mask RCNN paper.\n DATASET_DIR = os.path.join(args.datapath, \"stage1_train_fixed\")\n TRAIN_IMG_SET = os.path.join(args.datapath, \"stage1_train_fixed_10fold\", args.train_dataset)\n VAL_IMG_SET = os.path.join(args.datapath, \"stage1_train_fixed_10fold\", args.val_dataset)\n\n dataset_train = NucleiDataset()\n dataset_train.load_image_info(DATASET_DIR, TRAIN_IMG_SET)\n dataset_train.prepare()\n\n dataset_val = NucleiDataset()\n dataset_val.load_image_info(DATASET_DIR, VAL_IMG_SET)\n dataset_val.prepare()\n\n print(\"Loading {} training images, {} validation images\"\n .format(len(dataset_train.image_ids), len(dataset_val.image_ids)))\n\n\n if args.finetune == \"heads\":\n model.train(dataset_train, dataset_val, \n learning_rate=config.LEARNING_RATE, \n epochs=int(args.epochs), \n layers='heads',\n logger=logger)\n elif args.finetune == \"all\":\n model.train(dataset_train, dataset_val,\n learning_rate=config.LEARNING_RATE,\n epochs=int(args.epochs),\n layers='all',\n logger=logger)\n else: \n raise NameError(\"Only two finetune type is vaild(\\\"heads\\\" or \\\"all\\\")\")\n\n\n elif args.command == \"evaluate\": \n # TODO AP in [0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95]\n class InferenceConfig(NucleiConfig):\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_MAX_INSTANCES = 300\n config = InferenceConfig()\n config.display()\n\n model = modellib.MaskRCNN(mode=\"inference\", config=config,\n model_dir=args.ckpt)\n\n print(\"Loading weights From \", args.model)\n model.load_weights(args.model, by_name=True)\n\n VALSET_DIR = os.path.join(args.dataset, \"stage1_val\")\n dataset_val = NucleiDataset()\n dataset_val.load_image_info(VALSET_DIR)\n dataset_val.prepare()\n print(\"Evaluate {} images\".format(len(dataset_val.image_ids)))\n\n APs = []\n\n for image_id in tqdm(dataset_val.image_ids):\n # Load image and ground truth data\n image, image_meta, gt_class_id, gt_bbox, gt_mask =modellib.load_image_gt(\n dataset_val, InferenceConfig, image_id, use_mini_mask=False)\n molded_images = np.expand_dims(modellib.mold_image(image, config), 0)\n\n # Run object detection\n results = model.detect([image], verbose=0)\n r = results[0]\n\n # Compute AP\n AP, precisions, recalls, overlaps =utils.compute_ap(gt_bbox, \n gt_class_id,r[\"rois\"], r[\"class_ids\"], r[\"scores\"], iou_threshold=0.5)\n APs.append(AP)\n\n print(\"mAP: \", np.mean(APs))\n\n elif args.command == \"predict\":\n\n class InferenceConfig(NucleiConfig):\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_NMS_THRESHOLD = 0.3\n DETECTION_MAX_INSTANCES = 300\n\n config = InferenceConfig()\n config.display()\n\n model = modellib.MaskRCNN(mode=\"inference\", config=config,\n model_dir=args.ckpt)\n\n print(\"Loading weights From \", args.model)\n model.load_weights(args.model, by_name=True)\n\n TESTSET_DIR = os.path.join(args.dataset, \"stage1_test\")\n dataset_test = NucleiDataset()\n dataset_test.load_image_info(TESTSET_DIR)\n dataset_test.prepare()\n\n print(\"Predict {} images\".format(dataset_test.num_images))\n\n test_ids = []\n test_rles = []\n\n for image_id in tqdm(dataset_test.image_ids):\n image = dataset_test.load_image(image_id)\n id_ = dataset_test.image_info[image_id][\"id\"]\n results = model.detect([image], verbose=0)\n r = results[0]\n mask_exist = np.zeros(r['masks'].shape[:-1], dtype=np.uint8)\n for i in range(r['masks'].shape[-1]):\n _mask = r['masks'][:,:,i]\n overlap_index = np.where(np.multiply(mask_exist, _mask) == 1)\n _mask[overlap_index] = 0\n mask_exist += _mask\n if np.any(_mask):\n test_ids.append(id_)\n test_rles.append(rle_encoding(_mask))\n else :\n continue\n # if np.count_nonzero(_mask) > 40 :\n # test_ids.append(id_)\n # test_rles.append(rle_encoding(_mask))\n # else :\n # continue\n\n sub = pd.DataFrame()\n sub['ImageId'] = test_ids\n sub['EncodedPixels'] = pd.Series(test_rles).apply(lambda x: ' '.join(str(y) for y in x))\n csvpath = \"{}.csv\".format(args.model)\n print(\"Writing the Result in {}\".format(csvpath))\n sub.to_csv(csvpath, index=False)\n\n else:\n print(\"'{}' is not recognized. Use 'train' 'evaluate' 'predict'\".format(args.command))\n\n\n" ]
[ [ "pandas.Series", "numpy.multiply", "pandas.DataFrame", "numpy.mean", "numpy.any", "numpy.zeros" ] ]
[ { "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": [] } ]
mitenjain/protpore
[ "06b779473c4bf9f9c8c4305aa08873ae75386886" ]
[ "proteinhmmvisualize.py" ]
[ "'''\r\nAuthor: Hannah Meyers\r\n\r\nThis file contains the experiment code for attempting to model\r\nprotein nanopore traces via HMMs. Please see inline comments\r\nfor an explanation of what each piece of the code is doing.\r\n'''\r\nfrom __future__ import print_function\r\n\r\nfrom PyPore.parsers import *\r\nfrom PyPore.DataTypes import *\r\nfrom hmm import *\r\nfrom yahmm import *\r\n\r\nimport math\r\nimport matplotlib.pyplot as plt\r\nimport itertools as it\r\nimport glob\r\nimport seaborn as sns\r\nimport sys\r\nimport pandas as pd\r\nfrom proteinDists import *\r\nfrom scipy.stats import kde\r\n\r\n\r\n\r\n#Experiment data files. The first set before the break are all experiment files from\r\n#the same day of data collection. Files after the break are each from different days.\r\nfilenames = [\r\n\r\n#\"ProteinFiles/12907001-s05.abf\"\r\n#\"ProteinFiles/13311001-s05.abf\"\r\n\"experiment_data/13n25010-s05.abf\",\r\n#\"experiment_data/13n25001-s05.abf\",\r\n#\"experiment_data/13n25005-s05.abf\",\r\n#\"experiment_data/13n25007-s05.abf\",\r\n#\"experiment_data/13n25012-s05.abf\",#bad\r\n#----#\r\n#\"experiment_data/13n12001-s05.abf\",\r\n#\"experiment_data/13n13006-s05.abf\",\r\n#\"experiment_data/14131001-s05.abf\",\r\n#---#\r\n#\"experiment_data/14410016-s05.abf\"\r\n] \r\n\r\n#Inserts are uniform across the range of current we expect to see in an event\r\ninsert1 = MultivariateDistribution( [ UniformDistribution( 0, 40 ), UniformDistribution( 0, 10 ) ] )\r\n\r\n#Create first local model\r\nprofile_means = pd.read_csv( 'profile_data/profilemeans.csv' )\r\nprofile_stds = pd.read_csv( 'profile_data/profilestds.csv' )\r\n\r\n#Convert CSV data to distribution objects\r\ndists_means = [ NormalDistribution( profile_means[col].mean(), profile_means[col].std() ) for col in profile_means ] \r\ndists_stds = [ LogNormalDistribution( np.log( profile_stds[col] ).mean(), np.log( profile_stds[col] ).std() ) for col in profile_stds ]\r\n\r\n\r\n#build multivariate profile with distributions of means/std deviations\r\nprofile = [ MultivariateDistribution([ mean, std ]) for mean, std in it.izip( dists_means, dists_stds ) ]\r\n#profile[5] = MultivariateDistribution([ ExtremeValueDistribution( 20, 10 ), LogNormalDistribution( np.log(4.5), np.log(3.5) ) ])\r\n\r\n#print(profile[5])\r\n\r\n#list of board functions corresponds to the 11 profile positions\r\nboardlist = [ProteinDomainBoard2]*2 +[ProteinDomainBoard]*9\r\n\r\n#build model\r\nmodel = ModularDomainProfileModel2( boardlist, profile, \"ClpXProfile-{}\".format( len(profile) ), insert1)\r\n\r\n\r\n\r\n#iteration for applying model to events in filenames list and plotting\r\nfor file in it.imap( File, filenames ):\r\n x = 1\r\n \r\n print(file.filename)\r\n #Events must drop below this threshold\r\n threshold = 38\r\n rules = [lambda event: event.duration > 1000000,\r\n lambda event: event.min > -5,\r\n lambda event: event.max < threshold]\r\n \r\n file.parse( lambda_event_parser( threshold=threshold, rules = rules ) )\r\n \r\n for event in file.events:\r\n event.filter()\r\n \r\n print(event)\r\n #false_positive_rate controls the number of segments that will be created by the segmenter\r\n event.parse( SpeedyStatSplit( min_width=5, false_positive_rate=1e-65, cutoff_freq = 2000) )\r\n \r\n #print(event.segments)\r\n \r\n \r\n #Apply HMM to event\r\n _, hidden_states = model.viterbi( np.array( [[ seg.mean, seg.std] for seg in event.segments ] ) )\r\n if hidden_states != None:\r\n \r\n #First subplot is event + segmentation\r\n plt.figure( figsize=(20, 8))\r\n plt.subplot( 311 )\r\n event.plot( color='cycle' )\r\n\r\n #Second subplot is event + HMM\r\n plt.subplot( 312 )\r\n event.plot( color='hmm', hmm=model, hidden_states=hidden_states, cmap='Set1' )\r\n\r\n #Final subplot is color cycle with profile means\r\n #this subplot is currently inaccurate as it only plots the first profile\r\n #furthermore, there was a bug in PyPore when I started on this that makes the color cycle\r\n #not match up to the HMM colors. I am unsure if the bug has been fixed since then.\r\n ax = plt.subplot( 313 )\r\n plt.imshow( [ np.arange( 0., len(profile) ) / len(profile) ], interpolation='nearest', cmap=\"Set1\" )\r\n plt.grid( False )\r\n means = [ d.parameters[0][0].parameters[0] for d in profile ]\r\n for i, mean in enumerate( means ):\r\n plt.text( i-0.2, 0.1, str( round(mean, 1) ), fontsize=12 )\r\n \r\n #Output HMM state path to output.txt file\r\n outputtext = 'output' + str(x) + '.txt'\r\n f = open(outputtext, 'w')\r\n for i, state in enumerate( hidden_states ):\r\n f.write(state[1].name+\"\\n\")\r\n f.close()\r\n \r\n #s = file.filename[16:] +'fp55s' + str(x)\r\n s = 'backslip' + str(x)\r\n #save figure with name s + counter to prevent name duplications\r\n plt.savefig(s)\r\n x += 1\r\n \r\n #show figure\r\n #plt.show()\r\n file.close()\r\n" ]
[ [ "pandas.read_csv", "matplotlib.pyplot.savefig", "matplotlib.pyplot.subplot", "matplotlib.pyplot.grid", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
cloudscenes/geopandas
[ "409d8f0a1562df088ce28c39a48fe4df669660fe" ]
[ "geopandas/tools/tests/test_clip.py" ]
[ "\"\"\"Tests for the clip module.\"\"\"\n\nimport warnings\nfrom distutils.version import LooseVersion\n\nimport numpy as np\nimport pandas as pd\n\nimport shapely\nfrom shapely.geometry import (\n Polygon,\n Point,\n LineString,\n LinearRing,\n GeometryCollection,\n MultiPoint,\n)\n\nimport geopandas\nfrom geopandas import GeoDataFrame, GeoSeries, clip\n\nfrom geopandas.testing import assert_geodataframe_equal, assert_geoseries_equal\nimport pytest\n\n\npytestmark = pytest.mark.skip_no_sindex\npandas_133 = pd.__version__ == LooseVersion(\"1.3.3\")\n\n\[email protected]\ndef point_gdf():\n \"\"\"Create a point GeoDataFrame.\"\"\"\n pts = np.array([[2, 2], [3, 4], [9, 8], [-12, -15]])\n gdf = GeoDataFrame([Point(xy) for xy in pts], columns=[\"geometry\"], crs=\"EPSG:3857\")\n return gdf\n\n\[email protected]\ndef pointsoutside_nooverlap_gdf():\n \"\"\"Create a point GeoDataFrame. Its points are all outside the single\n rectangle, and its bounds are outside the single rectangle's.\"\"\"\n pts = np.array([[5, 15], [15, 15], [15, 20]])\n gdf = GeoDataFrame([Point(xy) for xy in pts], columns=[\"geometry\"], crs=\"EPSG:3857\")\n return gdf\n\n\[email protected]\ndef pointsoutside_overlap_gdf():\n \"\"\"Create a point GeoDataFrame. Its points are all outside the single\n rectangle, and its bounds are overlapping the single rectangle's.\"\"\"\n pts = np.array([[5, 15], [15, 15], [15, 5]])\n gdf = GeoDataFrame([Point(xy) for xy in pts], columns=[\"geometry\"], crs=\"EPSG:3857\")\n return gdf\n\n\[email protected]\ndef single_rectangle_gdf():\n \"\"\"Create a single rectangle for clipping.\"\"\"\n poly_inters = Polygon([(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)])\n gdf = GeoDataFrame([1], geometry=[poly_inters], crs=\"EPSG:3857\")\n gdf[\"attr2\"] = \"site-boundary\"\n return gdf\n\n\[email protected]\ndef larger_single_rectangle_gdf():\n \"\"\"Create a slightly larger rectangle for clipping.\n The smaller single rectangle is used to test the edge case where slivers\n are returned when you clip polygons. This fixture is larger which\n eliminates the slivers in the clip return.\n \"\"\"\n poly_inters = Polygon([(-5, -5), (-5, 15), (15, 15), (15, -5), (-5, -5)])\n gdf = GeoDataFrame([1], geometry=[poly_inters], crs=\"EPSG:3857\")\n gdf[\"attr2\"] = [\"study area\"]\n return gdf\n\n\[email protected]\ndef buffered_locations(point_gdf):\n \"\"\"Buffer points to create a multi-polygon.\"\"\"\n buffered_locs = point_gdf\n buffered_locs[\"geometry\"] = buffered_locs.buffer(4)\n buffered_locs[\"type\"] = \"plot\"\n return buffered_locs\n\n\[email protected]\ndef donut_geometry(buffered_locations, single_rectangle_gdf):\n \"\"\"Make a geometry with a hole in the middle (a donut).\"\"\"\n donut = geopandas.overlay(\n buffered_locations, single_rectangle_gdf, how=\"symmetric_difference\"\n )\n return donut\n\n\[email protected]\ndef two_line_gdf():\n \"\"\"Create Line Objects For Testing\"\"\"\n linea = LineString([(1, 1), (2, 2), (3, 2), (5, 3)])\n lineb = LineString([(3, 4), (5, 7), (12, 2), (10, 5), (9, 7.5)])\n gdf = GeoDataFrame([1, 2], geometry=[linea, lineb], crs=\"EPSG:3857\")\n return gdf\n\n\[email protected]\ndef multi_poly_gdf(donut_geometry):\n \"\"\"Create a multi-polygon GeoDataFrame.\"\"\"\n multi_poly = donut_geometry.unary_union\n out_df = GeoDataFrame(geometry=GeoSeries(multi_poly), crs=\"EPSG:3857\")\n out_df[\"attr\"] = [\"pool\"]\n return out_df\n\n\[email protected]\ndef multi_line(two_line_gdf):\n \"\"\"Create a multi-line GeoDataFrame.\n This GDF has one multiline and one regular line.\"\"\"\n # Create a single and multi line object\n multiline_feat = two_line_gdf.unary_union\n linec = LineString([(2, 1), (3, 1), (4, 1), (5, 2)])\n out_df = GeoDataFrame(geometry=GeoSeries([multiline_feat, linec]), crs=\"EPSG:3857\")\n out_df[\"attr\"] = [\"road\", \"stream\"]\n return out_df\n\n\[email protected]\ndef multi_point(point_gdf):\n \"\"\"Create a multi-point GeoDataFrame.\"\"\"\n multi_point = point_gdf.unary_union\n out_df = GeoDataFrame(\n geometry=GeoSeries(\n [multi_point, Point(2, 5), Point(-11, -14), Point(-10, -12)]\n ),\n crs=\"EPSG:3857\",\n )\n out_df[\"attr\"] = [\"tree\", \"another tree\", \"shrub\", \"berries\"]\n return out_df\n\n\[email protected]\ndef mixed_gdf():\n \"\"\"Create a Mixed Polygon and LineString For Testing\"\"\"\n point = Point([(2, 3), (11, 4), (7, 2), (8, 9), (1, 13)])\n line = LineString([(1, 1), (2, 2), (3, 2), (5, 3), (12, 1)])\n poly = Polygon([(3, 4), (5, 2), (12, 2), (10, 5), (9, 7.5)])\n ring = LinearRing([(1, 1), (2, 2), (3, 2), (5, 3), (12, 1)])\n gdf = GeoDataFrame(\n [1, 2, 3, 4], geometry=[point, poly, line, ring], crs=\"EPSG:3857\"\n )\n return gdf\n\n\[email protected]\ndef geomcol_gdf():\n \"\"\"Create a Mixed Polygon and LineString For Testing\"\"\"\n point = Point([(2, 3), (11, 4), (7, 2), (8, 9), (1, 13)])\n poly = Polygon([(3, 4), (5, 2), (12, 2), (10, 5), (9, 7.5)])\n coll = GeometryCollection([point, poly])\n gdf = GeoDataFrame([1], geometry=[coll], crs=\"EPSG:3857\")\n return gdf\n\n\[email protected]\ndef sliver_line():\n \"\"\"Create a line that will create a point when clipped.\"\"\"\n linea = LineString([(10, 5), (13, 5), (15, 5)])\n lineb = LineString([(1, 1), (2, 2), (3, 2), (5, 3), (12, 1)])\n gdf = GeoDataFrame([1, 2], geometry=[linea, lineb], crs=\"EPSG:3857\")\n return gdf\n\n\ndef test_not_gdf(single_rectangle_gdf):\n \"\"\"Non-GeoDataFrame inputs raise attribute errors.\"\"\"\n with pytest.raises(TypeError):\n clip((2, 3), single_rectangle_gdf)\n with pytest.raises(TypeError):\n clip(single_rectangle_gdf, (2, 3))\n\n\ndef test_returns_gdf(point_gdf, single_rectangle_gdf):\n \"\"\"Test that function returns a GeoDataFrame (or GDF-like) object.\"\"\"\n out = clip(point_gdf, single_rectangle_gdf)\n assert isinstance(out, GeoDataFrame)\n\n\ndef test_returns_series(point_gdf, single_rectangle_gdf):\n \"\"\"Test that function returns a GeoSeries if GeoSeries is passed.\"\"\"\n out = clip(point_gdf.geometry, single_rectangle_gdf)\n assert isinstance(out, GeoSeries)\n\n\ndef test_non_overlapping_geoms():\n \"\"\"Test that a bounding box returns empty if the extents don't overlap\"\"\"\n unit_box = Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)])\n unit_gdf = GeoDataFrame([1], geometry=[unit_box], crs=\"EPSG:3857\")\n non_overlapping_gdf = unit_gdf.copy()\n non_overlapping_gdf = non_overlapping_gdf.geometry.apply(\n lambda x: shapely.affinity.translate(x, xoff=20)\n )\n out = clip(unit_gdf, non_overlapping_gdf)\n assert_geodataframe_equal(out, unit_gdf.iloc[:0])\n out2 = clip(unit_gdf.geometry, non_overlapping_gdf)\n assert_geoseries_equal(out2, GeoSeries(crs=unit_gdf.crs))\n\n\ndef test_clip_points(point_gdf, single_rectangle_gdf):\n \"\"\"Test clipping a points GDF with a generic polygon geometry.\"\"\"\n clip_pts = clip(point_gdf, single_rectangle_gdf)\n pts = np.array([[2, 2], [3, 4], [9, 8]])\n exp = GeoDataFrame([Point(xy) for xy in pts], columns=[\"geometry\"], crs=\"EPSG:3857\")\n assert_geodataframe_equal(clip_pts, exp)\n\n\ndef test_clip_points_geom_col_rename(point_gdf, single_rectangle_gdf):\n \"\"\"Test clipping a points GDF with a generic polygon geometry.\"\"\"\n point_gdf_geom_col_rename = point_gdf.rename_geometry(\"geometry2\")\n clip_pts = clip(point_gdf_geom_col_rename, single_rectangle_gdf)\n pts = np.array([[2, 2], [3, 4], [9, 8]])\n exp = GeoDataFrame(\n [Point(xy) for xy in pts],\n columns=[\"geometry2\"],\n crs=\"EPSG:3857\",\n geometry=\"geometry2\",\n )\n assert_geodataframe_equal(clip_pts, exp)\n\n\ndef test_clip_poly(buffered_locations, single_rectangle_gdf):\n \"\"\"Test clipping a polygon GDF with a generic polygon geometry.\"\"\"\n clipped_poly = clip(buffered_locations, single_rectangle_gdf)\n assert len(clipped_poly.geometry) == 3\n assert all(clipped_poly.geom_type == \"Polygon\")\n\n\ndef test_clip_poly_geom_col_rename(buffered_locations, single_rectangle_gdf):\n \"\"\"Test clipping a polygon GDF with a generic polygon geometry.\"\"\"\n\n poly_gdf_geom_col_rename = buffered_locations.rename_geometry(\"geometry2\")\n clipped_poly = clip(poly_gdf_geom_col_rename, single_rectangle_gdf)\n assert len(clipped_poly.geometry) == 3\n assert \"geometry\" not in clipped_poly.keys()\n assert \"geometry2\" in clipped_poly.keys()\n\n\ndef test_clip_poly_series(buffered_locations, single_rectangle_gdf):\n \"\"\"Test clipping a polygon GDF with a generic polygon geometry.\"\"\"\n clipped_poly = clip(buffered_locations.geometry, single_rectangle_gdf)\n assert len(clipped_poly) == 3\n assert all(clipped_poly.geom_type == \"Polygon\")\n\n\[email protected](pandas_133, reason=\"Regression in pandas 1.3.3 (GH #2101)\")\ndef test_clip_multipoly_keep_slivers(multi_poly_gdf, single_rectangle_gdf):\n \"\"\"Test a multi poly object where the return includes a sliver.\n Also the bounds of the object should == the bounds of the clip object\n if they fully overlap (as they do in these fixtures).\"\"\"\n clipped = clip(multi_poly_gdf, single_rectangle_gdf)\n assert np.array_equal(clipped.total_bounds, single_rectangle_gdf.total_bounds)\n # Assert returned data is a geometry collection given sliver geoms\n assert \"GeometryCollection\" in clipped.geom_type[0]\n\n\[email protected](pandas_133, reason=\"Regression in pandas 1.3.3 (GH #2101)\")\ndef test_clip_multipoly_keep_geom_type(multi_poly_gdf, single_rectangle_gdf):\n \"\"\"Test a multi poly object where the return includes a sliver.\n Also the bounds of the object should == the bounds of the clip object\n if they fully overlap (as they do in these fixtures).\"\"\"\n clipped = clip(multi_poly_gdf, single_rectangle_gdf, keep_geom_type=True)\n assert np.array_equal(clipped.total_bounds, single_rectangle_gdf.total_bounds)\n # Assert returned data is a not geometry collection\n assert (clipped.geom_type == \"Polygon\").any()\n\n\ndef test_clip_single_multipoly_no_extra_geoms(\n buffered_locations, larger_single_rectangle_gdf\n):\n \"\"\"When clipping a multi-polygon feature, no additional geom types\n should be returned.\"\"\"\n multi = buffered_locations.dissolve(by=\"type\").reset_index()\n clipped = clip(multi, larger_single_rectangle_gdf)\n assert clipped.geom_type[0] == \"Polygon\"\n\n\ndef test_clip_multiline(multi_line, single_rectangle_gdf):\n \"\"\"Test that clipping a multiline feature with a poly returns expected output.\"\"\"\n clipped = clip(multi_line, single_rectangle_gdf)\n assert clipped.geom_type[0] == \"MultiLineString\"\n\n\ndef test_clip_multipoint(single_rectangle_gdf, multi_point):\n \"\"\"Clipping a multipoint feature with a polygon works as expected.\n should return a geodataframe with a single multi point feature\"\"\"\n clipped = clip(multi_point, single_rectangle_gdf)\n assert clipped.geom_type[0] == \"MultiPoint\"\n assert hasattr(clipped, \"attr\")\n # All points should intersect the clip geom\n assert len(clipped) == 2\n clipped_mutltipoint = MultiPoint(\n [\n Point(2, 2),\n Point(3, 4),\n Point(9, 8),\n ]\n )\n assert clipped.iloc[0].geometry.wkt == clipped_mutltipoint.wkt\n assert all(clipped.intersects(single_rectangle_gdf.unary_union))\n\n\ndef test_clip_lines(two_line_gdf, single_rectangle_gdf):\n \"\"\"Test what happens when you give the clip_extent a line GDF.\"\"\"\n clip_line = clip(two_line_gdf, single_rectangle_gdf)\n assert len(clip_line.geometry) == 2\n\n\ndef test_clip_with_multipolygon(buffered_locations, single_rectangle_gdf):\n \"\"\"Test clipping a polygon with a multipolygon.\"\"\"\n multi = buffered_locations.dissolve(by=\"type\").reset_index()\n clipped = clip(single_rectangle_gdf, multi)\n assert clipped.geom_type[0] == \"Polygon\"\n\n\ndef test_mixed_geom(mixed_gdf, single_rectangle_gdf):\n \"\"\"Test clipping a mixed GeoDataFrame\"\"\"\n clipped = clip(mixed_gdf, single_rectangle_gdf)\n assert (\n clipped.geom_type[0] == \"Point\"\n and clipped.geom_type[1] == \"Polygon\"\n and clipped.geom_type[2] == \"LineString\"\n )\n\n\ndef test_mixed_series(mixed_gdf, single_rectangle_gdf):\n \"\"\"Test clipping a mixed GeoSeries\"\"\"\n clipped = clip(mixed_gdf.geometry, single_rectangle_gdf)\n assert (\n clipped.geom_type[0] == \"Point\"\n and clipped.geom_type[1] == \"Polygon\"\n and clipped.geom_type[2] == \"LineString\"\n )\n\n\ndef test_clip_warning_no_extra_geoms(buffered_locations, single_rectangle_gdf):\n \"\"\"Test a user warning is provided if no new geometry types are found.\"\"\"\n with pytest.warns(UserWarning):\n clip(buffered_locations, single_rectangle_gdf, True)\n warnings.warn(\n \"keep_geom_type was called when no extra geometry types existed.\",\n UserWarning,\n )\n\n\ndef test_clip_with_polygon(single_rectangle_gdf):\n \"\"\"Test clip when using a shapely object\"\"\"\n polygon = Polygon([(0, 0), (5, 12), (10, 0), (0, 0)])\n clipped = clip(single_rectangle_gdf, polygon)\n exp_poly = polygon.intersection(\n Polygon([(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)])\n )\n exp = GeoDataFrame([1], geometry=[exp_poly], crs=\"EPSG:3857\")\n exp[\"attr2\"] = \"site-boundary\"\n assert_geodataframe_equal(clipped, exp)\n\n\ndef test_clip_with_line_extra_geom(single_rectangle_gdf, sliver_line):\n \"\"\"When the output of a clipped line returns a geom collection,\n and keep_geom_type is True, no geometry collections should be returned.\"\"\"\n clipped = clip(sliver_line, single_rectangle_gdf, keep_geom_type=True)\n assert len(clipped.geometry) == 1\n # Assert returned data is a not geometry collection\n assert not (clipped.geom_type == \"GeometryCollection\").any()\n\n\ndef test_clip_line_keep_slivers(single_rectangle_gdf, sliver_line):\n \"\"\"Test the correct output if a point is returned\n from a line only geometry type.\"\"\"\n clipped = clip(sliver_line, single_rectangle_gdf)\n # Assert returned data is a geometry collection given sliver geoms\n assert \"Point\" == clipped.geom_type[0]\n assert \"LineString\" == clipped.geom_type[1]\n\n\ndef test_clip_no_box_overlap(pointsoutside_nooverlap_gdf, single_rectangle_gdf):\n \"\"\"Test clip when intersection is empty and boxes do not overlap.\"\"\"\n clipped = clip(pointsoutside_nooverlap_gdf, single_rectangle_gdf)\n assert len(clipped) == 0\n\n\ndef test_clip_box_overlap(pointsoutside_overlap_gdf, single_rectangle_gdf):\n \"\"\"Test clip when intersection is empty and boxes do overlap.\"\"\"\n clipped = clip(pointsoutside_overlap_gdf, single_rectangle_gdf)\n assert len(clipped) == 0\n\n\ndef test_warning_extra_geoms_mixed(single_rectangle_gdf, mixed_gdf):\n \"\"\"Test the correct warnings are raised if keep_geom_type is\n called on a mixed GDF\"\"\"\n with pytest.warns(UserWarning):\n clip(mixed_gdf, single_rectangle_gdf, keep_geom_type=True)\n\n\ndef test_warning_geomcoll(single_rectangle_gdf, geomcol_gdf):\n \"\"\"Test the correct warnings are raised if keep_geom_type is\n called on a GDF with GeometryCollection\"\"\"\n with pytest.warns(UserWarning):\n clip(geomcol_gdf, single_rectangle_gdf, keep_geom_type=True)\n\n\ndef test_warning_crs_mismatch(point_gdf, single_rectangle_gdf):\n with pytest.warns(UserWarning, match=\"CRS mismatch between the CRS\"):\n clip(point_gdf, single_rectangle_gdf.to_crs(4326))\n" ]
[ [ "numpy.array", "numpy.array_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mendelmaker/yolact
[ "83e7d08f03951c49a9731759e8458c51fe0922d7" ]
[ "eval.py" ]
[ "import json\nimport numpy as np\nimport torch\nimport pycocotools\nimport argparse\nfrom pycocotools.coco import COCO\nfrom pycocotools.cocoeval import COCOeval\nfrom terminaltables import AsciiTable\nfrom collections import OrderedDict\nimport torch.backends.cudnn as cudnn\n\nfrom data.coco import COCODetection\nfrom modules.build_yolact import Yolact\nfrom utils.augmentations import BaseTransform\nfrom utils.functions import MovingAverage, ProgressBar\nfrom utils.box_utils import bbox_iou, mask_iou\nfrom utils import timer\nfrom utils.output_utils import after_nms, NMS\nfrom data.config import cfg, update_config, COCO_LABEL_MAP\n\nparser = argparse.ArgumentParser(description='YOLACT COCO Evaluation')\nparser.add_argument('--trained_model', default='yolact_base_54_800000.pth', type=str)\nparser.add_argument('--visual_top_k', default=5, type=int, help='Further restrict the number of predictions to parse')\nparser.add_argument('--traditional_nms', default=False, action='store_true', help='Whether to use traditional nms.')\nparser.add_argument('--max_num', default=-1, type=int, help='The maximum number of images for test, set to -1 for all.')\nparser.add_argument('--cocoapi', action='store_true', help='Whether to use cocoapi to evaluate results.')\n\n\nclass Make_json:\n def __init__(self):\n self.bbox_data = []\n self.mask_data = []\n self.coco_cats = {}\n\n for coco_id, real_id in COCO_LABEL_MAP.items():\n class_id = real_id - 1\n self.coco_cats[class_id] = coco_id\n\n def add_bbox(self, image_id: int, category_id: int, bbox: list, score: float):\n \"\"\" Note that bbox should be a list or tuple of (x1, y1, x2, y2) \"\"\"\n bbox = [bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]]\n\n # Round to the nearest 10th to avoid huge file sizes, as COCO suggests\n bbox = [round(float(x) * 10) / 10 for x in bbox]\n\n self.bbox_data.append({'image_id': int(image_id),\n 'category_id': self.coco_cats[int(category_id)],\n 'bbox': bbox,\n 'score': float(score)})\n\n def add_mask(self, image_id: int, category_id: int, segmentation: np.ndarray, score: float):\n \"\"\" The segmentation should be the full mask, the size of the image and with size [h, w]. \"\"\"\n rle = pycocotools.mask.encode(np.asfortranarray(segmentation.astype(np.uint8)))\n rle['counts'] = rle['counts'].decode('ascii') # json.dump doesn't like bytes strings\n\n self.mask_data.append({'image_id': int(image_id),\n 'category_id': self.coco_cats[int(category_id)],\n 'segmentation': rle,\n 'score': float(score)})\n\n def dump(self):\n dump_arguments = [(self.bbox_data, f'results/bbox_detections.json'),\n (self.mask_data, f'results/mask_detections.json')]\n\n for data, path in dump_arguments:\n with open(path, 'w') as f:\n json.dump(data, f)\n\n\nclass APDataObject:\n \"\"\"Stores all the information necessary to calculate the AP for one IoU and one class.\"\"\"\n\n def __init__(self):\n self.data_points = []\n self.num_gt_positives = 0\n\n def push(self, score: float, is_true: bool):\n self.data_points.append((score, is_true))\n\n def add_gt_positives(self, num_positives: int):\n \"\"\" Call this once per image. \"\"\"\n self.num_gt_positives += num_positives\n\n def is_empty(self) -> bool:\n return len(self.data_points) == 0 and self.num_gt_positives == 0\n\n def get_ap(self) -> float:\n \"\"\" Warning: result not cached. \"\"\"\n\n if self.num_gt_positives == 0:\n return 0\n\n # Sort descending by score\n self.data_points.sort(key=lambda x: -x[0])\n\n precisions = []\n recalls = []\n num_true = 0\n num_false = 0\n\n # Compute the precision-recall curve. The x axis is recalls and the y axis precisions.\n for datum in self.data_points:\n # datum[1] is whether the detection a true or false positive\n if datum[1]:\n num_true += 1\n else:\n num_false += 1\n\n precision = num_true / (num_true + num_false)\n recall = num_true / self.num_gt_positives\n\n precisions.append(precision)\n recalls.append(recall)\n\n # Smooth the curve by computing [max(precisions[i:]) for i in range(len(precisions))]\n # Basically, remove any temporary dips from the curve.\n # At least that's what I think, idk. COCOEval did it so I do too.\n for i in range(len(precisions) - 1, 0, -1):\n if precisions[i] > precisions[i - 1]:\n precisions[i - 1] = precisions[i]\n\n # Compute the integral of precision(recall) d_recall from recall=0->1 using fixed-length riemann summation with 101 bars.\n y_range = [0] * 101 # idx 0 is recall == 0.0 and idx 100 is recall == 1.00\n x_range = np.array([x / 100 for x in range(101)])\n recalls = np.array(recalls)\n\n # I realize this is weird, but all it does is find the nearest precision(x) for a given x in x_range.\n # Basically, if the closest recall we have to 0.01 is 0.009 this sets precision(0.01) = precision(0.009).\n # I approximate the integral this way, because that's how COCOEval does it.\n indices = np.searchsorted(recalls, x_range, side='left')\n for bar_idx, precision_idx in enumerate(indices):\n if precision_idx < len(precisions):\n y_range[bar_idx] = precisions[precision_idx]\n\n # Finally compute the riemann sum to get our integral.\n # avg([precision(x) for x in 0:0.01:1])\n return sum(y_range) / len(y_range)\n\n\ndef prep_metrics(ap_data, nms_outs, gt, gt_masks, h, w, num_crowd, image_id, make_json, cocoapi):\n \"\"\" Returns a list of APs for this image, with each element being for a class \"\"\"\n\n with timer.env('After NMS'):\n pred_classes, pred_confs, pred_boxes, pred_masks = after_nms(nms_outs, h, w)\n if pred_classes.size(0) == 0:\n return\n\n pred_classes = list(pred_classes.cpu().numpy().astype(int))\n pred_confs = list(pred_confs.cpu().numpy().astype(float))\n pred_masks = pred_masks.view(-1, h * w).cuda() if cuda else pred_masks.view(-1, h * w)\n pred_boxes = pred_boxes.cuda() if cuda else pred_boxes\n\n if cocoapi:\n with timer.env('Output json'):\n pred_boxes = pred_boxes.cpu().numpy()\n pred_masks = pred_masks.view(-1, h, w).cpu().numpy()\n\n for i in range(pred_masks.shape[0]):\n # Make sure that the bounding box actually makes sense and a mask was produced\n if (pred_boxes[i, 3] - pred_boxes[i, 1]) * (pred_boxes[i, 2] - pred_boxes[i, 0]) > 0:\n make_json.add_bbox(image_id, pred_classes[i], pred_boxes[i, :], pred_confs[i])\n make_json.add_mask(image_id, pred_classes[i], pred_masks[i, :, :], pred_confs[i])\n return\n\n with timer.env('Prepare gt'):\n gt_boxes = torch.Tensor(gt[:, :4])\n gt_boxes[:, [0, 2]] *= w\n gt_boxes[:, [1, 3]] *= h\n gt_classes = list(gt[:, 4].astype(int))\n gt_masks = torch.Tensor(gt_masks).view(-1, h * w)\n\n if num_crowd > 0:\n split = lambda x: (x[-num_crowd:], x[:-num_crowd])\n crowd_boxes, gt_boxes = split(gt_boxes)\n crowd_masks, gt_masks = split(gt_masks)\n crowd_classes, gt_classes = split(gt_classes)\n\n with timer.env('Eval Setup'):\n mask_iou_cache = mask_iou(pred_masks, gt_masks)\n bbox_iou_cache = bbox_iou(pred_boxes.float(), gt_boxes.float())\n\n if num_crowd > 0:\n crowd_mask_iou_cache = mask_iou(pred_masks, crowd_masks, iscrowd=True)\n crowd_bbox_iou_cache = bbox_iou(pred_boxes.float(), crowd_boxes.float(), iscrowd=True)\n else:\n crowd_mask_iou_cache = None\n crowd_bbox_iou_cache = None\n\n iou_types = [('box', lambda i, j: bbox_iou_cache[i, j].item(), lambda i, j: crowd_bbox_iou_cache[i, j].item()),\n ('mask', lambda i, j: mask_iou_cache[i, j].item(), lambda i, j: crowd_mask_iou_cache[i, j].item())]\n\n timer.start('Main loop')\n for _class in set(pred_classes + gt_classes):\n num_gt_per_class = gt_classes.count(_class)\n\n for iouIdx in range(len(iou_thresholds)):\n iou_threshold = iou_thresholds[iouIdx]\n\n for iou_type, iou_func, crowd_func in iou_types:\n gt_used = [False] * len(gt_classes)\n ap_obj = ap_data[iou_type][iouIdx][_class]\n ap_obj.add_gt_positives(num_gt_per_class)\n\n for i, pred_class in enumerate(pred_classes):\n if pred_class != _class:\n continue\n\n max_iou_found = iou_threshold\n max_match_idx = -1\n for j, gt_class in enumerate(gt_classes):\n if gt_used[j] or gt_class != _class:\n continue\n\n iou = iou_func(i, j)\n\n if iou > max_iou_found:\n max_iou_found = iou\n max_match_idx = j\n\n if max_match_idx >= 0:\n gt_used[max_match_idx] = True\n ap_obj.push(pred_confs[i], True)\n else:\n # If the detection matches a crowd, we can just ignore it\n matched_crowd = False\n\n if num_crowd > 0:\n for j in range(len(crowd_classes)):\n if crowd_classes[j] != _class:\n continue\n\n iou = crowd_func(i, j)\n\n if iou > iou_threshold:\n matched_crowd = True\n break\n\n # All this crowd code so that we can make sure that our eval code gives the\n # same result as COCOEval. There aren't even that many crowd annotations to\n # begin with, but accuracy is of the utmost importance.\n if not matched_crowd:\n ap_obj.push(pred_confs[i], False)\n timer.stop('Main loop')\n\n\ndef calc_map(ap_data):\n print('\\nCalculating mAP...')\n aps = [{'box': [], 'mask': []} for _ in iou_thresholds]\n\n for _class in range(len(cfg.dataset.class_names)):\n for iou_idx in range(len(iou_thresholds)):\n for iou_type in ('box', 'mask'):\n ap_obj = ap_data[iou_type][iou_idx][_class]\n\n if not ap_obj.is_empty():\n aps[iou_idx][iou_type].append(ap_obj.get_ap())\n\n all_maps = {'box': OrderedDict(), 'mask': OrderedDict()}\n\n for iou_type in ('box', 'mask'):\n all_maps[iou_type]['all'] = 0 # Make this first in the ordereddict\n for i, threshold in enumerate(iou_thresholds):\n mAP = sum(aps[i][iou_type]) / len(aps[i][iou_type]) * 100 if len(aps[i][iou_type]) > 0 else 0\n all_maps[iou_type][int(threshold * 100)] = mAP\n all_maps[iou_type]['all'] = (sum(all_maps[iou_type].values()) / (len(all_maps[iou_type].values()) - 1))\n\n row1 = list(all_maps['box'].keys())\n row1.insert(0, ' ')\n\n row2 = list(all_maps['box'].values())\n row2 = [round(aa, 2) for aa in row2]\n row2.insert(0, 'box')\n\n row3 = list(all_maps['mask'].values())\n row3 = [round(aa, 2) for aa in row3]\n row3.insert(0, 'mask')\n\n table = [row1, row2, row3]\n table = AsciiTable(table)\n return table.table, row2, row3\n\n\ndef evaluate(net, dataset, max_num=-1, during_training=False, cocoapi=False, traditional_nms=False):\n frame_times = MovingAverage()\n dataset_size = len(dataset) if max_num < 0 else min(max_num, len(dataset))\n dataset_indices = list(range(len(dataset)))\n dataset_indices = dataset_indices[:dataset_size]\n progress_bar = ProgressBar(40, dataset_size)\n\n # For each class and iou, stores tuples (score, isPositive)\n # Index ap_data[type][iouIdx][classIdx]\n ap_data = {'box': [[APDataObject() for _ in cfg.dataset.class_names] for _ in iou_thresholds],\n 'mask': [[APDataObject() for _ in cfg.dataset.class_names] for _ in iou_thresholds]}\n make_json = Make_json()\n\n for i, image_idx in enumerate(dataset_indices):\n timer.reset()\n\n with timer.env('Data loading'):\n img, gt, gt_masks, h, w, num_crowd = dataset.pull_item(image_idx)\n\n batch = img.unsqueeze(0)\n if cuda:\n batch = batch.cuda()\n\n with timer.env('Network forward'):\n net_outs = net(batch)\n nms_outs = NMS(net_outs, traditional_nms)\n prep_metrics(ap_data, nms_outs, gt, gt_masks, h, w, num_crowd, dataset.ids[image_idx], make_json, cocoapi)\n\n # First couple of images take longer because we're constructing the graph.\n # Since that's technically initialization, don't include those in the FPS calculations.\n fps = 0\n if i > 1 and not during_training:\n frame_times.add(timer.total_time())\n fps = 1 / frame_times.get_avg()\n\n progress = (i + 1) / dataset_size * 100\n progress_bar.set_val(i + 1)\n print('\\rProcessing: %s %d / %d (%.2f%%) %.2f fps ' % (\n repr(progress_bar), i + 1, dataset_size, progress, fps), end='')\n\n else:\n if cocoapi:\n make_json.dump()\n print(f'\\nJson files dumped, saved in: \\'results/\\', start evaluting.')\n\n gt_annotations = COCO(cfg.dataset.valid_info)\n bbox_dets = gt_annotations.loadRes(f'results/bbox_detections.json')\n mask_dets = gt_annotations.loadRes(f'results/mask_detections.json')\n\n print('\\nEvaluating BBoxes:')\n bbox_eval = COCOeval(gt_annotations, bbox_dets, 'bbox')\n bbox_eval.evaluate()\n bbox_eval.accumulate()\n bbox_eval.summarize()\n\n print('\\nEvaluating Masks:')\n bbox_eval = COCOeval(gt_annotations, mask_dets, 'segm')\n bbox_eval.evaluate()\n bbox_eval.accumulate()\n bbox_eval.summarize()\n return\n\n table, box_row, mask_row = calc_map(ap_data)\n print(table)\n return table, box_row, mask_row\n\n\niou_thresholds = [x / 100 for x in range(50, 100, 5)]\ncuda = torch.cuda.is_available()\n\nif __name__ == '__main__':\n args = parser.parse_args()\n strs = args.trained_model.split('_')\n config = f'{strs[-3]}_{strs[-2]}_config'\n\n update_config(config)\n print(f'\\nUsing \\'{config}\\' according to the trained_model.\\n')\n\n with torch.no_grad():\n if cuda:\n cudnn.benchmark = True\n cudnn.fastest = True\n torch.set_default_tensor_type('torch.cuda.FloatTensor')\n else:\n torch.set_default_tensor_type('torch.FloatTensor')\n\n dataset = COCODetection(cfg.dataset.valid_images, cfg.dataset.valid_info, augmentation=BaseTransform())\n\n net = Yolact()\n net.load_weights('weights/' + args.trained_model, cuda)\n net.eval()\n print('\\nModel loaded.\\n')\n\n if cuda:\n net = net.cuda()\n\n evaluate(net, dataset, args.max_num, False, args.cocoapi, args.traditional_nms)\n" ]
[ [ "torch.set_default_tensor_type", "torch.Tensor", "torch.no_grad", "torch.cuda.is_available", "numpy.searchsorted", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
nealde/Ampere
[ "75fa9c34940a71ef865eb98b551b4a4a27da96c3", "75fa9c34940a71ef865eb98b551b4a4a27da96c3" ]
[ "setup.py", "ampere/models/P2D/solve.py" ]
[ "import setuptools\nimport pkg_resources\n\nfrom setuptools import setup, Extension\n\n\ndef is_installed(requirement):\n try:\n pkg_resources.require(requirement)\n except pkg_resources.ResolutionError:\n return False\n else:\n return True\n\n\nif not is_installed('numpy>=1.11.0'):\n print(\"\"\"\n Error: numpy needs to be installed first. You can install it via:\n\n $ pip install numpy\n \"\"\")\n exit(1)\n\nif not is_installed('Cython>=0.29'):\n print(\"\"\"\n Error: cython needs to be installed first. You can install it via:\n\n $ pip install cython\n \"\"\")\n exit(1)\n\nimport numpy\nfrom Cython.Distutils import build_ext\nfrom Cython.Build import cythonize\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\nida_dir = \"ampere/models/ida\"\nida_files = ['ida.c', 'ida_band.c', 'ida_dense.c', 'ida_direct.c', 'ida_ic.c', 'ida_io.c', 'nvector_serial.c', 'sundials_band.c', 'sundials_dense.c', 'sundials_direct.c', 'sundials_math.c', 'sundials_nvector.c']\nida_requirements1 = [ida_dir + '/' + ida_file for ida_file in ida_files]\n\n\next_modules = [\n Extension(\"ampere.models.P2D.P2D_fd\", [\"ampere/models/P2D/P2D_fd.pyx\", \"ampere/models/P2D/P2D_fd.c\", *ida_requirements1], include_dirs=[numpy.get_include()]),\n Extension(\"ampere.models.SPM.SPM_fd\", [\"ampere/models/SPM/SPM_fd.pyx\", \"ampere/models/SPM/SPM_fd.c\", *ida_requirements1], include_dirs=[numpy.get_include()]),\n Extension(\"ampere.models.SPM.SPM_fd_sei\", [\"ampere/models/SPM/SPM_fd_sei.pyx\", \"ampere/models/SPM/SPM_fd_sei.c\", *ida_requirements1], include_dirs=[numpy.get_include()]),\n Extension(\"ampere.models.SPM.SPM_par\", [\"ampere/models/SPM/SPM_par.pyx\", \"ampere/models/SPM/SPM_par.c\", *ida_requirements1], include_dirs=[numpy.get_include()]),\n]\ncmdclass = {'build_ext': build_ext}\n\nprint(setuptools.find_packages())\nsetup(\n name=\"ampere\",\n version=\"0.5.4\",\n author=\"Neal Dawson-Elli\",\n author_email=\"[email protected]\",\n description=\"A Python package for working with battery discharge data and physics-based battery models\",\n\n cmdclass=cmdclass,\n ext_modules=cythonize(ext_modules, compiler_directives={'language_level' : \"3\"}),\n\n\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/nealde/Ampere\",\n packages=[*setuptools.find_packages()],\n install_requires=['cython', 'matplotlib < 3.4', 'numpy', 'scipy'],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n 'Programming Language :: Cython',\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n 'Topic :: Scientific/Engineering :: Mathematics',\n ],\n keywords=\"battery numerical simulation modeling\",\n)\n", "import numpy as np\nfrom .P2D_fd import model as P2D_fd\n\n\ndef p2d_fd(p, initial_state=(), tf=0, internal=False):\n model_inputs = np.concatenate([p, [0], [tf], initial_state])\n N1 = p[25]\n N2 = p[26]\n N3 = p[27]\n Nr1 = p[28]\n Nr2 = p[29]\n\n model_outputs = np.zeros((10000, int(5*N1+2*N2+5*N3+N1*Nr1+N3*Nr2+15)))\n P2D_fd(model_inputs, model_outputs)\n\n count = np.nonzero(model_outputs[:,-2])[0][-1]+1\n model_outputs = model_outputs[:count]\n final = model_outputs[-1]\n # need to select: time, voltage, current\n out = model_outputs[:,[0,-2,-1]]\n out[:,-1] /= 17.1\n # out[:,1] -= var[:,6]\n return out, final, model_outputs\n" ]
[ [ "numpy.get_include" ], [ "numpy.concatenate", "numpy.nonzero" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hboshnak/mindarmour
[ "0609a4eaea875a84667bed279add9305752880cc", "0609a4eaea875a84667bed279add9305752880cc", "0609a4eaea875a84667bed279add9305752880cc", "0609a4eaea875a84667bed279add9305752880cc" ]
[ "mindarmour/fuzz_testing/model_coverage_metrics.py", "tests/ut/python/privacy/diff_privacy/test_monitor.py", "examples/reliability/model_fault_injection.py", "mindarmour/adv_robustness/attacks/black/genetic_attack.py" ]
[ "# Copyright 2019 Huawei Technologies Co., Ltd\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\"\"\"\nModel-Test Coverage Metrics.\n\"\"\"\nfrom abc import abstractmethod\nfrom collections import defaultdict\nimport math\nimport numpy as np\n\nfrom mindspore import Tensor\nfrom mindspore import Model\nfrom mindspore.train.summary.summary_record import _get_summary_tensor_data\n\nfrom mindarmour.utils._check_param import check_model, check_numpy_param, check_int_positive, \\\n check_param_type, check_value_positive\nfrom mindarmour.utils.logger import LogUtil\n\nLOGGER = LogUtil.get_instance()\nTAG = 'CoverageMetrics'\n\n\nclass CoverageMetrics:\n \"\"\"\n The abstract base class for Neuron coverage classes calculating coverage metrics.\n\n As we all known, each neuron output of a network will have a output range after training (we call it original\n range), and test dataset is used to estimate the accuracy of the trained network. However, neurons' output\n distribution would be different with different test datasets. Therefore, similar to function fuzz, model fuzz means\n testing those neurons' outputs and estimating the proportion of original range that has emerged with test\n datasets.\n\n Reference: `DeepGauge: Multi-Granularity Testing Criteria for Deep Learning Systems\n <https://arxiv.org/abs/1803.07519>`_\n\n Args:\n model (Model): The pre-trained model which waiting for testing.\n incremental (bool): Metrics will be calculate in incremental way or not. Default: False.\n batch_size (int): The number of samples in a fuzz test batch. Default: 32.\n \"\"\"\n\n def __init__(self, model, incremental=False, batch_size=32):\n self._model = check_model('model', model, Model)\n self.incremental = check_param_type('incremental', incremental, bool)\n self.batch_size = check_int_positive('batch_size', batch_size)\n self._activate_table = defaultdict(list)\n\n @abstractmethod\n def get_metrics(self, dataset):\n \"\"\"\n Calculate coverage metrics of given dataset.\n\n Args:\n dataset (numpy.ndarray): Dataset used to calculate coverage metrics.\n\n Raises:\n NotImplementedError: It is an abstract method.\n \"\"\"\n msg = 'The function get_metrics() is an abstract method in class `CoverageMetrics`, and should be' \\\n ' implemented in child class.'\n LOGGER.error(TAG, msg)\n raise NotImplementedError(msg)\n\n def _init_neuron_activate_table(self, data):\n \"\"\"\n Initialise the activate table of each neuron in the model with format:\n {'layer1': [n1, n2, n3, ..., nn], 'layer2': [n1, n2, n3, ..., nn], ...}\n\n Args:\n data (numpy.ndarray): Data used for initialising the activate table.\n\n Return:\n dict, return a activate_table.\n \"\"\"\n self._model.predict(Tensor(data))\n layer_out = _get_summary_tensor_data()\n if not layer_out:\n msg = 'User must use TensorSummary() operation to specify the middle layer of the model participating in ' \\\n 'the coverage calculation.'\n LOGGER.error(TAG, msg)\n raise ValueError(msg)\n activate_table = defaultdict()\n for layer, value in layer_out.items():\n activate_table[layer] = np.zeros(value.shape[1], np.bool)\n return activate_table\n\n def _get_bounds(self, train_dataset):\n \"\"\"\n Update the lower and upper boundaries of neurons' outputs.\n\n Args:\n train_dataset (numpy.ndarray): Training dataset used for determine the neurons' output boundaries.\n\n Return:\n - numpy.ndarray, upper bounds of neuron' outputs.\n\n - numpy.ndarray, lower bounds of neuron' outputs.\n \"\"\"\n upper_bounds = defaultdict(list)\n lower_bounds = defaultdict(list)\n batches = math.ceil(train_dataset.shape[0] / self.batch_size)\n for i in range(batches):\n inputs = train_dataset[i * self.batch_size: (i + 1) * self.batch_size]\n self._model.predict(Tensor(inputs))\n layer_out = _get_summary_tensor_data()\n for layer, tensor in layer_out.items():\n value = tensor.asnumpy()\n value = np.mean(value, axis=tuple([i for i in range(2, len(value.shape))]))\n min_value = np.min(value, axis=0)\n max_value = np.max(value, axis=0)\n if np.any(upper_bounds[layer]):\n max_flag = upper_bounds[layer] > max_value\n min_flag = lower_bounds[layer] < min_value\n upper_bounds[layer] = upper_bounds[layer] * max_flag + max_value * (1 - max_flag)\n lower_bounds[layer] = lower_bounds[layer] * min_flag + min_value * (1 - min_flag)\n else:\n upper_bounds[layer] = max_value\n lower_bounds[layer] = min_value\n return upper_bounds, lower_bounds\n\n def _activate_rate(self):\n \"\"\"\n Calculate the activate rate of neurons.\n \"\"\"\n total_neurons = 0\n activated_neurons = 0\n for _, value in self._activate_table.items():\n activated_neurons += np.sum(value)\n total_neurons += len(value)\n activate_rate = activated_neurons / total_neurons\n\n return activate_rate\n\n\nclass NeuronCoverage(CoverageMetrics):\n \"\"\"\n Calculate the neurons activated coverage. Neuron is activated when its output is greater than the threshold.\n Neuron coverage equals the proportion of activated neurons to total neurons in the network.\n\n Args:\n model (Model): The pre-trained model which waiting for testing.\n threshold (float): Threshold used to determined neurons is activated or not. Default: 0.1.\n incremental (bool): Metrics will be calculate in incremental way or not. Default: False.\n batch_size (int): The number of samples in a fuzz test batch. Default: 32.\n\n \"\"\"\n def __init__(self, model, threshold=0.1, incremental=False, batch_size=32):\n super(NeuronCoverage, self).__init__(model, incremental, batch_size)\n threshold = check_param_type('threshold', threshold, float)\n self.threshold = check_value_positive('threshold', threshold)\n\n\n def get_metrics(self, dataset):\n \"\"\"\n Get the metric of neuron coverage: the proportion of activated neurons to total neurons in the network.\n\n Args:\n dataset (numpy.ndarray): Dataset used to calculate coverage metrics.\n\n Returns:\n float, the metric of 'neuron coverage'.\n\n Examples:\n >>> nc = NeuronCoverage(model, threshold=0.1)\n >>> nc_metrics = nc.get_metrics(test_data)\n \"\"\"\n dataset = check_numpy_param('dataset', dataset)\n batches = math.ceil(dataset.shape[0] / self.batch_size)\n if not self.incremental or not self._activate_table:\n self._activate_table = self._init_neuron_activate_table(dataset[0:1])\n for i in range(batches):\n inputs = dataset[i * self.batch_size: (i + 1) * self.batch_size]\n self._model.predict(Tensor(inputs))\n layer_out = _get_summary_tensor_data()\n for layer, tensor in layer_out.items():\n value = tensor.asnumpy()\n value = np.mean(value, axis=tuple([i for i in range(2, len(value.shape))]))\n activate = np.sum(value > self.threshold, axis=0) > 0\n self._activate_table[layer] = np.logical_or(self._activate_table[layer], activate)\n neuron_coverage = self._activate_rate()\n return neuron_coverage\n\n\nclass TopKNeuronCoverage(CoverageMetrics):\n \"\"\"\n Calculate the top k activated neurons coverage. Neuron is activated when its output has the top k largest value in\n that hidden layers. Top k neurons coverage equals the proportion of activated neurons to total neurons in the\n network.\n\n Args:\n model (Model): The pre-trained model which waiting for testing.\n top_k (int): Neuron is activated when its output has the top k largest value in that hidden layers. Default: 3.\n incremental (bool): Metrics will be calculate in incremental way or not. Default: False.\n batch_size (int): The number of samples in a fuzz test batch. Default: 32.\n \"\"\"\n def __init__(self, model, top_k=3, incremental=False, batch_size=32):\n super(TopKNeuronCoverage, self).__init__(model, incremental=incremental, batch_size=batch_size)\n self.top_k = check_int_positive('top_k', top_k)\n\n def get_metrics(self, dataset):\n \"\"\"\n Get the metric of Top K activated neuron coverage.\n\n Args:\n dataset (numpy.ndarray): Dataset used to calculate coverage metrics.\n\n Returns:\n float, the metrics of 'top k neuron coverage'.\n\n Examples:\n >>> tknc = TopKNeuronCoverage(model, top_k=3)\n >>> metrics = tknc.get_metrics(test_data)\n \"\"\"\n dataset = check_numpy_param('dataset', dataset)\n batches = math.ceil(dataset.shape[0] / self.batch_size)\n if not self.incremental or not self._activate_table:\n self._activate_table = self._init_neuron_activate_table(dataset[0:1])\n for i in range(batches):\n inputs = dataset[i * self.batch_size: (i + 1) * self.batch_size]\n self._model.predict(Tensor(inputs))\n layer_out = _get_summary_tensor_data()\n for layer, tensor in layer_out.items():\n value = tensor.asnumpy()\n if len(value.shape) > 2:\n value = np.mean(value, axis=tuple([i for i in range(2, len(value.shape))]))\n top_k_value = np.sort(value)[:, -self.top_k].reshape(value.shape[0], 1)\n top_k_value = np.sum((value - top_k_value) >= 0, axis=0) > 0\n self._activate_table[layer] = np.logical_or(self._activate_table[layer], top_k_value)\n top_k_neuron_coverage = self._activate_rate()\n return top_k_neuron_coverage\n\n\nclass SuperNeuronActivateCoverage(CoverageMetrics):\n \"\"\"\n Get the metric of 'super neuron activation coverage'. :math:`SNAC = |UpperCornerNeuron|/|N|`. SNAC refers to the\n proportion of neurons whose neurons output value in the test set exceeds the upper bounds of the corresponding\n neurons output value in the training set.\n\n Args:\n model (Model): The pre-trained model which waiting for testing.\n train_dataset (numpy.ndarray): Training dataset used for determine the neurons' output boundaries.\n incremental (bool): Metrics will be calculate in incremental way or not. Default: False.\n batch_size (int): The number of samples in a fuzz test batch. Default: 32.\n \"\"\"\n def __init__(self, model, train_dataset, incremental=False, batch_size=32):\n super(SuperNeuronActivateCoverage, self).__init__(model, incremental=incremental, batch_size=batch_size)\n train_dataset = check_numpy_param('train_dataset', train_dataset)\n self.upper_bounds, self.lower_bounds = self._get_bounds(train_dataset=train_dataset)\n\n def get_metrics(self, dataset):\n \"\"\"\n Get the metric of 'strong neuron activation coverage'.\n\n Args:\n dataset (numpy.ndarray): Dataset used to calculate coverage metrics.\n\n Returns:\n float, the metric of 'strong neuron activation coverage'.\n\n Examples:\n >>> snac = SuperNeuronActivateCoverage(model, train_dataset)\n >>> metrics = snac.get_metrics(test_data)\n \"\"\"\n dataset = check_numpy_param('dataset', dataset)\n if not self.incremental or not self._activate_table:\n self._activate_table = self._init_neuron_activate_table(dataset[0:1])\n batches = math.ceil(dataset.shape[0] / self.batch_size)\n\n for i in range(batches):\n inputs = dataset[i * self.batch_size: (i + 1) * self.batch_size]\n self._model.predict(Tensor(inputs))\n layer_out = _get_summary_tensor_data()\n for layer, tensor in layer_out.items():\n value = tensor.asnumpy()\n if len(value.shape) > 2:\n value = np.mean(value, axis=tuple([i for i in range(2, len(value.shape))]))\n activate = np.sum(value > self.upper_bounds[layer], axis=0) > 0\n self._activate_table[layer] = np.logical_or(self._activate_table[layer], activate)\n snac = self._activate_rate()\n return snac\n\n\nclass NeuronBoundsCoverage(SuperNeuronActivateCoverage):\n \"\"\"\n Get the metric of 'neuron boundary coverage' :math:`NBC = (|UpperCornerNeuron| + |LowerCornerNeuron|)/(2*|N|)`,\n where :math:`|N|` is the number of neurons, NBC refers to the proportion of neurons whose neurons output value in\n the test dataset exceeds the upper and lower bounds of the corresponding neurons output value in the training\n dataset.\n\n Args:\n model (Model): The pre-trained model which waiting for testing.\n train_dataset (numpy.ndarray): Training dataset used for determine the neurons' output boundaries.\n incremental (bool): Metrics will be calculate in incremental way or not. Default: False.\n batch_size (int): The number of samples in a fuzz test batch. Default: 32.\n \"\"\"\n\n def __init__(self, model, train_dataset, incremental=False, batch_size=32):\n super(NeuronBoundsCoverage, self).__init__(model, train_dataset, incremental=incremental, batch_size=batch_size)\n\n def get_metrics(self, dataset):\n \"\"\"\n Get the metric of 'neuron boundary coverage'.\n\n Args:\n dataset (numpy.ndarray): Dataset used to calculate coverage metrics.\n\n Returns:\n float, the metric of 'neuron boundary coverage'.\n\n Examples:\n >>> nbc = NeuronBoundsCoverage(model, train_dataset)\n >>> metrics = nbc.get_metrics(test_data)\n \"\"\"\n dataset = check_numpy_param('dataset', dataset)\n if not self.incremental or not self._activate_table:\n self._activate_table = self._init_neuron_activate_table(dataset[0:1])\n\n batches = math.ceil(dataset.shape[0] / self.batch_size)\n for i in range(batches):\n inputs = dataset[i * self.batch_size: (i + 1) * self.batch_size]\n self._model.predict(Tensor(inputs))\n layer_out = _get_summary_tensor_data()\n for layer, tensor in layer_out.items():\n value = tensor.asnumpy()\n if len(value.shape) > 2:\n value = np.mean(value, axis=tuple([i for i in range(2, len(value.shape))]))\n outer = np.logical_or(value > self.upper_bounds[layer], value < self.lower_bounds[layer])\n activate = np.sum(outer, axis=0) > 0\n self._activate_table[layer] = np.logical_or(self._activate_table[layer], activate)\n nbc = self._activate_rate()\n return nbc\n\n\nclass KMultisectionNeuronCoverage(SuperNeuronActivateCoverage):\n \"\"\"\n Get the metric of 'k-multisection neuron coverage'. KMNC measures how thoroughly the given set of test inputs\n covers the range of neurons output values derived from training dataset.\n\n Args:\n model (Model): The pre-trained model which waiting for testing.\n train_dataset (numpy.ndarray): Training dataset used for determine the neurons' output boundaries.\n segmented_num (int): The number of segmented sections of neurons' output intervals. Default: 100.\n incremental (bool): Metrics will be calculate in incremental way or not. Default: False.\n batch_size (int): The number of samples in a fuzz test batch. Default: 32.\n \"\"\"\n\n def __init__(self, model, train_dataset, segmented_num=100, incremental=False, batch_size=32):\n super(KMultisectionNeuronCoverage, self).__init__(model, train_dataset, incremental=incremental,\n batch_size=batch_size)\n self.segmented_num = check_int_positive('segmented_num', segmented_num)\n self.intervals = defaultdict(list)\n for keys in self.upper_bounds.keys():\n self.intervals[keys] = (self.upper_bounds[keys] - self.lower_bounds[keys]) / self.segmented_num\n\n def _init_k_multisection_table(self, data):\n \"\"\" Initial the activate table.\"\"\"\n self._model.predict(Tensor(data))\n layer_out = _get_summary_tensor_data()\n activate_section_table = defaultdict()\n for layer, value in layer_out.items():\n activate_section_table[layer] = np.zeros((value.shape[1], self.segmented_num), np.bool)\n return activate_section_table\n\n def get_metrics(self, dataset):\n \"\"\"\n Get the metric of 'k-multisection neuron coverage'.\n\n Args:\n dataset (numpy.ndarray): Dataset used to calculate coverage metrics.\n\n Returns:\n float, the metric of 'k-multisection neuron coverage'.\n\n Examples:\n >>> kmnc = KMultisectionNeuronCoverage(model, train_dataset, segmented_num=100)\n >>> metrics = kmnc.get_metrics(test_data)\n \"\"\"\n\n dataset = check_numpy_param('dataset', dataset)\n if not self.incremental or not self._activate_table:\n self._activate_table = self._init_k_multisection_table(dataset[0:1])\n\n batches = math.ceil(dataset.shape[0] / self.batch_size)\n for i in range(batches):\n inputs = dataset[i * self.batch_size: (i + 1) * self.batch_size]\n self._model.predict(Tensor(inputs))\n layer_out = _get_summary_tensor_data()\n for layer, tensor in layer_out.items():\n value = tensor.asnumpy()\n value = np.mean(value, axis=tuple([i for i in range(2, len(value.shape))]))\n hits = np.floor((value - self.lower_bounds[layer]) / self.intervals[layer]).astype(int)\n hits = np.transpose(hits, [1, 0])\n for n in range(len(hits)):\n for sec in hits[n]:\n if sec >= self.segmented_num or sec < 0:\n continue\n self._activate_table[layer][n][sec] = True\n\n kmnc = self._activate_rate() / self.segmented_num\n return kmnc\n", "# Copyright 2019 Huawei Technologies Co., Ltd\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\"\"\"\nDP-Monitor test.\n\"\"\"\nimport pytest\nimport numpy as np\n\nimport mindspore.nn as nn\nimport mindspore.dataset as ds\nfrom mindspore.train import Model\nimport mindspore.context as context\n\nfrom mindarmour.privacy.diff_privacy import PrivacyMonitorFactory\nfrom mindarmour.utils.logger import LogUtil\n\nfrom tests.ut.python.utils.mock_net import Net\n\nLOGGER = LogUtil.get_instance()\nTAG = 'DP-Monitor Test'\n\n\ndef dataset_generator():\n batch_size = 16\n batches = 128\n\n data = np.random.random((batches * batch_size, 1, 32, 32)).astype(\n np.float32)\n label = np.random.randint(0, 10, batches * batch_size).astype(np.int32)\n for i in range(batches):\n yield data[i * batch_size: (i + 1) * batch_size], \\\n label[i * batch_size: (i + 1) * batch_size]\n\n\[email protected]\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_card\[email protected]_mindarmour\ndef test_dp_monitor():\n context.set_context(mode=context.GRAPH_MODE, device_target=\"Ascend\")\n batch_size = 16\n epochs = 1\n rdp = PrivacyMonitorFactory.create(policy='rdp', num_samples=60000,\n batch_size=batch_size,\n initial_noise_multiplier=0.4,\n noise_decay_rate=6e-3)\n suggest_epoch = rdp.max_epoch_suggest()\n LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',\n suggest_epoch)\n network = Net()\n net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction=\"mean\")\n net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)\n\n model = Model(network, net_loss, net_opt)\n\n LOGGER.info(TAG, \"============== Starting Training ==============\")\n ds1 = ds.GeneratorDataset(dataset_generator,\n [\"data\", \"label\"])\n model.train(epochs, ds1, callbacks=[rdp], dataset_sink_mode=False)\n\n\[email protected]\[email protected]_x86_gpu_training\[email protected]_card\[email protected]_mindarmour\ndef test_dp_monitor_gpu():\n context.set_context(mode=context.GRAPH_MODE, device_target=\"GPU\")\n batch_size = 16\n epochs = 1\n rdp = PrivacyMonitorFactory.create(policy='rdp', num_samples=60000,\n batch_size=batch_size,\n initial_noise_multiplier=0.4,\n noise_decay_rate=6e-3)\n suggest_epoch = rdp.max_epoch_suggest()\n LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',\n suggest_epoch)\n network = Net()\n net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction=\"mean\")\n net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)\n\n model = Model(network, net_loss, net_opt)\n\n LOGGER.info(TAG, \"============== Starting Training ==============\")\n ds1 = ds.GeneratorDataset(dataset_generator,\n [\"data\", \"label\"])\n model.train(epochs, ds1, callbacks=[rdp], dataset_sink_mode=False)\n\n\[email protected]\[email protected]_x86_cpu\[email protected]_card\[email protected]_mindarmour\ndef test_dp_monitor_cpu():\n context.set_context(mode=context.GRAPH_MODE, device_target=\"CPU\")\n batch_size = 16\n epochs = 1\n rdp = PrivacyMonitorFactory.create(policy='rdp', num_samples=60000,\n batch_size=batch_size,\n initial_noise_multiplier=0.4,\n noise_decay_rate=6e-3)\n suggest_epoch = rdp.max_epoch_suggest()\n LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',\n suggest_epoch)\n network = Net()\n net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction=\"mean\")\n net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)\n\n model = Model(network, net_loss, net_opt)\n\n LOGGER.info(TAG, \"============== Starting Training ==============\")\n ds1 = ds.GeneratorDataset(dataset_generator,\n [\"data\", \"label\"])\n model.train(epochs, ds1, callbacks=[rdp], dataset_sink_mode=False)\n\n\[email protected]\[email protected]_arm_ascend_training\[email protected]_x86_ascend_training\[email protected]_card\[email protected]_mindarmour\ndef test_dp_monitor_zcdp():\n context.set_context(mode=context.GRAPH_MODE, device_target=\"Ascend\")\n batch_size = 16\n epochs = 1\n zcdp = PrivacyMonitorFactory.create(policy='zcdp', num_samples=60000,\n batch_size=batch_size,\n initial_noise_multiplier=0.4,\n noise_decay_rate=6e-3)\n suggest_epoch = zcdp.max_epoch_suggest()\n LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',\n suggest_epoch)\n network = Net()\n net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction=\"mean\")\n net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)\n\n model = Model(network, net_loss, net_opt)\n\n LOGGER.info(TAG, \"============== Starting Training ==============\")\n ds1 = ds.GeneratorDataset(dataset_generator,\n [\"data\", \"label\"])\n model.train(epochs, ds1, callbacks=[zcdp], dataset_sink_mode=False)\n\n\[email protected]\[email protected]_x86_gpu_training\[email protected]_card\[email protected]_mindarmour\ndef test_dp_monitor_zcdp_gpu():\n context.set_context(mode=context.GRAPH_MODE, device_target=\"GPU\")\n batch_size = 16\n epochs = 1\n zcdp = PrivacyMonitorFactory.create(policy='zcdp', num_samples=60000,\n batch_size=batch_size,\n initial_noise_multiplier=0.4,\n noise_decay_rate=6e-3)\n suggest_epoch = zcdp.max_epoch_suggest()\n LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',\n suggest_epoch)\n network = Net()\n net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction=\"mean\")\n net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)\n\n model = Model(network, net_loss, net_opt)\n\n LOGGER.info(TAG, \"============== Starting Training ==============\")\n ds1 = ds.GeneratorDataset(dataset_generator,\n [\"data\", \"label\"])\n model.train(epochs, ds1, callbacks=[zcdp], dataset_sink_mode=False)\n\n\[email protected]\[email protected]_x86_cpu\[email protected]_card\[email protected]_mindarmour\ndef test_dp_monitor_zcdp_cpu():\n context.set_context(mode=context.GRAPH_MODE, device_target=\"CPU\")\n batch_size = 16\n epochs = 1\n zcdp = PrivacyMonitorFactory.create(policy='zcdp', num_samples=60000,\n batch_size=batch_size,\n initial_noise_multiplier=0.4,\n noise_decay_rate=6e-3)\n suggest_epoch = zcdp.max_epoch_suggest()\n LOGGER.info(TAG, 'The recommended maximum training epochs is: %s',\n suggest_epoch)\n network = Net()\n net_loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction=\"mean\")\n net_opt = nn.Momentum(network.trainable_params(), 0.01, 0.9)\n\n model = Model(network, net_loss, net_opt)\n\n LOGGER.info(TAG, \"============== Starting Training ==============\")\n ds1 = ds.GeneratorDataset(dataset_generator,\n [\"data\", \"label\"])\n model.train(epochs, ds1, callbacks=[zcdp], dataset_sink_mode=False)\n", "# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n\"\"\"\nFault injection example.\nDownload checkpoint from: https://www.mindspore.cn/resources/hub or just trained your own checkpoint.\nDownload dataset from: http://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz.\nFile structure:\n --cifar10-batches-bin\n --train\n --data_batch_1.bin\n --data_batch_2.bin\n --data_batch_3.bin\n --data_batch_4.bin\n --data_batch_5.bin\n --test\n --test_batch.bin\n\nPlease extract and restructure the file as shown above.\n\"\"\"\nimport argparse\n\nimport numpy as np\nfrom mindspore import Model, context\nfrom mindspore.train.serialization import load_checkpoint\n\nfrom mindarmour.reliability.model_fault_injection.fault_injection import FaultInjector\nfrom examples.common.networks.lenet5.lenet5_net import LeNet5\nfrom examples.common.networks.vgg.vgg import vgg16\nfrom examples.common.networks.resnet.resnet import resnet50\nfrom examples.common.dataset.data_processing import create_dataset_cifar, generate_mnist_dataset\n\n\nparser = argparse.ArgumentParser(description='layer_states')\nparser.add_argument('--device_target', type=str, default=\"CPU\", choices=['Ascend', 'GPU', 'CPU'])\nparser.add_argument('--model', type=str, default='lenet', choices=['lenet', 'resnet50', 'vgg16'])\nparser.add_argument('--device_id', type=int, default=0)\nargs = parser.parse_args()\ncontext.set_context(mode=context.GRAPH_MODE, device_target=args.device_target, device_id=args.device_id)\n\n\ntest_flag = args.model\nif test_flag == 'lenet':\n # load data\n DATA_FILE = '../common/dataset/MNIST_Data/test'\n ckpt_path = '../common/networks/lenet5/trained_ckpt_file/checkpoint_lenet-10_1875.ckpt'\n ds_eval = generate_mnist_dataset(DATA_FILE, batch_size=64)\n net = LeNet5()\nelif test_flag == 'vgg16':\n from examples.common.networks.vgg.config import cifar_cfg as cfg\n DATA_FILE = '../common/dataset/cifar10-batches-bin'\n ckpt_path = '../common/networks/vgg16_ascend_v111_cifar10_offical_cv_bs64_acc93.ckpt'\n ds_eval = create_dataset_cifar(DATA_FILE, 224, 224, training=False)\n net = vgg16(10, cfg, 'test')\nelif test_flag == 'resnet50':\n DATA_FILE = '../common/dataset/cifar10-batches-bin'\n ckpt_path = '../common/networks/resnet50_ascend_v111_cifar10_offical_cv_bs32_acc92.ckpt'\n ds_eval = create_dataset_cifar(DATA_FILE, 224, 224, training=False)\n net = resnet50(10)\nelse:\n exit()\n\ntest_images = []\ntest_labels = []\nfor data in ds_eval.create_tuple_iterator(output_numpy=True):\n images = data[0].astype(np.float32)\n labels = data[1]\n test_images.append(images)\n test_labels.append(labels)\nds_data = np.concatenate(test_images, axis=0)\nds_label = np.concatenate(test_labels, axis=0)\n\nparam_dict = load_checkpoint(ckpt_path, net=net)\nmodel = Model(net)\n\n# Initialization\nfi_type = ['bitflips_random', 'bitflips_designated', 'random', 'zeros',\n 'nan', 'inf', 'anti_activation', 'precision_loss']\nfi_mode = ['single_layer', 'all_layer']\nfi_size = [1, 2, 3]\n\n# Fault injection\nfi = FaultInjector(model, fi_type, fi_mode, fi_size)\nresults = fi.kick_off(ds_data, ds_label, iter_times=100)\nresult_summary = fi.metrics()\n\n# print result\nfor result in results:\n print(result)\nfor result in result_summary:\n print(result)\n", "# Copyright 2019 Huawei Technologies Co., Ltd\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\"\"\"\nGenetic-Attack.\n\"\"\"\nimport numpy as np\nfrom scipy.special import softmax\n\nfrom mindarmour.utils.logger import LogUtil\nfrom mindarmour.utils._check_param import check_numpy_param, check_model, \\\n check_pair_numpy_param, check_param_type, check_value_positive, \\\n check_int_positive, check_detection_inputs, check_value_non_negative, check_param_multi_types\nfrom mindarmour.adv_robustness.attacks.attack import Attack\nfrom .black_model import BlackModel\n\nLOGGER = LogUtil.get_instance()\nTAG = 'GeneticAttack'\n\n\nclass GeneticAttack(Attack):\n \"\"\"\n The Genetic Attack represents the black-box attack based on the genetic algorithm,\n which belongs to differential evolution algorithms.\n\n This attack was proposed by Moustafa Alzantot et al. (2018).\n\n References: `Moustafa Alzantot, Yash Sharma, Supriyo Chakraborty,\n \"GeneticAttack: Practical Black-box Attacks with\n Gradient-FreeOptimization\" <https://arxiv.org/abs/1805.11090>`_\n\n Args:\n model (BlackModel): Target model.\n model_type (str): The type of targeted model. 'classification' and 'detection' are supported now.\n default: 'classification'.\n targeted (bool): If True, turns on the targeted attack. If False,\n turns on untargeted attack. It should be noted that only untargeted attack\n is supported for model_type='detection', Default: True.\n reserve_ratio (Union[int, float]): The percentage of objects that can be detected after attacks,\n specifically for model_type='detection'. Reserve_ratio should be in the range of (0, 1). Default: 0.3.\n pop_size (int): The number of particles, which should be greater than\n zero. Default: 6.\n mutation_rate (Union[int, float]): The probability of mutations, which should be in the range of (0, 1).\n Default: 0.005.\n per_bounds (Union[int, float]): Maximum L_inf distance.\n max_steps (int): The maximum round of iteration for each adversarial\n example. Default: 1000.\n step_size (Union[int, float]): Attack step size. Default: 0.2.\n temp (Union[int, float]): Sampling temperature for selection. Default: 0.3.\n The greater the temp, the greater the differences between individuals'\n selecting probabilities.\n bounds (Union[tuple, list, None]): Upper and lower bounds of data. In form\n of (clip_min, clip_max). Default: (0, 1.0).\n adaptive (bool): If True, turns on dynamic scaling of mutation\n parameters. If false, turns on static mutation parameters.\n Default: False.\n sparse (bool): If True, input labels are sparse-encoded. If False,\n input labels are one-hot-encoded. Default: True.\n c (Union[int, float]): Weight of perturbation loss. Default: 0.1.\n\n Examples:\n >>> import mindspore.ops.operations as M\n >>> from mindspore import Tensor\n >>> from mindspore.nn import Cell\n >>> from mindarmour import BlackModel\n >>> from mindarmour.adv_robustness.attacks import GeneticAttack\n >>> class ModelToBeAttacked(BlackModel):\n ... def __init__(self, network):\n ... super(ModelToBeAttacked, self).__init__()\n ... self._network = network\n ... def predict(self, inputs):\n ... result = self._network(Tensor(inputs.astype(np.float32)))\n ... return result.asnumpy()\n >>> class Net(Cell):\n ... def __init__(self):\n ... super(Net, self).__init__()\n ... self._softmax = M.Softmax()\n ... def construct(self, inputs):\n ... out = self._softmax(inputs)\n ... return out\n >>> net = Net()\n >>> model = ModelToBeAttacked(net)\n >>> attack = GeneticAttack(model, sparse=False)\n >>> batch_size = 6\n >>> x_test = np.random.rand(batch_size, 10)\n >>> y_test = np.random.randint(low=0, high=10, size=batch_size)\n >>> y_test = np.eye(10)[y_test]\n >>> y_test = y_test.astype(np.float32)\n >>> _, adv_data, _ = attack.generate(x_test, y_test)\n \"\"\"\n def __init__(self, model, model_type='classification', targeted=True, reserve_ratio=0.3, sparse=True,\n pop_size=6, mutation_rate=0.005, per_bounds=0.15, max_steps=1000, step_size=0.20, temp=0.3,\n bounds=(0, 1.0), adaptive=False, c=0.1):\n super(GeneticAttack, self).__init__()\n self._model = check_model('model', model, BlackModel)\n self._model_type = check_param_type('model_type', model_type, str)\n if self._model_type not in ('classification', 'detection'):\n msg = \"Only 'classification' or 'detection' is supported now, but got {}.\".format(self._model_type)\n LOGGER.error(TAG, msg)\n raise ValueError(msg)\n self._targeted = check_param_type('targeted', targeted, bool)\n self._reserve_ratio = check_value_non_negative('reserve_ratio', reserve_ratio)\n if self._reserve_ratio > 1:\n msg = \"reserve_ratio should not be greater than 1.0, but got {}.\".format(self._reserve_ratio)\n LOGGER.error(TAG, msg)\n raise ValueError(msg)\n self._sparse = check_param_type('sparse', sparse, bool)\n self._per_bounds = check_value_positive('per_bounds', per_bounds)\n self._pop_size = check_int_positive('pop_size', pop_size)\n self._step_size = check_value_positive('step_size', step_size)\n self._temp = check_value_positive('temp', temp)\n self._max_steps = check_int_positive('max_steps', max_steps)\n self._mutation_rate = check_value_non_negative('mutation_rate', mutation_rate)\n if self._mutation_rate > 1:\n msg = \"mutation_rate should not be greater than 1.0, but got {}.\".format(self._mutation_rate)\n LOGGER.error(TAG, msg)\n raise ValueError(msg)\n self._adaptive = check_param_type('adaptive', adaptive, bool)\n # initial global optimum fitness value\n self._best_fit = -np.inf\n # count times of no progress\n self._plateau_times = 0\n # count times of changing attack step_size\n self._adap_times = 0\n self._bounds = bounds\n if self._bounds is not None:\n self._bounds = check_param_multi_types('bounds', bounds, [list, tuple])\n for b in self._bounds:\n _ = check_param_multi_types('bound', b, [int, float])\n self._c = check_value_positive('c', c)\n\n def _mutation(self, cur_pop, step_noise=0.01, prob=0.005):\n \"\"\"\n Generate mutation samples in genetic_attack.\n\n Args:\n cur_pop (numpy.ndarray): Samples before mutation.\n step_noise (float): Noise range. Default: 0.01.\n prob (float): Mutation probability. Default: 0.005.\n\n Returns:\n numpy.ndarray, samples after mutation operation in genetic_attack.\n\n Examples:\n >>> mul_pop = self._mutation_op([0.2, 0.3, 0.4], step_noise=0.03,\n >>> prob=0.01)\n \"\"\"\n cur_pop = check_numpy_param('cur_pop', cur_pop)\n perturb_noise = np.clip(np.random.random(cur_pop.shape) - 0.5,\n -step_noise, step_noise)*(self._bounds[1] - self._bounds[0])\n mutated_pop = perturb_noise*(\n np.random.random(cur_pop.shape) < prob) + cur_pop\n return mutated_pop\n\n\n def _compute_next_generation(self, cur_pop, fit_vals, x_ori):\n \"\"\"\n Compute pop for next generation\n\n Args:\n cur_pop (numpy.ndarray): Samples before mutation.\n fit_vals (numpy.ndarray): fitness values\n x_ori (numpy.ndarray): original input x\n\n Returns:\n numpy.ndarray, pop after generation\n\n Examples:\n >>> cur_pop, elite = self._compute_next_generation(cur_pop, fit_vals, x_ori)\n \"\"\"\n best_fit = max(fit_vals)\n\n if best_fit > self._best_fit:\n self._best_fit = best_fit\n self._plateau_times = 0\n else:\n self._plateau_times += 1\n adap_threshold = (lambda z: 100 if z > -0.4 else 300)(best_fit)\n if self._plateau_times > adap_threshold:\n self._adap_times += 1\n self._plateau_times = 0\n if self._adaptive:\n step_noise = max(self._step_size, 0.4*(0.9**self._adap_times))\n step_p = max(self._mutation_rate, 0.5*(0.9**self._adap_times))\n else:\n step_noise = self._step_size\n step_p = self._mutation_rate\n step_temp = self._temp\n elite = cur_pop[np.argmax(fit_vals)]\n select_probs = softmax(fit_vals/step_temp)\n select_args = np.arange(self._pop_size)\n parents_arg = np.random.choice(\n a=select_args, size=2*(self._pop_size - 1),\n replace=True, p=select_probs)\n parent1 = cur_pop[parents_arg[:self._pop_size - 1]]\n parent2 = cur_pop[parents_arg[self._pop_size - 1:]]\n parent1_probs = select_probs[parents_arg[:self._pop_size - 1]]\n parent2_probs = select_probs[parents_arg[self._pop_size - 1:]]\n parent2_probs = parent2_probs / (parent1_probs + parent2_probs)\n # duplicate the probabilities to all features of each particle.\n dims = len(x_ori.shape)\n for _ in range(dims):\n parent2_probs = parent2_probs[:, np.newaxis]\n parent2_probs = np.tile(parent2_probs, ((1,) + x_ori.shape))\n cross_probs = (np.random.random(parent1.shape) >\n parent2_probs).astype(np.int32)\n children = parent1*cross_probs + parent2*(1 - cross_probs)\n mutated_children = self._mutation(\n children, step_noise=self._per_bounds*step_noise,\n prob=step_p)\n cur_pop = np.concatenate((mutated_children, elite[np.newaxis, :]))\n\n return cur_pop, elite\n\n\n\n def _generate_classification(self, inputs, labels):\n \"\"\"\n Generate adversarial examples based on input data and\n targeted labels (or ground_truth labels) for classification model.\n\n Args:\n inputs (Union[numpy.ndarray, tuple]): Input samples. The format of inputs should be numpy.ndarray.\n labels (Union[numpy.ndarray, tuple]): Targeted labels or ground-truth labels.\n The format of labels should be numpy.ndarray.\n\n Returns:\n - numpy.ndarray, bool values for each attack result.\n\n - numpy.ndarray, generated adversarial examples.\n\n - numpy.ndarray, query times for each sample.\n \"\"\"\n inputs, labels = check_pair_numpy_param('inputs', inputs, 'labels', labels)\n if self._sparse:\n if labels.size > 1:\n label_squ = np.squeeze(labels)\n else:\n label_squ = labels\n if len(label_squ.shape) >= 2 or label_squ.shape[0] != inputs.shape[0]:\n msg = \"The parameter 'sparse' of GeneticAttack is True, but the input labels is not sparse style \" \\\n \"and got its shape as {}.\".format(labels.shape)\n LOGGER.error(TAG, msg)\n raise ValueError(msg)\n else:\n labels = np.argmax(labels, axis=1)\n images = inputs\n\n adv_list = []\n success_list = []\n query_times_list = []\n for i in range(images.shape[0]):\n is_success = False\n x_ori = images[i]\n if not self._bounds:\n self._bounds = [np.min(x_ori), np.max(x_ori)]\n pixel_deep = self._bounds[1] - self._bounds[0]\n label_i = labels[i]\n\n # generate particles\n ori_copies = np.repeat(x_ori[np.newaxis, :], self._pop_size, axis=0)\n # initial perturbations\n cur_pert = np.random.uniform(self._bounds[0], self._bounds[1], ori_copies.shape)\n cur_pop = ori_copies + cur_pert\n query_times = 0\n iters = 0\n\n while iters < self._max_steps:\n iters += 1\n cur_pop = np.clip(np.clip(cur_pop,\n ori_copies - pixel_deep*self._per_bounds,\n ori_copies + pixel_deep*self._per_bounds),\n self._bounds[0], self._bounds[1])\n\n pop_preds = self._model.predict(cur_pop)\n query_times += cur_pop.shape[0]\n all_preds = np.argmax(pop_preds, axis=1)\n if self._targeted:\n success_pop = np.equal(label_i, all_preds).astype(np.int32)\n else:\n success_pop = np.not_equal(label_i, all_preds).astype(np.int32)\n is_success = max(success_pop)\n best_idx = np.argmax(success_pop)\n target_preds = pop_preds[:, label_i]\n others_preds_sum = np.sum(pop_preds, axis=1) - target_preds\n if self._targeted:\n fit_vals = target_preds - others_preds_sum\n else:\n fit_vals = others_preds_sum - target_preds\n\n if is_success:\n LOGGER.debug(TAG, 'successfully find one adversarial sample '\n 'and start Reduction process.')\n final_adv = cur_pop[best_idx]\n\n final_adv, query_times = self._reduction(x_ori, query_times, label_i, final_adv,\n model=self._model, targeted_attack=self._targeted)\n break\n\n cur_pop, elite = self._compute_next_generation(cur_pop, fit_vals, x_ori)\n\n if not is_success:\n LOGGER.debug(TAG, 'fail to find adversarial sample.')\n final_adv = elite\n adv_list.append(final_adv)\n\n LOGGER.debug(TAG,\n 'iteration times is: %d and query times is: %d',\n iters,\n query_times)\n success_list.append(is_success)\n query_times_list.append(query_times)\n del ori_copies, cur_pert, cur_pop\n return np.asarray(success_list), \\\n np.asarray(adv_list), \\\n np.asarray(query_times_list)\n\n\n\n def _generate_detection(self, inputs, labels):\n \"\"\"\n Generate adversarial examples based on input data and\n targeted labels (or ground_truth labels) for detection model.\n\n Args:\n inputs (Union[numpy.ndarray, tuple]): Input samples. The format of inputs should be only one array.\n labels (Union[numpy.ndarray, tuple]): Targeted labels or ground-truth labels. The format of labels should\n be (gt_boxes, gt_labels).\n\n Returns:\n - numpy.ndarray, bool values for each attack result.\n\n - numpy.ndarray, generated adversarial examples.\n\n - numpy.ndarray, query times for each sample.\n \"\"\"\n images, auxiliary_inputs, gt_boxes, gt_labels = check_detection_inputs(inputs, labels)\n adv_list = []\n success_list = []\n query_times_list = []\n for i in range(images.shape[0]):\n is_success = False\n x_ori = images[i]\n if not self._bounds:\n self._bounds = [np.min(x_ori), np.max(x_ori)]\n pixel_deep = self._bounds[1] - self._bounds[0]\n auxiliary_input_i = tuple()\n for item in auxiliary_inputs:\n auxiliary_input_i += (np.expand_dims(item[i], axis=0),)\n gt_boxes_i, gt_labels_i = np.expand_dims(gt_boxes[i], axis=0), np.expand_dims(gt_labels[i], axis=0)\n inputs_i = (images[i],) + auxiliary_input_i\n confi_ori, gt_object_num = self._detection_scores(inputs_i, gt_boxes_i, gt_labels_i, model=self._model)\n LOGGER.info(TAG, 'The number of ground-truth objects is %s', gt_object_num[0])\n\n # generate particles\n ori_copies = np.repeat(x_ori[np.newaxis, :], self._pop_size, axis=0)\n # initial perturbations\n cur_pert = np.random.uniform(self._bounds[0], self._bounds[1], ori_copies.shape)\n cur_pop = ori_copies + cur_pert\n query_times = 0\n iters = 0\n\n while iters < self._max_steps:\n iters += 1\n cur_pop = np.clip(np.clip(cur_pop,\n ori_copies - pixel_deep*self._per_bounds,\n ori_copies + pixel_deep*self._per_bounds),\n self._bounds[0], self._bounds[1])\n\n confi_adv, correct_nums_adv = self._detection_scores(\n (cur_pop,) + auxiliary_input_i, gt_boxes_i, gt_labels_i, model=self._model)\n LOGGER.info(TAG, 'The number of correctly detected objects in adversarial image is %s',\n np.min(correct_nums_adv))\n query_times += self._pop_size\n fit_vals = abs(\n confi_ori - confi_adv) - self._c / self._pop_size * np.linalg.norm(\n (cur_pop - x_ori).reshape(cur_pop.shape[0], -1), axis=1)\n\n if np.max(fit_vals) < 0:\n self._c /= 2\n\n if np.max(fit_vals) < -2:\n LOGGER.debug(TAG,\n 'best fitness value is %s, which is too small. We recommend that you decrease '\n 'the value of the initialization parameter c.', np.max(fit_vals))\n if iters < 3 and np.max(fit_vals) > 100:\n LOGGER.debug(TAG,\n 'best fitness value is %s, which is too large. We recommend that you increase '\n 'the value of the initialization parameter c.', np.max(fit_vals))\n\n if np.min(correct_nums_adv) <= int(gt_object_num*self._reserve_ratio):\n is_success = True\n best_idx = np.argmin(correct_nums_adv)\n\n if is_success:\n LOGGER.debug(TAG, 'successfully find one adversarial sample '\n 'and start Reduction process.')\n final_adv = cur_pop[best_idx]\n break\n\n cur_pop, elite = self._compute_next_generation(cur_pop, fit_vals, x_ori)\n\n if not is_success:\n LOGGER.debug(TAG, 'fail to find adversarial sample.')\n final_adv = elite\n\n final_adv, query_times = self._fast_reduction(\n x_ori, final_adv, query_times, auxiliary_input_i, gt_boxes_i, gt_labels_i, model=self._model)\n adv_list.append(final_adv)\n\n LOGGER.debug(TAG,\n 'iteration times is: %d and query times is: %d',\n iters,\n query_times)\n success_list.append(is_success)\n query_times_list.append(query_times)\n del ori_copies, cur_pert, cur_pop\n return np.asarray(success_list), \\\n np.asarray(adv_list), \\\n np.asarray(query_times_list)\n\n def generate(self, inputs, labels):\n \"\"\"\n Generate adversarial examples based on input data and targeted labels (or ground_truth labels).\n\n Args:\n inputs (Union[numpy.ndarray, tuple]): Input samples. The format of inputs should be numpy.ndarray if\n model_type='classification'. The format of inputs can be (input1, input2, ...) or only one array if\n model_type='detection'.\n labels (Union[numpy.ndarray, tuple]): Targeted labels or ground-truth labels. The format of labels should\n be numpy.ndarray if model_type='classification'. The format of labels should be (gt_boxes, gt_labels)\n if model_type='detection'.\n\n Returns:\n - numpy.ndarray, bool values for each attack result.\n\n - numpy.ndarray, generated adversarial examples.\n\n - numpy.ndarray, query times for each sample.\n \"\"\"\n if self._model_type == 'classification':\n success_list, adv_data, query_time_list = self._generate_classification(inputs, labels)\n\n elif self._model_type == 'detection':\n success_list, adv_data, query_time_list = self._generate_detection(inputs, labels)\n\n return success_list, adv_data, query_time_list\n" ]
[ [ "numpy.min", "numpy.sort", "numpy.logical_or", "numpy.max", "numpy.any", "numpy.floor", "numpy.transpose", "numpy.zeros", "numpy.sum" ], [ "numpy.random.random", "numpy.random.randint" ], [ "numpy.concatenate" ], [ "numpy.expand_dims", "numpy.asarray", "numpy.squeeze", "numpy.concatenate", "numpy.max", "numpy.argmin", "scipy.special.softmax", "numpy.clip", "numpy.arange", "numpy.argmax", "numpy.repeat", "numpy.random.choice", "numpy.min", "numpy.equal", "numpy.not_equal", "numpy.sum", "numpy.random.random", "numpy.tile", "numpy.random.uniform" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.6", "1.10", "1.4", "1.9", "1.5", "1.2", "1.7", "1.3", "1.8" ], "tensorflow": [] } ]
Exusial/jittor
[ "eca21d5bba5098bce4f492fa44908677b6e76588", "eca21d5bba5098bce4f492fa44908677b6e76588", "eca21d5bba5098bce4f492fa44908677b6e76588", "eca21d5bba5098bce4f492fa44908677b6e76588", "eca21d5bba5098bce4f492fa44908677b6e76588" ]
[ "python/jittor/test/test_argsort_op.py", "python/jittor/contrib.py", "python/jittor/test/test_broadcast_to_op.py", "python/jittor/test/test_models.py", "python/jittor/test/test_cub_cumsum.py" ]
[ "# ***************************************************************\n# Copyright (c) 2021 Jittor. All Rights Reserved. \n# Maintainers: \n# Guoye Yang <[email protected]>\n# Dun Liang <[email protected]>. \n# \n# This file is subject to the terms and conditions defined in\n# file 'LICENSE.txt', which is part of this source code package.\n# ***************************************************************\nimport unittest\nimport jittor as jt\nimport numpy as np\nfrom jittor import compile_extern\nfrom .test_log import find_log_with_re\nif jt.has_cuda:\n from jittor.compile_extern import cublas_ops, cudnn_ops, cub_ops\nelse:\n cublas_ops = cudnn_ops = cub_ops = None\n\ndef check_argsort(shape, dim, descending = False):\n x = jt.random(shape)\n y, y_key = jt.argsort(x, dim=dim, descending=descending)\n v = []\n for i in range(len(shape)):\n if (i == dim):\n v.append(y)\n else:\n v.append(jt.index(shape, dim=i))\n yk = jt.reindex(x, v)\n yk_ = yk.data\n y_key_ = y_key.data\n x__ = x.data\n if descending:\n x__ = -x__\n yk__ = np.sort(x__, axis=dim)\n if descending:\n yk__ = -yk__\n assert np.allclose(y_key_, yk__)\n assert np.allclose(yk_, yk__)\n\ndef check_cub_argsort(shape, dim, descending = False):\n with jt.log_capture_scope(\n log_silent=1,\n log_v=0, log_vprefix=\"op.cc=100\"\n ) as raw_log:\n x = jt.random(shape)\n y, y_key = jt.argsort(x, dim=dim, descending=descending)\n v = []\n for i in range(len(shape)):\n if (i == dim):\n v.append(y)\n else:\n v.append(jt.index(shape, dim=i))\n yk = jt.reindex(x, v)\n yk_ = yk.data\n y_key_ = y_key.data\n logs = find_log_with_re(raw_log, \"(Jit op key (not )?found: \" + \"cub_argsort\" + \".*)\")\n assert len(logs)==1\n x__ = x.data\n if descending:\n x__ = -x__\n yk__ = np.sort(x__, axis=dim)\n if descending:\n yk__ = -yk__\n assert np.allclose(y_key_, yk__)\n assert np.allclose(yk_, yk__)\n\ndef check_backward(shape, dim, descending = False):\n x = jt.random(shape)\n y, y_key = jt.argsort(x, dim=dim, descending=descending)\n loss = (y_key * y_key).sum()\n gs = jt.grad(loss, x)\n assert np.allclose(x.data*2, gs.data)\n\nclass TestArgsortOp(unittest.TestCase):\n def test(self):\n check_argsort([5,5], 0, False)\n check_argsort([5,5], 0, True)\n check_argsort([5,5], 1, False)\n check_argsort([5,5], 1, True)\n check_argsort([12, 34, 56, 78], 1, True)\n check_argsort([12, 34, 56, 78], 3, True)\n check_argsort([12, 34, 56, 78], 2, False)\n check_argsort([12, 34, 56, 78], 0, False)\n\n def test_backward(self):\n check_backward([5,5], 0, False)\n check_backward([5,5], 0, True)\n check_backward([5,5], 1, False)\n check_backward([5,5], 1, True)\n check_backward([12, 34, 56, 78], 1, True)\n check_backward([12, 34, 56, 78], 3, True)\n check_backward([12, 34, 56, 78], 2, False)\n check_backward([12, 34, 56, 78], 0, False)\n\n def test_doc(self):\n assert \"Argsort Operator\" in jt.argsort.__doc__\n\n @unittest.skipIf(cub_ops==None, \"Not use cub, Skip\")\n @jt.flag_scope(use_cuda=1)\n def test_cub(self):\n check_cub_argsort([5,5], 0, False)\n check_cub_argsort([5,5], 0, True)\n check_cub_argsort([5,5], 1, False)\n check_cub_argsort([5,5], 1, True)\n check_cub_argsort([12, 34, 56, 78], 1, True)\n check_cub_argsort([12, 34, 56, 78], 3, True)\n check_cub_argsort([12, 34, 56, 78], 2, False)\n check_cub_argsort([12, 34, 56, 78], 0, False)\n\n @unittest.skipIf(cub_ops==None, \"Not use cub, Skip\")\n @jt.flag_scope(use_cuda=1)\n def test_cub_backward(self):\n check_backward([5,5], 0, False)\n check_backward([5,5], 0, True)\n check_backward([5,5], 1, False)\n check_backward([5,5], 1, True)\n check_backward([12, 34, 56, 78], 1, True)\n check_backward([12, 34, 56, 78], 3, True)\n check_backward([12, 34, 56, 78], 2, False)\n check_backward([12, 34, 56, 78], 0, False)\n\nif __name__ == \"__main__\":\n unittest.main()", "# ***************************************************************\n# Copyright (c) 2021 Jittor. All Rights Reserved. \n# Maintainers: \n# Guowei Yang <[email protected]>\n# Guoye Yang <[email protected]>\n# Dun Liang <[email protected]>. \n# \n# This file is subject to the terms and conditions defined in\n# file 'LICENSE.txt', which is part of this source code package.\n# ***************************************************************\nimport jittor as jt\nimport numpy as np\nfrom jittor import pool\nfrom collections.abc import Sequence\n\n\ndef argmax_pool(x, size, stride, padding=0):\n return pool.pool(x, size, 'maximum', padding, stride)\n\ndef concat(arr, dim):\n '''Concat Operator can concat a list of jt Var at a specfic dimension.\n \n * [in] x: input var list for concat\n\n * [in] dim: concat which dim\n\n * [out] out: concat result\n\nExample::\n\n jt.concat([jt.array([[1],[2]]), jt.array([[2],[2]])], dim=1)\n # return [[1],[2],[2],[2]]\n '''\n # TODO: low performance when concat lots of vars\n total_dim = 0\n if dim < 0: dim += len(arr[0].shape)\n for a in arr:\n total_dim += a.shape[dim]\n cdim = 0\n s = None\n indexes = [ f\"i{i}\" for i in range(len(a.shape)) ]\n for a in arr:\n shape = list(a.shape)\n shape[dim] = total_dim\n indexes[dim] = f\"i{dim}-{cdim}\"\n b = a.reindex(shape, indexes)\n # ugly fix for preventing large fused op \n if len(arr)>=100:\n b.stop_fuse()\n if s is None:\n s = b\n else:\n s += b\n cdim += a.shape[dim]\n return s\n\ndef check(bc):\n bc = np.array(bc)\n if ((bc != 1) * (bc != bc.max(0))).sum() > 0:\n raise Exception(f\"Shape not match.\")\n else:\n return bc.max(0)\n\ndef slice_var_index(x, slices):\n if not isinstance(slices, tuple):\n slices = (slices,)\n if isinstance(slices[0], jt.Var):\n if len(slices) == 1 and slices[0].dtype == \"bool\":\n return slice_var_index(x, tuple(slices[0].where()))\n bc = []\n ml = -1\n for idx, s in enumerate(slices):\n if isinstance(s, jt.Var):\n shape = s.shape\n elif isinstance(s, np.ndarray):\n shape = list(s.shape)\n elif isinstance(s, list):\n shape = list(np.array(s).shape)\n else:\n continue\n if len(shape) >= ml:\n ml = len(shape)\n bc.append(shape)\n for idx, shape in enumerate(bc):\n if len(shape) < ml:\n shape = (ml - len(shape)) * [1] + shape\n bc[idx] = shape\n if len(bc) >= 1: \n bc_shape = check(bc)\n ss = []\n for idx, s in enumerate(slices):\n if isinstance(s, np.ndarray) or isinstance(s, list):\n ss.append(jt.array(s).broadcast(bc_shape.tolist()))\n elif isinstance(s, jt.Var):\n ss.append(s.broadcast(bc_shape.tolist()))\n else:\n ss.append(s)\n slices = ss\n out_shape = []\n out_index = []\n shape = x.shape\n cnt_list = 0\n extras_idx = []\n extras = []\n has_ellipse = 0\n ellipse_index = 0\n for s,i in zip(slices,range(len(slices))):\n if isinstance(s,type(...)):\n has_ellipse+=1\n ellipse_index = i\n if has_ellipse>1:\n raise Exception(f\"There are more than one ...\")\n elif has_ellipse==1:\n slices = list(slices)\n del slices[ellipse_index]\n while len(slices)<len(shape):\n slices.insert(ellipse_index,slice(None))\n\n for i in range(len(shape)):\n if i>=len(slices):\n s = slice(None)\n else:\n s = slices[i]\n sp = shape[i]\n j = len(out_shape)\n if isinstance(s, int):\n if s<0: s += sp\n out_index.append(str(s))\n elif isinstance(s, slice):\n if s == slice(None):\n out_shape.append(sp)\n out_index.append(f\"i{j}\")\n continue\n start = 0 if s.start is None else s.start\n stop = sp if s.stop is None else s.stop\n step = 1 if s.step is None else s.step\n if start<0: start += sp\n if stop<0: stop += sp\n if stop>sp+1: stop = sp\n out_shape.append(1+int(max(0, (stop-start-1)//step)))\n out_index.append(f\"{start}+i{j}*{step}\")\n elif isinstance(s, jt.Var):\n if cnt_list == 0:\n for idx in range(len(bc_shape)):\n extras_idx.append(f\"i{len(out_shape) + idx}\")\n out_shape += bc_shape.tolist()\n out_index.append(f\"@e{cnt_list}(\"+ \",\".join(extras_idx) + \")\")\n cnt_list += 1\n extras.append(s)\n else:\n raise Exception(f\"Not support slice {s}\")\n if len(out_shape)==0:\n out_shape = [1]\n # Stop fuse both input and output, prevent recompile\n x.stop_fuse()\n return (out_shape, out_index, 0, [], extras)\n\ndef _slice_var_old(x, slices):\n reindex_args = slice_var_index(x, slices)\n x.stop_fuse()\n return x.reindex(*reindex_args).stop_fuse()\n\ndef _setitem_old(x, slices, value):\n reindex_args = slice_var_index(x, slices)\n reindex_reduce_args = (x.shape, reindex_args[1]) + reindex_args[3:]\n xslice = x.stop_fuse().reindex(*reindex_args).stop_fuse()\n value = jt.broadcast(value, xslice)\n value = value.cast(x.dtype)\n one = jt.broadcast(1, xslice)\n if not isinstance(reindex_args[0][0], jt.Var):\n reindex_args = (x.shape,) + reindex_args[1:]\n mask = one.reindex_reduce(\"add\", *reindex_reduce_args)\n data = value.reindex_reduce(\"add\", *reindex_reduce_args)\n # Stop fuse both input and output, prevent recompile\n out = mask.ternary(data, x).stop_fuse()\n x.assign(out)\n return x\n\n# PATCH\ndef getitem(x, slices):\n if isinstance(slices, jt.Var) and slices.dtype == \"bool\":\n return getitem(x, tuple(slices.where()))\n if isinstance(slices, tuple):\n ss = []\n for s in slices:\n if isinstance(s, jt.Var) and s.dtype == \"bool\":\n ss.extend(s.where())\n else:\n ss.append(s)\n slices = tuple(ss)\n return x.getitem(slices)\n\ndef setitem(x, slices, value):\n if isinstance(slices, jt.Var) and slices.dtype == \"bool\":\n slices = tuple(slices.where())\n elif isinstance(slices, tuple):\n ss = []\n for s in slices:\n if isinstance(s, jt.Var) and s.dtype == \"bool\":\n ss.extend(s.where())\n else:\n ss.append(s)\n slices = tuple(ss)\n return x.assign(x.setitem(slices, value))\n\njt.Var.__getitem__ = jt.Var.slice_var = getitem\njt.Var.__setitem__ = setitem\n\n\ndef _merge_dtypes(dtypes):\n s = -1\n e = -1\n names = [\"bool\",\"uint\",\"int\",\"float\"]\n dbytes = [\"8\",\"16\",\"32\",\"64\"]\n for d in dtypes:\n for name in names:\n if d.startswith(name):\n s = max(s,names.index(name))\n for db in dbytes:\n if d.endswith(db):\n e = max(e,dbytes.index(db))\n assert s>=0 and s<4 and e<4\n dtype = names[s]+(\"\" if e ==-1 else dbytes[e])\n return dtype \n\ndef concat(arr, dim=0):\n '''Concat Operator can concat a list of jt Var at a specfic dimension.\n \n * [in] x: input var list for concat\n\n * [in] dim: concat which dim\n\n * return: concat result\n\nExample::\n\n jt.concat([jt.array([[1],[2]]), jt.array([[2],[2]])], dim=1)\n # return [[1],[2],[2],[2]]\n '''\n if not isinstance(arr, Sequence):\n raise TypeError(\"concat arr needs to be a tuple or list\")\n if len(arr) == 0:\n raise ValueError(\"need at least one array to concat\")\n total_dim = 0\n if dim < 0: dim += len(arr[0].shape)\n dtypes = []\n for a in arr:\n total_dim += a.shape[dim]\n dtypes.append(str(a.dtype))\n cdim = 0\n shape = list(a.shape)\n shape[dim] = total_dim\n s = jt.empty(shape, dtype = _merge_dtypes(dtypes))\n slices = [slice(None)]*len(a.shape)\n for a in arr:\n if a.shape[dim] == 0:\n continue\n slices[dim] = slice(cdim, cdim+a.shape[dim])\n # print(slices, type(a))\n s = s.setitem(tuple(slices), a)\n # s = jt.setitem(s, tuple(slices), a)\n cdim += a.shape[dim]\n return s\n", "# ***************************************************************\n# Copyright (c) 2021 Jittor. All Rights Reserved. \n# Maintainers: Dun Liang <[email protected]>. \n# This file is subject to the terms and conditions defined in\n# file 'LICENSE.txt', which is part of this source code package.\n# ***************************************************************\nimport unittest\nimport jittor as jt\nimport numpy as np\nfrom .test_core import expect_error\nfrom .test_cuda import test_cuda\nimport contextlib\n\ndef gen_data(shape):\n num = np.multiply.reduce(shape)\n a = np.arange(0, num)\n return a.reshape(shape)\n\nclass TestBroadcastToOp(unittest.TestCase):\n def setUp(self):\n self.use_shape = False\n \n def test1(self):\n def check(shape1, shape2):\n a = gen_data(shape1)\n b = gen_data(shape2)\n aa,bb = np.broadcast_arrays(a, b)\n if self.use_shape:\n ja = jt.ops.broadcast(a, shape2).data\n else:\n ja = jt.ops.broadcast_var(a, b).data\n assert ja.shape == aa.shape and (ja==aa).all(), f\"{ja}, {aa}\"\n check([1], [3])\n check([3,1], [3])\n check([3,1,3], [1,3,1])\n check([2,3,4], [2,3,4,1,1,1])\n check([2,3], [2,3,1,1])\n check([2,1,3,1,4], [1,3,4])\n \n expect_error(lambda: jt.ops.broadcast_var([1,2],[1,2,3]))\n \n def test_binary_op(self):\n if self.use_shape: return\n def check(shape1, shape2):\n a = gen_data(shape1)\n b = gen_data(shape2)\n x = y = None\n try:\n x = a+b\n except Exception as e:\n pass\n try:\n y = jt.ops.add(a, b).data\n except Exception as e:\n pass\n assert (x==y).all(), f\"{x}\\n{y}\"\n check([1], [3])\n check([3,1], [3])\n check([3,1,3], [1,3,1])\n check([2,3,4], [2,3,4,1,1,1])\n check([2,3], [2,3,1,1])\n check([2,1,3,1,4], [1,3,4])\n\nclass TestBroadcastToOpForward(unittest.TestCase):\n def test_forward(self):\n @contextlib.contextmanager\n def check(bop_num):\n jt.clean()\n yield\n graph = jt.dump_all_graphs()\n bop = [ node for node in graph.nodes_info \n if node.startswith(\"Op\") and \"broadcast_to\" in node]\n assert len(bop)==bop_num, (len(bop), bop_num)\n \n with check(1):\n a = jt.array([1,2,3])\n b = a+1\n assert (b.data==[2,3,4]).all()\n del a, b\n\n with check(0):\n a = jt.array([1,2,3])\n b = a+a\n assert (b.data==[2,4,6]).all()\n del a, b\n\n def test_shape(shape1, shape2, bop_num):\n with check(bop_num):\n a = jt.random(shape1)\n b = jt.random(shape2)\n c = a+b\n test_shape([3,3,3], [3,3,3], 0)\n test_shape([3,3,3], [3,3,1], 1)\n test_shape([3,3,3], [3,1,1], 1)\n test_shape([3,3,3], [1,1,1], 1)\n test_shape([3,3,3], [1,1,3], 1)\n test_shape([3,3,3], [1,3,3], 1)\n test_shape([3,3,1], [1,3,3], 2)\n test_shape([3,1,3], [1,3,3], 2)\n test_shape([3,3], [1,3,3], 1)\n test_shape([3,3], [1,3,1], 2)\n\n\nclass TestBroadcastToOp2(TestBroadcastToOp):\n def setUp(self):\n self.use_shape = True\n\[email protected](not jt.compiler.has_cuda, \"No CUDA found\")\nclass TestBroadcastToOpCuda(TestBroadcastToOp):\n def setUp(self):\n jt.flags.use_cuda = 2\n self.use_shape = False\n def tearDown(self):\n jt.flags.use_cuda = 0\n\[email protected](not jt.compiler.has_cuda, \"No CUDA found\")\nclass TestBroadcastToOp2Cuda(TestBroadcastToOp):\n def setUp(self):\n jt.flags.use_cuda = 2\n self.use_shape = True\n def tearDown(self):\n jt.flags.use_cuda = 0\n\n\nclass TestBroadcastToOpMisc(unittest.TestCase):\n def test_negtive_dim(self):\n a = jt.array([1,2])\n assert (a.broadcast([2,2], [-1]).data == [[1,1],[2,2]]).all()\n assert (a.broadcast([2,2], [-2]).data == [[1,2],[1,2]]).all()\n \n def test_negtive_dim2(self):\n a = jt.array([1,2])\n b = jt.zeros((2,2))\n assert (a.broadcast(b, [-1]).data == [[1,1],[2,2]]).all()\n assert (a.broadcast(b, [-2]).data == [[1,2],[1,2]]).all()\n\n def test_zero_dim(self):\n a = jt.array(1.0)\n b = a.broadcast([0])\n assert b.shape == [0]\n\n\nif __name__ == \"__main__\":\n unittest.main()", "# ***************************************************************\n# Copyright (c) 2021 Jittor. All Rights Reserved. \n# Maintainers: \n# Wenyang Zhou <[email protected]>\n# Dun Liang <[email protected]>. \n# \n# This file is subject to the terms and conditions defined in\n# file 'LICENSE.txt', which is part of this source code package.\n# ***************************************************************\nimport unittest\nimport jittor as jt\nimport numpy as np\nimport jittor.models as jtmodels\n\nskip_this_test = False\ntry:\n jt.dirty_fix_pytorch_runtime_error()\n import torch\n import torchvision.models as tcmodels\n from torch import nn\nexcept:\n torch = None\n skip_this_test = True\n\[email protected](skip_this_test, \"skip_this_test\")\nclass test_models(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n self.models = [\n 'squeezenet1_0',\n 'squeezenet1_1',\n 'alexnet',\n 'resnet18',\n 'resnet34',\n 'resnet50',\n 'resnet101',\n 'resnet152',\n 'resnext50_32x4d',\n 'resnext101_32x8d',\n 'vgg11',\n 'vgg11_bn',\n 'vgg13',\n 'vgg13_bn',\n 'vgg16',\n 'vgg16_bn',\n 'vgg19',\n 'vgg19_bn',\n 'wide_resnet50_2',\n 'wide_resnet101_2',\n 'googlenet',\n 'mobilenet_v2',\n 'mnasnet0_5',\n 'mnasnet0_75',\n 'mnasnet1_0',\n 'mnasnet1_3',\n 'shufflenet_v2_x0_5',\n 'shufflenet_v2_x1_0',\n 'shufflenet_v2_x1_5',\n 'shufflenet_v2_x2_0',\n \"densenet121\",\n \"densenet161\",\n \"densenet169\",\n 'inception_v3',\n ]\n\n @unittest.skipIf(not jt.has_cuda, \"Cuda not found\")\n @jt.flag_scope(use_cuda=1)\n def test_models(self):\n with torch.no_grad():\n self.run_models()\n\n def run_models(self):\n def to_cuda(x):\n if jt.has_cuda:\n return x.cuda()\n return x\n threshold = 1e-2\n # Define numpy input image\n bs = 1\n test_img = np.random.random((bs,3,224,224)).astype('float32')\n # test_img = np.random.random((bs,3,280,280)).astype('float32')\n # Define pytorch & jittor input image\n pytorch_test_img = to_cuda(torch.Tensor(test_img))\n jittor_test_img = jt.array(test_img)\n for test_model in self.models:\n if test_model == \"inception_v3\":\n test_img = np.random.random((bs,3,300,300)).astype('float32')\n pytorch_test_img = to_cuda(torch.Tensor(test_img))\n jittor_test_img = jt.array(test_img)\n # Define pytorch & jittor model\n pytorch_model = to_cuda(tcmodels.__dict__[test_model]())\n jittor_model = jtmodels.__dict__[test_model]()\n # Set eval to avoid dropout layer\n pytorch_model.eval()\n jittor_model.eval()\n # Jittor loads pytorch parameters to ensure forward alignment\n jittor_model.load_parameters(pytorch_model.state_dict())\n # Judge pytorch & jittor forward relative error. If the differece is lower than threshold, this test passes.\n pytorch_result = pytorch_model(pytorch_test_img)\n jittor_result = jittor_model(jittor_test_img)\n x = pytorch_result.detach().cpu().numpy() + 1\n y = jittor_result.data + 1\n relative_error = abs(x - y) / abs(y)\n diff = relative_error.mean()\n assert diff < threshold, f\"[*] {test_model} forward fails..., Relative Error: {diff}\"\n print(f\"[*] {test_model} forword passes with Relative Error {diff}\")\n jt.clean()\n jt.gc()\n torch.cuda.empty_cache()\n print('all models pass test.')\n \nif __name__ == \"__main__\":\n unittest.main()\n", "# ***************************************************************\n# Copyright (c) 2021 Jittor. All Rights Reserved. \n# Maintainers: \n# Guoye Yang <[email protected]>\n# Dun Liang <[email protected]>. \n# \n# This file is subject to the terms and conditions defined in\n# file 'LICENSE.txt', which is part of this source code package.\n# ***************************************************************\nimport unittest\nimport jittor as jt\nimport numpy as np\nfrom jittor import compile_extern\nif jt.has_cuda:\n from jittor.compile_extern import cublas_ops, cudnn_ops, cub_ops\nelse:\n cublas_ops = cudnn_ops = cub_ops = None\n\n\ndef test_forward(shape, dim=None):\n x = jt.random(shape)\n y = jt.numpy_cumsum(x)\n y_ = jt.cub_cumsum(x)\n assert(np.allclose(y.data, y_.data))\n\ndef test_backward(shape, dim=None):\n x = jt.random(shape)\n z = jt.random(shape)\n\n y = jt.numpy_cumsum(x)\n loss = (y * z).sum()\n grad = jt.grad(loss, x)\n \n y_ = jt.cub_cumsum(x)\n loss_ = (y_ * z).sum()\n grad_ = jt.grad(loss_, x)\n assert(np.allclose(grad.data, grad_.data))\n\nclass TestCubCumsumOp(unittest.TestCase):\n @unittest.skipIf(cub_ops==None, \"Not use cub, Skip\")\n @jt.flag_scope(use_cuda=1)\n def test_1d(self):\n test_forward([20])\n test_forward([3007])\n test_forward([3007], 0)\n test_forward([3007], -1)\n\n @unittest.skipIf(cub_ops==None, \"Not use cub, Skip\")\n @jt.flag_scope(use_cuda=1)\n def test_1d_backward(self):\n test_backward([20])\n test_backward([3007])\n test_backward([3007], 0)\n test_backward([3007], -1)\n\n @unittest.skipIf(cub_ops==None, \"Not use cub, Skip\")\n @jt.flag_scope(use_cuda=1)\n def test_2d(self):\n test_forward([5,5])\n test_forward([2000, 3007])\n test_forward([2000, 3007], 1)\n test_forward([2000, 3007], -1)\n\n @unittest.skipIf(cub_ops==None, \"Not use cub, Skip\")\n @jt.flag_scope(use_cuda=1)\n def test_2d_backward(self):\n test_backward([5,5])\n test_backward([2000, 3007])\n test_backward([2000, 3007], 1)\n test_backward([2000, 3007], -1)\n\n @unittest.skipIf(cub_ops==None, \"Not use cub, Skip\")\n @jt.flag_scope(use_cuda=1)\n def test_nd(self):\n test_forward([5,6,7,8], 0)\n test_forward([5,6,7,8], 1)\n test_forward([5,6,7,8], 2)\n test_forward([5,6,7,8], 3)\n test_forward([5,6,7,8], -1)\n test_forward([16,14,14,2048], 0)\n test_forward([16,14,14,2048], 1)\n test_forward([16,14,14,2048], 2)\n test_forward([16,14,14,2048], 3)\n test_forward([16,14,14,2048], -1)\n test_forward([16,14,14,2047], 3)\n\n @unittest.skipIf(cub_ops==None, \"Not use cub, Skip\")\n @jt.flag_scope(use_cuda=1)\n def test_nd_backward(self):\n test_backward([5,6,7,8], 0)\n test_backward([5,6,7,8], 1)\n test_backward([5,6,7,8], 2)\n test_backward([5,6,7,8], 3)\n test_backward([5,6,7,8], -1)\n test_backward([16,14,14,2048], 0)\n test_backward([16,14,14,2048], 1)\n test_backward([16,14,14,2048], 2)\n test_backward([16,14,14,2048], 3)\n test_backward([16,14,14,2048], -1)\n test_backward([16,14,14,2047], 3)\n\nif __name__ == \"__main__\":\n unittest.main()" ]
[ [ "numpy.allclose", "numpy.sort" ], [ "numpy.array" ], [ "numpy.multiply.reduce", "numpy.arange", "numpy.broadcast_arrays" ], [ "numpy.random.random", "torch.no_grad", "torch.cuda.empty_cache", "torch.Tensor" ], [ "numpy.allclose" ] ]
[ { "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": [] } ]
6666ev/bert_seq2seq
[ "caa9b6c5629ae5783c733aebbbcf669d8ab5dde2", "caa9b6c5629ae5783c733aebbbcf669d8ab5dde2", "caa9b6c5629ae5783c733aebbbcf669d8ab5dde2" ]
[ "examples/roberta_coarsness_NER_CRF_train.py", "my_gpt2_generate_article.py", "bert_seq2seq/basic_bert.py" ]
[ "## 粗粒度ner加crf层的例子\nimport torch\nfrom tqdm import tqdm\nimport unicodedata\nimport os\nimport time\nfrom torch.utils.data import Dataset, DataLoader\nfrom bert_seq2seq import Tokenizer, load_chinese_base_vocab\nfrom bert_seq2seq import load_bert\n\ndata_path = \"./state_dict/corase_train_update.txt\"\n\nvocab_path = \"./state_dict/roberta_wwm_vocab.txt\" # roberta模型字典的位置\nmodel_name = \"roberta\" # 选择模型名字\nmodel_path = \"./state_dict/roberta_wwm_pytorch_model.bin\" # roberta模型位置\nrecent_model_path = \"\" # 用于把已经训练好的模型继续训练\nmodel_save_path = \"./bert_粗粒度ner_crf.bin\"\nbatch_size = 4\nlr = 1e-5\n\nword2idx = load_chinese_base_vocab(vocab_path)\n\ntarget = [\"O\", \"B-LOC\", \"I-LOC\", \"B-PER\", \"I-PER\", \"B-ORG\", \"I-ORG\"]\n\ndef _is_punctuation(ch):\n \"\"\"标点符号类字符判断(全/半角均在此内)\n \"\"\"\n code = ord(ch)\n return 33 <= code <= 47 or \\\n 58 <= code <= 64 or \\\n 91 <= code <= 96 or \\\n 123 <= code <= 126 or \\\n unicodedata.category(ch).startswith('P')\n\ndef _cjk_punctuation():\n return u'\\uff02\\uff03\\uff04\\uff05\\uff06\\uff07\\uff08\\uff09\\uff0a\\uff0b\\uff0c\\uff0d\\uff0f\\uff1a\\uff1b\\uff1c\\uff1d\\uff1e\\uff20\\uff3b\\uff3c\\uff3d\\uff3e\\uff3f\\uff40\\uff5b\\uff5c\\uff5d\\uff5e\\uff5f\\uff60\\uff62\\uff63\\uff64\\u3000\\u3001\\u3003\\u3008\\u3009\\u300a\\u300b\\u300c\\u300d\\u300e\\u300f\\u3010\\u3011\\u3014\\u3015\\u3016\\u3017\\u3018\\u3019\\u301a\\u301b\\u301c\\u301d\\u301e\\u301f\\u3030\\u303e\\u303f\\u2013\\u2014\\u2018\\u2019\\u201b\\u201c\\u201d\\u201e\\u201f\\u2026\\u2027\\ufe4f\\ufe51\\ufe54\\xb7\\uff01\\uff1f\\uff61\\u3002'\n\ndef _is_cjk_character(ch):\n \"\"\"CJK类字符判断(包括中文字符也在此列)\n 参考:https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)\n \"\"\"\n code = ord(ch)\n return 0x4E00 <= code <= 0x9FFF or \\\n 0x3400 <= code <= 0x4DBF or \\\n 0x20000 <= code <= 0x2A6DF or \\\n 0x2A700 <= code <= 0x2B73F or \\\n 0x2B740 <= code <= 0x2B81F or \\\n 0x2B820 <= code <= 0x2CEAF or \\\n 0xF900 <= code <= 0xFAFF or \\\n 0x2F800 <= code <= 0x2FA1F\n\ndef _is_control(ch):\n \"\"\"控制类字符判断\n \"\"\"\n return unicodedata.category(ch) in ('Cc', 'Cf')\n\ndef word_piece_tokenize(word):\n \"\"\"word内分成subword\n \"\"\"\n if word in word2idx:\n return [word]\n tokens = []\n start, stop = 0, 0\n while start < len(word):\n stop = len(word)\n while stop > start:\n sub = word[start:stop]\n if start > 0:\n sub = '##' + sub\n if sub in word2idx:\n break\n stop -= 1\n if start == stop:\n stop += 1\n tokens.append(sub)\n start = stop\n\n return tokens\n\ndef read_corpus(data_path):\n \"\"\"\n 读原始数据\n \"\"\"\n sents_src = []\n sents_tgt = []\n\n with open(data_path, encoding=\"utf-8\") as f:\n lines = f.readlines()\n row = \"\"\n t = []\n for line in lines:\n if line == \"\\n\":\n \n if len(row) < 300: \n sents_src.append(row)\n sents_tgt.append(t)\n row = \"\"\n t = []\n continue\n line = line.split(\" \")\n row = row + line[0]\n t.append(line[1].strip(\"\\n\"))\n\n return sents_src, sents_tgt\n\n## 自定义dataset\nclass NERDataset(Dataset):\n \"\"\"\n 针对特定数据集,定义一个相关的取数据的方式\n \"\"\"\n def __init__(self, sents_src, sents_tgt) :\n ## 一般init函数是加载所有数据\n super(NERDataset, self).__init__()\n # 读原始数据\n # self.sents_src, self.sents_tgt = read_corpus(poem_corpus_dir)\n self.sents_src = sents_src\n self.sents_tgt = sents_tgt\n \n self.idx2word = {k: v for v, k in word2idx.items()}\n self.tokenizer = Tokenizer(word2idx)\n\n def __getitem__(self, i):\n ## 得到单个数据\n # print(i)\n src = self.sents_src[i]\n tgt = self.sents_tgt[i]\n tgt = [\"O\"] + tgt + [\"O\"]\n tgt = [target.index(i) for i in tgt ]\n token_ids, token_type_ids = self.tokenizer.encode(src)\n if len(token_ids) != len(tgt):\n print(\"not equal\")\n os._exit(0)\n output = {\n \"token_ids\": token_ids,\n \"token_type_ids\": token_type_ids,\n \"target_id\": tgt\n }\n return output\n\n def __len__(self):\n return len(self.sents_src)\n \ndef collate_fn(batch):\n \"\"\"\n 动态padding, batch为一部分sample\n \"\"\"\n\n def padding(indice, max_length, pad_idx=0):\n \"\"\"\n pad 函数\n \"\"\"\n pad_indice = [item + [pad_idx] * max(0, max_length - len(item)) for item in indice]\n return torch.tensor(pad_indice)\n\n\n token_ids = [data[\"token_ids\"] for data in batch]\n \n max_length = max([len(t) for t in token_ids])\n token_type_ids = [data[\"token_type_ids\"] for data in batch]\n target_ids = [data[\"target_id\"] for data in batch]\n \n token_ids_padded = padding(token_ids, max_length)\n token_type_ids_padded = padding(token_type_ids, max_length)\n target_ids_padded = padding(target_ids, max_length)\n\n return token_ids_padded, token_type_ids_padded, target_ids_padded\n\ndef viterbi_decode(nodes, trans):\n \"\"\"\n 维特比算法 解码\n nodes: (seq_len, target_size)\n trans: (target_size, target_size)\n \"\"\"\n scores = nodes[0]\n scores[1:] -= 100000 # 刚开始标签肯定是\"O\"\n target_size = nodes.shape[1]\n seq_len = nodes.shape[0]\n labels = torch.arange(0, target_size).view(1, -1)\n path = labels\n for l in range(1, seq_len):\n scores = scores.view(-1, 1)\n M = scores + trans + nodes[l].view(1, -1)\n scores, ids = M.max(0)\n path = torch.cat((path[:, ids], labels), dim=0)\n # print(scores)\n # print(scores)\n return path[:, scores.argmax()]\n\ndef ner_print(model, test_data, device=\"cpu\"):\n model.eval()\n idxtword = {v: k for k, v in word2idx.items()}\n\n tokenier = Tokenizer(word2idx)\n trans = model.state_dict()[\"crf_layer.trans\"]\n for text in test_data:\n decode = []\n text_encode, text_ids = tokenier.encode(text)\n \n text_tensor = torch.tensor(text_encode, device=device).view(1, -1)\n out = model(text_tensor).squeeze(0) # 其实是nodes\n labels = viterbi_decode(out, trans)\n starting = False\n for l in labels:\n if l > 0:\n label = target[l.item()]\n if label[0] == \"B\":\n decode.append(label[2: ])\n starting = True\n elif starting:\n decode.append(label[2: ])\n else: \n starting = False\n decode.append(\"O\")\n else :\n decode.append(\"O\")\n flag = 0\n\n res = {}\n text_decode = [idxtword[i] for i in text_encode]\n for index, each_entity in enumerate(decode):\n if each_entity != \"O\":\n if flag != each_entity:\n # cur_text = \"\".join([text[t] for t in mapping[index]])\n cur_text = text_decode[index]\n if each_entity in res.keys():\n res[each_entity].append(cur_text)\n else :\n res[each_entity] = [cur_text]\n flag = each_entity\n elif flag == each_entity:\n res[each_entity][-1] += text_decode[index]\n # res[each_entity][-1] += \"\".join([text[t] for t in mapping[index]])\n else :\n flag = 0\n print(res)\n\n\nclass Trainer:\n def __init__(self):\n # 加载数据\n \n self.sents_src, self.sents_tgt = read_corpus(data_path)\n\n self.tokenier = Tokenizer(word2idx)\n # 判断是否有可用GPU\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n print(\"device: \" + str(self.device))\n # 定义模型\n self.bert_model = load_bert(word2idx, model_name=model_name, model_class=\"sequence_labeling_crf\", target_size=len(target))\n ## 加载预训练的模型参数~\n self.bert_model.load_pretrain_params(model_path)\n # 将模型发送到计算设备(GPU或CPU)\n self.bert_model.set_device(self.device)\n # 声明需要优化的参数\n self.optim_parameters = list(self.bert_model.parameters())\n self.optimizer = torch.optim.Adam(self.optim_parameters, lr=lr, weight_decay=1e-3)\n # 声明自定义的数据加载器\n dataset = NERDataset(self.sents_src, self.sents_tgt)\n self.dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, collate_fn=collate_fn)\n\n def train(self, epoch):\n # 一个epoch的训练\n self.bert_model.train()\n self.iteration(epoch, dataloader=self.dataloader, train=True)\n \n def save(self, save_path):\n \"\"\"\n 保存模型\n \"\"\"\n self.bert_model.save_all_params(save_path)\n print(\"{} saved!\".format(save_path))\n\n def iteration(self, epoch, dataloader, train=True):\n total_loss = 0\n start_time = time.time() ## 得到当前时间\n step = 0\n for token_ids, token_type_ids, target_ids in tqdm(dataloader,position=0, leave=True):\n # print(target_ids.shape)\n step += 1\n if step % 500 == 0:\n test_data = [\"日寇在京掠夺文物详情。\", \"以书结缘,把欧美,港台流行的食品类食谱汇集一堂。\", \"明天天津下雨,不知道主任还能不能来学校吃个饭。\"]\n ner_print(self.bert_model, test_data, device=self.device)\n self.bert_model.train()\n\n # 因为传入了target标签,因此会计算loss并且返回\n predictions, loss = self.bert_model(token_ids,\n labels=target_ids \n )\n # 反向传播\n if train:\n # 清空之前的梯度\n self.optimizer.zero_grad()\n # 反向传播, 获取新的梯度\n loss.backward()\n # 用获取的梯度更新模型参数\n self.optimizer.step()\n\n # 为计算当前epoch的平均loss\n total_loss += loss.item()\n \n end_time = time.time()\n spend_time = end_time - start_time\n # 打印训练信息\n print(\"epoch is \" + str(epoch)+\". loss is \" + str(total_loss) + \". spend time is \"+ str(spend_time))\n # 保存模型\n self.save(model_save_path)\n\nif __name__ == '__main__':\n \n trainer = Trainer()\n train_epoches = 25\n for epoch in range(train_epoches):\n # 训练一个epoch\n trainer.train(epoch)\n\n # with open(\"./state_dict/corase_train_update.txt\", \"a+\") as f:\n # with open(\"./corpus/粗粒度NER/人民日报ner数据.txt\", \"r\", encoding=\"utf-8\") as f1 :\n # lines = f1.readlines()\n # start = 1\n # string = \"\"\n # label = \"\"\n # for line in lines:\n # if line == \"\\n\":\n # f.write(\"\\n\")\n # continue\n # line = line.strip(\"\\n\")\n # line = line.split(\" \")\n # if _is_punctuation(line[0]) or _is_cjk_character(line[0]):\n # if string != \"\":\n # string = string.lower()\n # tokens = word_piece_tokenize(string) # 子词\n # for t in tokens:\n # if \"##\" in t:\n # f.write(t[2:] + \" \" + label + \"\\n\")\n # else :\n # f.write(t + \" \" + label + \"\\n\")\n # # f.write(string + \" \" + label + \"\\n\")\n # string = \"\"\n # label = \"\"\n # f.write(line[0] + \" \" + line[1] + \"\\n\")\n # else :\n # string += line[0]\n # label = line[1]", "## gpt2 进行文言文翻译\nfrom torch.utils import data\nfrom bert_seq2seq import load_gpt, tokenizer\nimport torch\nfrom tqdm import tqdm\nimport os \nimport time\nimport glob\nfrom torch.utils.data import Dataset, DataLoader\nfrom bert_seq2seq import Tokenizer, load_chinese_base_vocab\n\n\nvocab_path = \"./state_dict/gpt2/vocab.txt\"\nmodel_path = \"./state_dict/gpt2/pytorch_model.bin\"\n\nmodel_save_path = \"./state_dict/gpt2_article_gen.bin\"\nbatch_size = 2\nlr = 2e-5\nword2idx = load_chinese_base_vocab(vocab_path)\n\n\n\ndata_path = glob.glob(\"data/THUCNews/THUCNews/*/*.txt\")\n\n\nclass SeqDataset(Dataset):\n \"\"\"\n 针对特定数据集,定义一个相关的取数据的方式\n \"\"\"\n\n def __init__(self):\n ## 一般init函数是加载所有数据\n super(SeqDataset, self).__init__()\n # 读原始数据\n self.idx2word = {k: v for v, k in word2idx.items()}\n self.tokenizer = Tokenizer(word2idx)\n\n def __getitem__(self, i):\n ## 得到单个数据\n file_path = data_path[i]\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n lines = f.readlines()\n title = lines[0].strip(\"\\n\")\n content = lines[1:]\n content = \"\".join(content)\n content = content.replace(\"\\n\", \"&\").replace(\"  \", \"\").replace(\"&&\", \"\").replace(\"”\", \"\").replace(\"“\", \"\")\n content = content.split(\"&\")\n cons_text = \"\"\n index = 0\n while len(cons_text) < 900 and index < len(content):\n cons_text += content[index] + \"&\"\n index += 1\n # print(title)\n # print(cons_text)\n # # print(content)328\n if len(title) + len(content) > 1024:\n if i == 0:\n return self.__getitem__(i + 1)\n else :\n return self.__getitem__(i - 1)\n \n if len(cons_text) == 0:\n if i == 0:\n return self.__getitem__(i + 1)\n else :\n return self.__getitem__(i - 1)\n\n token_ids, _ = self.tokenizer.encode(title + \"&\" + cons_text, max_length=1000)\n \n output = {\n \"token_ids\": token_ids,\n }\n \n return output\n\n def __len__(self):\n return len(data_path)\n\n\n\ndef collate_fn(batch):\n \"\"\"\n 动态padding, batch为一部分sample\n \"\"\"\n\n def padding(indice, max_length, pad_idx=0):\n \"\"\"\n pad 函数\n \"\"\"\n pad_indice = [item + [pad_idx] * max(0, max_length - len(item)) for item in indice]\n return torch.tensor(pad_indice)\n\n token_ids = [data[\"token_ids\"] for data in batch]\n max_length = max([len(t) for t in token_ids])\n\n token_ids_padded = padding(token_ids, max_length)\n target_ids_padded = token_ids_padded.clone()\n target_ids_padded[target_ids_padded == 0] = -100\n\n return token_ids_padded, target_ids_padded\n\n\nclass Trainer:\n def __init__(self):\n # 加载数据\n # 判断是否有可用GPU\n self.device = torch.device(\"cuda:1\" if torch.cuda.is_available() else \"cpu\")\n print(\"device: \" + str(self.device))\n # 定义模型\n # self.gpt_model = AutoModelWithLMHead.from_pretrained(model_path)\n # self.gpt_model.to(self.device)\n # self.gpt_model = transformers.modeling_gpt2.GPT2LMHeadModel.from_pretrained(model_path)\n self.gpt_model = load_gpt(word2idx)\n ## 加载预训练的模型参数~\n self.gpt_model.load_pretrain_params(model_path)\n # 将模型发送到计算设备(GPU或CPU)\n self.gpt_model.set_device(self.device)\n # 声明需要优化的参数\n self.optim_parameters = list(self.gpt_model.parameters())\n self.optimizer = torch.optim.Adam(self.optim_parameters, lr=lr, weight_decay=1e-5)\n # 声明自定义的数据加载器\n dataset = SeqDataset()\n self.dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, collate_fn=collate_fn)\n\n def train(self, epoch):\n # 一个epoch的训练\n self.gpt_model.train()\n self.iteration(epoch, dataloader=self.dataloader, train=True)\n\n def save(self, save_path):\n \"\"\"\n 保存模型\n \"\"\"\n self.gpt_model.save_all_params(save_path)\n print(\"{} saved!\".format(save_path))\n\n def iteration(self, epoch, dataloader, train=True):\n total_loss = 0\n report_loss = 0\n start_time = time.time() ## 得到当前时间\n step = 0\n for token_ids, target_ids in tqdm(dataloader, total=len(dataloader)):\n # for token_ids, target_ids in tqdm(dataloader:\n step += 1\n \n if step % 10 == 0:\n print(f\"epoch is {epoch}\")\n self.gpt_model.eval()\n # self.gpt_model.to(torch.device(\"cpu\"))\n # text_generator = TextGenerationPipeline(self.gpt_model, tokenizer) \n test_data = [\"尚品宅配:家具定制模范生。\", \"今天的天气还不错。\", \"受双十一影响,阿里巴巴股票今天大涨。\"]\n for text in test_data:\n # out = text_generator(text, max_length=300, do_sample=True)\n # print(out)\n print(self.gpt_model.sample_generate(text, add_eos=False, top_k=10, out_max_length=900, top_p=0.7, temperature=3.0, repetition_penalty=1.5))\n self.gpt_model.train()\n # self.gpt_model.to(self.device)\n print(\"report loss is \" + str(report_loss))\n report_loss = 0.0\n self.gpt_model.save_all_params(model_save_path)\n print(\"模型保存完毕\")\n\n # 因为传入了target标签,因此会计算loss并且返回\n loss, _ = self.gpt_model(token_ids,\n labels=target_ids,\n )\n # 反向传播\n if train:\n # 清空之前的梯度\n self.optimizer.zero_grad()\n # 反向传播, 获取新的梯度\n loss.backward()\n # 用获取的梯度更新模型参数\n self.optimizer.step()\n\n # 为计算当前epoch的平均loss\n total_loss += loss.item()\n report_loss += loss.item()\n\n end_time = time.time()\n spend_time = end_time - start_time\n # 打印训练信息\n print(\"epoch is \" + str(epoch) + \". loss is \" + str(total_loss) + \". spend time is \" + str(spend_time))\n # 保存模型\n self.save(model_save_path)\n\n\nif __name__ == '__main__':\n\n trainer = Trainer()\n train_epoches = 5\n for epoch in range(train_epoches):\n # 训练一个epoch\n trainer.train(epoch)\n", "\nimport torch\nimport torch.nn as nn\nfrom bert_seq2seq.tokenizer import Tokenizer\n \ndef get_model(model_name, word2ix):\n if model_name == \"roberta\":\n from bert_seq2seq.model.roberta_model import BertModel, BertConfig, BertLayerNorm, BertPredictionHeadTransform,BertLMPredictionHead, CLS\n config = BertConfig(vocab_size=len(word2ix))\n bert = BertModel(config)\n layer_norm_cond = BertLayerNorm(config.hidden_size, conditional=True)\n\n CLS = CLS(config)\n\n elif model_name == \"bert\":\n from bert_seq2seq.model.bert_model import BertConfig, BertModel, BertLayerNorm, BertPredictionHeadTransform,BertLMPredictionHead,CLS\n config = BertConfig(vocab_size=len(word2ix))\n bert = BertModel(config)\n layer_norm_cond = BertLayerNorm(config.hidden_size, conditional=True)\n CLS = CLS(config)\n\n elif model_name == \"nezha\":\n from bert_seq2seq.model.nezha_model import BertConfig, BertModel, BertLayerNorm, BertPredictionHeadTransform,BertLMPredictionHead,CLS\n config = BertConfig(vocab_size=len(word2ix))\n bert = BertModel(config)\n layer_norm_cond = BertLayerNorm(config.hidden_size, conditional=True)\n CLS = CLS(config)\n\n elif model_name == \"roberta-large\":\n from bert_seq2seq.model.roberta_model import BertModel, RobertaLargeConfig, BertLayerNorm, BertPredictionHeadTransform,BertLMPredictionHead, CLS\n config = RobertaLargeConfig(vocab_size=len(word2ix))\n bert = BertModel(config)\n layer_norm_cond = BertLayerNorm(config.hidden_size, conditional=True)\n CLS = CLS(config)\n \n else:\n raise Exception(\"model_name_err\")\n\n return config, bert, layer_norm_cond, CLS\n\nclass BasicBert(nn.Module):\n def __init__(self, word2ix, model_name=\"roberta\", tokenizer=None):\n super().__init__()\n self.config = \"\"\n self.word2ix = word2ix\n\n if tokenizer is None:\n self.tokenizer = Tokenizer(word2ix)\n else:\n self.tokenizer = tokenizer\n\n self.model_name = model_name\n \n self.config, self.bert, self.layer_norm_cond, self.cls = get_model(model_name, word2ix)\n \n self.device = torch.device(\"cpu\")\n\n def load_pretrain_params(self, pretrain_model_path, keep_tokens=None, strict=False):\n checkpoint = torch.load(pretrain_model_path, map_location=self.device)\n\n checkpoint = {k: v for k, v in checkpoint.items()\n }\n if keep_tokens is not None:\n ## 说明精简词表了,embeedding层也要过滤下\n embedding_weight_name = \"bert.embeddings.word_embeddings.weight\"\n cls_pre_weight = \"cls.predictions.decoder.weight\"\n cls_pre_bias = \"cls.predictions.bias\"\n checkpoint[embedding_weight_name] = checkpoint[embedding_weight_name][keep_tokens]\n checkpoint[cls_pre_weight] = checkpoint[cls_pre_weight][keep_tokens]\n checkpoint[cls_pre_bias] = checkpoint[cls_pre_bias][keep_tokens]\n \n self.load_state_dict(checkpoint, strict=strict)\n torch.cuda.empty_cache()\n print(\"{} loaded!\".format(pretrain_model_path))\n\n def load_all_params(self, model_path, device=\"cuda\"):\n\n checkpoint = torch.load(model_path, map_location=device)\n self.load_state_dict(checkpoint, strict=False)\n torch.cuda.empty_cache()\n print(str(model_path) + \" loaded!\")\n\n def forward(self, input_text):\n ## 返回bert编码后得到的向量\n input_ids, _ = self.tokenizer.encode(input_text, max_length=512)\n input_ids = torch.tensor(input_ids, dtype=torch.long, device=self.device).view(1, -1)\n\n enc_layers, _ = self.bert(input_ids, position_ids=None, token_type_ids=None, \n output_all_encoded_layers=True)\n squence_out = enc_layers[-1] ## 取出来最后一层输出 (batch, seq_len, 768)\n\n tokens_hidden_state, _ = self.cls(squence_out)\n\n return tokens_hidden_state\n\n def set_device(self, device):\n self.device = torch.device(device)\n self.to(device)\n \n def save_all_params(self, save_path):\n if self.model_name == \"nezha\":\n # 不要保存相对位置编码权重\n checkpoints = {k: v for k, v in self.state_dict().items()\n if \"relative\" not in k}\n torch.save(checkpoints, save_path)\n return\n torch.save(self.state_dict(), save_path)\n\nclass BasicGPT(nn.Module):\n def __init__(self):\n super().__init__()\n self.device = torch.device(\"cpu\")\n\n def load_pretrain_params(self, pretrain_model_path):\n checkpoint = torch.load(pretrain_model_path, map_location=self.device)\n checkpoint = {\"model.\" + k: v for k, v in checkpoint.items()}\n\n self.load_state_dict(checkpoint, strict=True)\n torch.cuda.empty_cache()\n print(\"{} loaded!\".format(pretrain_model_path))\n\n def load_all_params(self, model_path, device=\"cuda\"):\n checkpoint = torch.load(model_path, map_location=device)\n self.load_state_dict(checkpoint, strict=False)\n torch.cuda.empty_cache()\n print(str(model_path) + \" loaded!\")\n\n def forward(self, x):\n raise NotImplemented\n\n def set_device(self, device):\n self.device = torch.device(device)\n self.to(device)\n \n def save_all_params(self, save_path):\n torch.save(self.state_dict(), save_path)\n\n\nclass BasicT5(nn.Module):\n def __init__(self):\n super().__init__()\n self.device = torch.device(\"cpu\")\n\n def load_pretrain_params(self, pretrain_model_path):\n checkpoint = torch.load(pretrain_model_path, map_location=self.device)\n checkpoint = {\"model.\" + k: v for k, v in checkpoint.items()}\n\n self.load_state_dict(checkpoint, strict=True)\n torch.cuda.empty_cache()\n print(\"{} loaded!\".format(pretrain_model_path))\n\n def load_all_params(self, model_path, device=\"cuda\"):\n checkpoint = torch.load(model_path, map_location=device)\n self.load_state_dict(checkpoint, strict=False)\n torch.cuda.empty_cache()\n print(str(model_path) + \" loaded!\")\n\n def forward(self, x):\n raise NotImplemented\n\n def set_device(self, device):\n self.device = torch.device(device)\n self.to(device)\n\n def save_all_params(self, save_path):\n torch.save(self.state_dict(), save_path)\n\nclass BasicBart(nn.Module):\n def __init__(self):\n super().__init__()\n self.device = torch.device(\"cpu\")\n\n def load_pretrain_params(self, pretrain_model_path):\n checkpoint = torch.load(pretrain_model_path, map_location=self.device)\n checkpoint = {\"model.\" + k: v for k, v in checkpoint.items()}\n\n self.load_state_dict(checkpoint, strict=False)\n torch.cuda.empty_cache()\n print(\"{} loaded!\".format(pretrain_model_path))\n\n def load_all_params(self, model_path, device=\"cuda\"):\n checkpoint = torch.load(model_path, map_location=device)\n self.load_state_dict(checkpoint, strict=False)\n torch.cuda.empty_cache()\n print(str(model_path) + \" loaded!\")\n\n def forward(self, x):\n raise NotImplemented\n\n def set_device(self, device):\n self.device = torch.device(device)\n self.to(device)\n\n def save_all_params(self, save_path):\n torch.save(self.state_dict(), save_path)\n\n" ]
[ [ "torch.optim.Adam", "torch.cat", "torch.utils.data.DataLoader", "torch.tensor", "torch.cuda.is_available", "torch.arange" ], [ "torch.optim.Adam", "torch.utils.data.DataLoader", "torch.cuda.is_available", "torch.tensor" ], [ "torch.load", "torch.cuda.empty_cache", "torch.tensor", "torch.device", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
panaali/qubovert
[ "d5ea46349d2a058954fb2cb06f559c0d3fb382c5" ]
[ "tests/problems/np/test_graphpartitioning.py" ]
[ "# Copyright 2020 Joseph T. Iosue\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\"\"\"\nContains tests for the GraphPartitioning class.\n\"\"\"\n\nfrom qubovert.problems import GraphPartitioning\nfrom qubovert.utils import (\n solve_qubo_bruteforce, solve_quso_bruteforce,\n solve_pubo_bruteforce, solve_puso_bruteforce\n)\nfrom numpy import allclose\n\n\nedges = {(\"a\", \"b\"), (\"a\", \"c\"), (\"c\", \"d\"),\n (\"b\", \"c\"), (\"e\", \"f\"), (\"d\", \"e\")}\nproblem = GraphPartitioning(edges)\nsolutions = (\n ({\"a\", \"b\", \"c\"}, {\"d\", \"e\", \"f\"}),\n ({\"d\", \"e\", \"f\"}, {\"a\", \"b\", \"c\"})\n)\n\nproblem_weighted = GraphPartitioning({(0, 1): 1, (1, 2): 3, (0, 3): 1})\nsolutions_weighted = (\n ({0, 3}, {1, 2}),\n ({1, 2}, {0, 3})\n)\n\n\ndef test_graphpartitioning_str():\n\n assert eval(str(problem)) == problem\n\n\ndef test_graphpartitioning_properties():\n\n assert problem.E == edges\n problem.V\n problem.degree\n problem.weights\n\n\ndef test_graphpartitioning_bruteforce():\n\n assert problem.solve_bruteforce() in solutions\n assert (\n problem.solve_bruteforce(all_solutions=True) in\n (list(solutions), list(reversed(solutions)))\n )\n\n\n# QUBO\n\ndef test_graphpartitioning_qubo_solve():\n\n e, sol = solve_qubo_bruteforce(problem.to_qubo())\n solution = problem.convert_solution(sol)\n\n assert solution in solutions\n assert problem.is_solution_valid(solution)\n assert problem.is_solution_valid(sol)\n assert allclose(e, 1)\n\n e, sol = solve_qubo_bruteforce(problem.to_qubo(10))\n solution = problem.convert_solution(sol)\n\n assert solution in solutions\n assert problem.is_solution_valid(solution)\n assert problem.is_solution_valid(sol)\n assert allclose(e, 1)\n\n e, sol = solve_qubo_bruteforce(problem_weighted.to_qubo())\n solution = problem_weighted.convert_solution(sol)\n assert solution == problem_weighted.convert_solution(\n [sol[i] for i in range(problem_weighted.num_binary_variables)]\n )\n\n assert solution in solutions_weighted\n assert problem_weighted.is_solution_valid(solution)\n assert problem_weighted.is_solution_valid(sol)\n assert allclose(e, 1)\n\n\ndef test_graphpartitioning_qubo_numvars():\n\n Q = problem.to_qubo()\n assert (\n len(set(y for x in Q for y in x)) ==\n problem.num_binary_variables ==\n Q.num_binary_variables\n )\n\n\n# quso\n\ndef test_graphpartitioning_quso_solve():\n\n e, sol = solve_quso_bruteforce(problem.to_quso())\n solution = problem.convert_solution(sol)\n\n assert solution in solutions\n assert problem.is_solution_valid(solution)\n assert problem.is_solution_valid(sol)\n assert allclose(e, 1)\n\n e, sol = solve_quso_bruteforce(problem_weighted.to_quso())\n solution = problem_weighted.convert_solution(sol)\n\n assert solution in solutions_weighted\n assert problem_weighted.is_solution_valid(solution)\n assert problem_weighted.is_solution_valid(sol)\n assert allclose(e, 1)\n\n\ndef test_graphpartitioning_quso_numvars():\n\n L = problem.to_quso()\n assert L.num_binary_variables == problem.num_binary_variables\n\n\n# PUBO\n\ndef test_graphpartitioning_pubo_solve():\n\n e, sol = solve_pubo_bruteforce(problem.to_pubo())\n solution = problem.convert_solution(sol)\n\n assert solution in solutions\n assert problem.is_solution_valid(solution)\n assert problem.is_solution_valid(sol)\n assert allclose(e, 1)\n\n e, sol = solve_pubo_bruteforce(problem_weighted.to_pubo())\n solution = problem_weighted.convert_solution(sol)\n\n assert solution in solutions_weighted\n assert problem_weighted.is_solution_valid(solution)\n assert problem_weighted.is_solution_valid(sol)\n assert allclose(e, 1)\n\n\n# puso\n\ndef test_graphpartitioning_puso_solve():\n\n e, sol = solve_puso_bruteforce(problem.to_puso())\n solution = problem.convert_solution(sol)\n\n assert solution in solutions\n assert problem.is_solution_valid(solution)\n assert problem.is_solution_valid(sol)\n assert allclose(e, 1)\n\n e, sol = solve_puso_bruteforce(problem_weighted.to_puso())\n solution = problem_weighted.convert_solution(sol)\n\n assert solution in solutions_weighted\n assert problem_weighted.is_solution_valid(solution)\n assert problem_weighted.is_solution_valid(sol)\n assert allclose(e, 1)\n" ]
[ [ "numpy.allclose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
JackKelly/Geocode
[ "b3cc89c7467384e41c5be6bcd80b36271cfc252c" ]
[ "geocode/latlons2llsoa.py" ]
[ "#!/usr/bin/env python3\n\"\"\"\nLoad a list of lat/lons from a CSV file and reverse-geocode them to LLSOA.\n\n- Jamie Taylor <[email protected]>\n- First Authored: 2020-04-16\n\"\"\"\n\nimport sys\nimport os\nimport argparse\nimport time as TIME\nimport pandas as pd\n\nfrom geocode import Geocoder, query_yes_no\n\ndef parse_options():\n \"\"\"Parse command line options.\"\"\"\n parser = argparse.ArgumentParser(description=(\"This is a command line interface (CLI) for \"\n \"the latlons2llsoa.py module\"),\n epilog=\"Jamie Taylor, 2020-04-16\")\n parser.add_argument(\"-f\", \"--input-file\", dest=\"infile\", action=\"store\", type=str,\n required=True, metavar=\"</path/to/file>\",\n help=\"Specify a CSV file containing a list of latitudes and longitudes to \"\n \"be reverse-geocoded. The file must contain the columns 'latitude' \"\n \"and 'longitude' (it can contain others, all of which will be kept).\")\n parser.add_argument(\"-o\", \"--output-file\", dest=\"outfile\", action=\"store\", type=str,\n required=True, metavar=\"</path/to/file>\", help=\"Specify an output file.\")\n parser.add_argument(\"--datazones\", dest=\"datazones\", action=\"store_true\",\n required=False, help=\"Specify to use Data Zones in Scotland.\")\n options = parser.parse_args()\n if not os.path.isfile(options.infile):\n raise Exception(f\"The input file '{options.infile}' does not exist.\")\n if os.path.isfile(options.outfile):\n check = query_yes_no(f\"The outfile '{options.outfile}' already exists, are you sure you \"\n \"wish to overwrite?\", \"no\")\n if not check:\n print(\"Quitting...\")\n sys.exit(0)\n return options\n\ndef main():\n timerstart = TIME.time()\n options = parse_options()\n with open(options.infile, \"r\") as fid:\n df = pd.read_csv(fid)\n with Geocoder(progress_bar=True) as geo:\n # import pdb; pdb.set_trace()\n df[\"llsoacd\"] = geo.reverse_geocode_llsoa(df[[\"latitude\", \"longitude\"]].to_numpy(),\n options.datazones)\n df.to_csv(options.outfile, index=False)\n print(f\"Finished, time taken: {TIME.time() - timerstart} seconds\")\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
Ishticode/kornia
[ "974abb43ec72d12dbd244a2fb247bbbab8498de0", "974abb43ec72d12dbd244a2fb247bbbab8498de0", "974abb43ec72d12dbd244a2fb247bbbab8498de0", "974abb43ec72d12dbd244a2fb247bbbab8498de0", "974abb43ec72d12dbd244a2fb247bbbab8498de0", "974abb43ec72d12dbd244a2fb247bbbab8498de0", "974abb43ec72d12dbd244a2fb247bbbab8498de0" ]
[ "kornia/enhance/histogram.py", "kornia/contrib/face_detection.py", "docs/source/_static/image_registration.py", "test/filters/test_unsharp_mask.py", "test/feature/test_mkd.py", "kornia/geometry/linalg.py", "kornia/augmentation/random_generator/_2d/affine.py" ]
[ "from typing import Optional, Tuple\n\nimport torch\n\n\ndef marginal_pdf(\n values: torch.Tensor, bins: torch.Tensor, sigma: torch.Tensor, epsilon: float = 1e-10\n) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Calculate the marginal probability distribution function of the input tensor based on the number of\n histogram bins.\n\n Args:\n values: shape [BxNx1].\n bins: shape [NUM_BINS].\n sigma: shape [1], gaussian smoothing factor.\n epsilon: scalar, for numerical stability.\n\n Returns:\n Tuple[torch.Tensor, torch.Tensor]:\n - torch.Tensor: shape [BxN].\n - torch.Tensor: shape [BxNxNUM_BINS].\n \"\"\"\n\n if not isinstance(values, torch.Tensor):\n raise TypeError(f\"Input values type is not a torch.Tensor. Got {type(values)}\")\n\n if not isinstance(bins, torch.Tensor):\n raise TypeError(f\"Input bins type is not a torch.Tensor. Got {type(bins)}\")\n\n if not isinstance(sigma, torch.Tensor):\n raise TypeError(f\"Input sigma type is not a torch.Tensor. Got {type(sigma)}\")\n\n if not values.dim() == 3:\n raise ValueError(\"Input values must be a of the shape BxNx1.\" \" Got {}\".format(values.shape))\n\n if not bins.dim() == 1:\n raise ValueError(\"Input bins must be a of the shape NUM_BINS\" \" Got {}\".format(bins.shape))\n\n if not sigma.dim() == 0:\n raise ValueError(\"Input sigma must be a of the shape 1\" \" Got {}\".format(sigma.shape))\n\n residuals = values - bins.unsqueeze(0).unsqueeze(0)\n kernel_values = torch.exp(-0.5 * (residuals / sigma).pow(2))\n\n pdf = torch.mean(kernel_values, dim=1)\n normalization = torch.sum(pdf, dim=1).unsqueeze(1) + epsilon\n pdf = pdf / normalization\n\n return pdf, kernel_values\n\n\ndef joint_pdf(kernel_values1: torch.Tensor, kernel_values2: torch.Tensor, epsilon: float = 1e-10) -> torch.Tensor:\n \"\"\"Calculate the joint probability distribution function of the input tensors based on the number of histogram\n bins.\n\n Args:\n kernel_values1: shape [BxNxNUM_BINS].\n kernel_values2: shape [BxNxNUM_BINS].\n epsilon: scalar, for numerical stability.\n\n Returns:\n shape [BxNUM_BINSxNUM_BINS].\n \"\"\"\n\n if not isinstance(kernel_values1, torch.Tensor):\n raise TypeError(f\"Input kernel_values1 type is not a torch.Tensor. Got {type(kernel_values1)}\")\n\n if not isinstance(kernel_values2, torch.Tensor):\n raise TypeError(f\"Input kernel_values2 type is not a torch.Tensor. Got {type(kernel_values2)}\")\n\n if not kernel_values1.dim() == 3:\n raise ValueError(\"Input kernel_values1 must be a of the shape BxN.\" \" Got {}\".format(kernel_values1.shape))\n\n if not kernel_values2.dim() == 3:\n raise ValueError(\"Input kernel_values2 must be a of the shape BxN.\" \" Got {}\".format(kernel_values2.shape))\n\n if kernel_values1.shape != kernel_values2.shape:\n raise ValueError(\n \"Inputs kernel_values1 and kernel_values2 must have the same shape.\"\n \" Got {} and {}\".format(kernel_values1.shape, kernel_values2.shape)\n )\n\n joint_kernel_values = torch.matmul(kernel_values1.transpose(1, 2), kernel_values2)\n normalization = torch.sum(joint_kernel_values, dim=(1, 2)).view(-1, 1, 1) + epsilon\n pdf = joint_kernel_values / normalization\n\n return pdf\n\n\ndef histogram(x: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsilon: float = 1e-10) -> torch.Tensor:\n \"\"\"Estimate the histogram of the input tensor.\n\n The calculation uses kernel density estimation which requires a bandwidth (smoothing) parameter.\n\n Args:\n x: Input tensor to compute the histogram with shape :math:`(B, D)`.\n bins: The number of bins to use the histogram :math:`(N_{bins})`.\n bandwidth: Gaussian smoothing factor with shape shape [1].\n epsilon: A scalar, for numerical stability.\n\n Returns:\n Computed histogram of shape :math:`(B, N_{bins})`.\n\n Examples:\n >>> x = torch.rand(1, 10)\n >>> bins = torch.torch.linspace(0, 255, 128)\n >>> hist = histogram(x, bins, bandwidth=torch.tensor(0.9))\n >>> hist.shape\n torch.Size([1, 128])\n \"\"\"\n\n pdf, _ = marginal_pdf(x.unsqueeze(2), bins, bandwidth, epsilon)\n\n return pdf\n\n\ndef histogram2d(\n x1: torch.Tensor, x2: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsilon: float = 1e-10\n) -> torch.Tensor:\n \"\"\"Estimate the 2d histogram of the input tensor.\n\n The calculation uses kernel density estimation which requires a bandwidth (smoothing) parameter.\n\n Args:\n x1: Input tensor to compute the histogram with shape :math:`(B, D1)`.\n x2: Input tensor to compute the histogram with shape :math:`(B, D2)`.\n bins: The number of bins to use the histogram :math:`(N_{bins})`.\n bandwidth: Gaussian smoothing factor with shape shape [1].\n epsilon: A scalar, for numerical stability. Default: 1e-10.\n\n Returns:\n Computed histogram of shape :math:`(B, N_{bins}), N_{bins})`.\n\n Examples:\n >>> x1 = torch.rand(2, 32)\n >>> x2 = torch.rand(2, 32)\n >>> bins = torch.torch.linspace(0, 255, 128)\n >>> hist = histogram2d(x1, x2, bins, bandwidth=torch.tensor(0.9))\n >>> hist.shape\n torch.Size([2, 128, 128])\n \"\"\"\n\n _, kernel_values1 = marginal_pdf(x1.unsqueeze(2), bins, bandwidth, epsilon)\n _, kernel_values2 = marginal_pdf(x2.unsqueeze(2), bins, bandwidth, epsilon)\n\n pdf = joint_pdf(kernel_values1, kernel_values2)\n\n return pdf\n\n\ndef image_histogram2d(\n image: torch.Tensor,\n min: float = 0.0,\n max: float = 255.0,\n n_bins: int = 256,\n bandwidth: Optional[float] = None,\n centers: Optional[torch.Tensor] = None,\n return_pdf: bool = False,\n kernel: str = \"triangular\",\n eps: float = 1e-10,\n) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Estimate the histogram of the input image(s).\n\n The calculation uses triangular kernel density estimation.\n\n Args:\n image: Input tensor to compute the histogram with shape\n :math:`(H, W)`, :math:`(C, H, W)` or :math:`(B, C, H, W)`.\n min: Lower end of the interval (inclusive).\n max: Upper end of the interval (inclusive). Ignored when\n :attr:`centers` is specified.\n n_bins: The number of histogram bins. Ignored when\n :attr:`centers` is specified.\n bandwidth: Smoothing factor. If not specified or equal to -1,\n :math:`(bandwidth = (max - min) / n_bins)`.\n centers: Centers of the bins with shape :math:`(n_bins,)`.\n If not specified or empty, it is calculated as centers of\n equal width bins of [min, max] range.\n return_pdf: If True, also return probability densities for\n each bin.\n kernel: kernel to perform kernel density estimation\n ``(`triangular`, `gaussian`, `uniform`, `epanechnikov`)``.\n\n Returns:\n Computed histogram of shape :math:`(bins)`, :math:`(C, bins)`,\n :math:`(B, C, bins)`.\n Computed probability densities of shape :math:`(bins)`, :math:`(C, bins)`,\n :math:`(B, C, bins)`, if return_pdf is ``True``. Tensor of zeros with shape\n of the histogram otherwise.\n \"\"\"\n if image is not None and not isinstance(image, torch.Tensor):\n raise TypeError(f\"Input image type is not a torch.Tensor. Got {type(image)}.\")\n\n if centers is not None and not isinstance(centers, torch.Tensor):\n raise TypeError(f\"Bins' centers type is not a torch.Tensor. Got {type(centers)}.\")\n\n if centers is not None and len(centers.shape) > 0 and centers.dim() != 1:\n raise ValueError(f\"Bins' centers must be a torch.Tensor of the shape (n_bins,). Got {centers.shape}.\")\n\n if not isinstance(min, float):\n raise TypeError(f'Type of lower end of the range is not a float. Got {type(min)}.')\n\n if not isinstance(max, float):\n raise TypeError(f\"Type of upper end of the range is not a float. Got {type(min)}.\")\n\n if not isinstance(n_bins, int):\n raise TypeError(f\"Type of number of bins is not an int. Got {type(n_bins)}.\")\n\n if bandwidth is not None and not isinstance(bandwidth, float):\n raise TypeError(f\"Bandwidth type is not a float. Got {type(bandwidth)}.\")\n\n if not isinstance(return_pdf, bool):\n raise TypeError(f\"Return_pdf type is not a bool. Got {type(return_pdf)}.\")\n\n if bandwidth is None:\n bandwidth = (max - min) / n_bins\n\n if centers is None:\n centers = min + bandwidth * (torch.arange(n_bins, device=image.device, dtype=image.dtype) + 0.5)\n centers = centers.reshape(-1, 1, 1, 1, 1)\n\n u = torch.abs(image.unsqueeze(0) - centers) / bandwidth\n\n if kernel == \"gaussian\":\n kernel_values = torch.exp(-0.5 * u ** 2)\n elif kernel in (\"triangular\", \"uniform\", \"epanechnikov\",):\n # compute the mask and cast to floating point\n mask = (u <= 1).to(u.dtype)\n if kernel == \"triangular\":\n kernel_values = (1. - u) * mask\n elif kernel == \"uniform\":\n kernel_values = torch.ones_like(u) * mask\n else: # kernel == \"epanechnikov\"\n kernel_values = (1. - u ** 2) * mask\n else:\n raise ValueError(f\"Kernel must be 'triangular', 'gaussian', \" f\"'uniform' or 'epanechnikov'. Got {kernel}.\")\n\n hist = torch.sum(kernel_values, dim=(-2, -1)).permute(1, 2, 0)\n\n if return_pdf:\n normalization = torch.sum(hist, dim=-1, keepdim=True) + eps\n pdf = hist / normalization\n if image.dim() == 2:\n hist = hist.squeeze()\n pdf = pdf.squeeze()\n elif image.dim() == 3:\n hist = hist.squeeze(0)\n pdf = pdf.squeeze(0)\n return hist, pdf\n\n if image.dim() == 2:\n hist = hist.squeeze()\n elif image.dim() == 3:\n hist = hist.squeeze(0)\n\n return hist, torch.zeros_like(hist)\n", "# based on: https://github.com/ShiqiYu/libfacedetection.train/blob/74f3aa77c63234dd954d21286e9a60703b8d0868/tasks/task1/yufacedetectnet.py # noqa\nimport math\nfrom enum import Enum\nfrom typing import Callable, Dict, List, Optional, Tuple\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom kornia.geometry.bbox import nms as nms_kornia\n\n__all__ = [\n \"FaceDetector\",\n \"FaceDetectorResult\",\n \"FaceKeypoint\",\n]\n\n\nurl: str = \"https://github.com/ShiqiYu/libfacedetection.train/raw/master/tasks/task1/weights/yunet_final.pth\"\n\n\nclass FaceKeypoint(Enum):\n r\"\"\"Define the keypoints detected in a face.\n\n The left/right convention is based on the screen viewer.\n \"\"\"\n EYE_LEFT = 0\n EYE_RIGHT = 1\n NOSE = 2\n MOUTH_LEFT = 3\n MOUTH_RIGHT = 4\n\n\nclass FaceDetectorResult:\n r\"\"\"Encapsulate the results obtained by the :py:class:`kornia.contrib.FaceDetector`.\n\n Args:\n data: the encoded results coming from the feature detector with shape :math:`(14,)`.\n\n \"\"\"\n def __init__(self, data: torch.Tensor) -> None:\n if len(data) < 15:\n raise ValueError(f\"Result must comes as vector of size(14). Got: {data.shape}.\")\n self._data = data\n\n def to(self, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> \"FaceDetectorResult\":\n \"\"\"Like :func:`torch.nn.Module.to()` method.\"\"\"\n self._data = self._data.to(device=device, dtype=dtype)\n return self\n\n @property\n def xmin(self) -> torch.Tensor:\n \"\"\"The bounding box top-left x-coordinate.\"\"\"\n return self._data[..., 0]\n\n @property\n def ymin(self) -> torch.Tensor:\n \"\"\"The bounding box top-left y-coordinate.\"\"\"\n return self._data[..., 1]\n\n @property\n def xmax(self) -> torch.Tensor:\n \"\"\"The bounding box bottom-right x-coordinate.\"\"\"\n return self._data[..., 2]\n\n @property\n def ymax(self) -> torch.Tensor:\n \"\"\"The bounding box bottom-right y-coordinate.\"\"\"\n return self._data[..., 3]\n\n def get_keypoint(self, keypoint: FaceKeypoint) -> torch.Tensor:\n \"\"\"The [x y] position of a given facial keypoint.\n\n Args:\n keypoint: the keypoint type to return the position.\n \"\"\"\n if keypoint == FaceKeypoint.EYE_LEFT:\n out = self._data[..., (4, 5)]\n elif keypoint == FaceKeypoint.EYE_RIGHT:\n out = self._data[..., (6, 7)]\n elif keypoint == FaceKeypoint.NOSE:\n out = self._data[..., (8, 9)]\n elif keypoint == FaceKeypoint.MOUTH_LEFT:\n out = self._data[..., (10, 11)]\n elif keypoint == FaceKeypoint.MOUTH_RIGHT:\n out = self._data[..., (12, 13)]\n else:\n raise ValueError(f\"Not valid keypoint type. Got: {keypoint}.\")\n return out\n\n @property\n def score(self) -> torch.Tensor:\n \"\"\"The detection score.\"\"\"\n return self._data[..., 14]\n\n @property\n def width(self) -> torch.Tensor:\n \"\"\"The bounding box width.\"\"\"\n return self.xmax - self.xmin\n\n @property\n def height(self) -> torch.Tensor:\n \"\"\"The bounding box height.\"\"\"\n return self.ymax - self.ymin\n\n @property\n def top_left(self) -> torch.Tensor:\n \"\"\"The [x y] position of the top-left coordinate of the bounding box.\"\"\"\n return self._data[..., (0, 1)]\n\n @property\n def top_right(self) -> torch.Tensor:\n \"\"\"The [x y] position of the top-left coordinate of the bounding box.\"\"\"\n out = self.top_left\n out[..., 0] += self.width\n return out\n\n @property\n def bottom_right(self) -> torch.Tensor:\n \"\"\"The [x y] position of the bottom-right coordinate of the bounding box.\"\"\"\n return self._data[..., (2, 3)]\n\n @property\n def bottom_left(self) -> torch.Tensor:\n \"\"\"The [x y] position of the top-left coordinate of the bounding box.\"\"\"\n out = self.top_left\n out[..., 1] += self.height\n return out\n\n\nclass FaceDetector(nn.Module):\n r\"\"\"Detect faces in a given image using a CNN.\n\n By default, it uses the method described in :cite:`facedetect-yu`.\n\n Args:\n top_k: the maximum number of detections to return before the nms.\n confidence_threshold: the threshold used to discard detections.\n nms_threshold: the threshold used by the nms for iou.\n keep_top_k: the maximum number of detections to return after the nms.\n\n Return:\n A tensor of shape :math:`(N,15)` to be used with :py:class:`kornia.contrib.FaceDetectorResult`.\n\n Example:\n >>> img = torch.rand(1, 3, 320, 320)\n >>> detect = FaceDetector()\n >>> res = detect(img)\n \"\"\"\n def __init__(self,\n top_k: int = 5000,\n confidence_threshold: float = 0.3,\n nms_threshold: float = 0.3,\n keep_top_k: int = 750) -> None:\n super().__init__()\n self.top_k = top_k\n self.confidence_threshold = confidence_threshold\n self.nms_threshold = nms_threshold\n self.keep_top_k = keep_top_k\n self.config = {\n 'name': 'YuFaceDetectNet',\n 'min_sizes': [[10, 16, 24], [32, 48], [64, 96], [128, 192, 256]],\n 'steps': [8, 16, 32, 64],\n 'variance': [0.1, 0.2],\n 'clip': False,\n }\n self.min_sizes: List[List[int]] = [[10, 16, 24], [32, 48], [64, 96], [128, 192, 256]]\n self.steps: List[int] = [8, 16, 32, 64]\n self.variance: List[float] = [0.1, 0.2]\n self.clip: bool = False\n self.model = YuFaceDetectNet('test', pretrained=True)\n self.nms: Callable = nms_kornia\n\n def preprocess(self, image: torch.Tensor) -> torch.Tensor:\n return image\n\n def postprocess(self, data: Dict[str, torch.Tensor], height: int, width: int) -> torch.Tensor:\n loc, conf, iou = data['loc'], data['conf'], data['iou']\n\n scale = torch.tensor([\n width, height, width, height,\n width, height, width, height,\n width, height, width, height,\n width, height,\n ], device=loc.device, dtype=loc.dtype) # 14\n\n priors = _PriorBox(self.min_sizes, self.steps, self.clip, image_size=(height, width))\n priors = priors.to(loc.device, loc.dtype)\n\n boxes = _decode(loc, priors(), self.variance) # Nx14\n boxes = boxes * scale\n\n # clamp here for the compatibility for ONNX\n cls_scores, iou_scores = conf[:, 1], iou[:, 0]\n scores = (cls_scores * iou_scores.clamp(0., 1.)).sqrt()\n\n # ignore low scores\n inds = (scores > self.confidence_threshold)\n boxes, scores = boxes[inds], scores[inds]\n\n # keep top-K before NMS\n order = scores.sort(descending=True)[1][:self.top_k]\n boxes, scores = boxes[order], scores[order]\n\n # performd NMS\n # NOTE: nms need to be revise since does not export well to onnx\n dets = torch.cat((boxes, scores[:, None]), dim=-1) # Nx15\n keep = self.nms(boxes[:, :4], scores, self.nms_threshold)\n if len(keep) > 0:\n dets = dets[keep, :]\n\n # keep top-K faster NMS\n return dets[:self.keep_top_k]\n\n def forward(self, image: torch.Tensor) -> torch.Tensor:\n img = self.preprocess(image)\n out = self.model(img)\n return self.postprocess(out, img.shape[-2], img.shape[-1])\n\n\n# utils for the network\n\nclass ConvDPUnit(nn.Sequential):\n def __init__(self, in_channels, out_channels, withBNRelu=True):\n super().__init__()\n self.add_module(\"conv1\", nn.Conv2d(in_channels, out_channels, 1, 1, 0, bias=True, groups=1))\n self.add_module(\"conv2\", nn.Conv2d(out_channels, out_channels, 3, 1, 1, bias=True, groups=out_channels))\n if withBNRelu:\n self.add_module(\"bn\", nn.BatchNorm2d(out_channels))\n self.add_module(\"relu\", nn.ReLU(inplace=True))\n\n\nclass Conv_head(nn.Sequential):\n def __init__(self, in_channels: int, mid_channels: int, out_channels: int) -> None:\n super().__init__()\n self.add_module(\"conv1\", nn.Conv2d(in_channels, mid_channels, 3, 2, 1, bias=True, groups=1))\n self.add_module(\"bn1\", nn.BatchNorm2d(mid_channels))\n self.add_module(\"relu\", nn.ReLU(inplace=True))\n self.add_module(\"conv2\", ConvDPUnit(mid_channels, out_channels))\n\n\nclass Conv4layerBlock(nn.Sequential):\n def __init__(self, in_channels: int, out_channels: int, withBNRelu: bool = True) -> None:\n super().__init__()\n self.add_module(\"conv1\", ConvDPUnit(in_channels, in_channels, True))\n self.add_module(\"conv2\", ConvDPUnit(in_channels, out_channels, withBNRelu))\n\n\nclass YuFaceDetectNet(nn.Module):\n def __init__(self, phase, pretrained: bool):\n super().__init__()\n self.phase = phase\n self.num_classes = 2\n\n self.model0 = Conv_head(3, 16, 16)\n self.model1 = Conv4layerBlock(16, 64)\n self.model2 = Conv4layerBlock(64, 64)\n self.model3 = Conv4layerBlock(64, 64)\n self.model4 = Conv4layerBlock(64, 64)\n self.model5 = Conv4layerBlock(64, 64)\n self.model6 = Conv4layerBlock(64, 64)\n\n self.head = nn.Sequential(\n Conv4layerBlock(64, 3 * (14 + 2 + 1), False),\n Conv4layerBlock(64, 2 * (14 + 2 + 1), False),\n Conv4layerBlock(64, 2 * (14 + 2 + 1), False),\n Conv4layerBlock(64, 3 * (14 + 2 + 1), False),\n )\n\n if self.phase == 'train':\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n if m.bias is not None:\n nn.init.xavier_normal_(m.weight.data)\n m.bias.data.fill_(0.02)\n else:\n m.weight.data.normal_(0, 0.01)\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n # use torch.hub to load pretrained model\n if pretrained:\n pretrained_dict = torch.hub.load_state_dict_from_url(\n url, map_location=lambda storage, loc: storage\n )\n self.load_state_dict(pretrained_dict, strict=True)\n self.eval()\n\n def forward(self, x: torch.Tensor) -> Dict[str, torch.Tensor]:\n detection_sources, head_list = [], []\n\n x = self.model0(x)\n x = F.max_pool2d(x, 2)\n x = self.model1(x)\n x = self.model2(x)\n x = F.max_pool2d(x, 2)\n x = self.model3(x)\n detection_sources.append(x)\n\n x = F.max_pool2d(x, 2)\n x = self.model4(x)\n detection_sources.append(x)\n\n x = F.max_pool2d(x, 2)\n x = self.model5(x)\n detection_sources.append(x)\n\n x = F.max_pool2d(x, 2)\n x = self.model6(x)\n detection_sources.append(x)\n\n for i, h in enumerate(self.head):\n x_tmp = h(detection_sources[i])\n head_list.append(x_tmp.permute(0, 2, 3, 1).contiguous())\n\n head_data = torch.cat([o.view(o.size(0), -1) for o in head_list], 1)\n head_data = head_data.view(head_data.size(0), -1, 17)\n\n loc_data, conf_data, iou_data = head_data.split((14, 2, 1), dim=-1)\n\n if self.phase == \"test\":\n loc_data = loc_data.view(-1, 14)\n conf_data = torch.softmax(conf_data.view(-1, self.num_classes), dim=-1)\n iou_data = iou_data.view(-1, 1)\n else:\n loc_data = loc_data.view(loc_data.size(0), -1, 14)\n conf_data = conf_data.view(conf_data.size(0), -1, self.num_classes)\n iou_data = iou_data.view(iou_data.size(0), -1, 1)\n\n return {\"loc\": loc_data, \"conf\": conf_data, \"iou\": iou_data}\n\n\n# utils for post-processing\n\n\n# Adapted from https://github.com/Hakuyume/chainer-ssd\ndef _decode(loc: torch.Tensor, priors: torch.Tensor, variances: List[float]) -> torch.Tensor:\n \"\"\"Decode locations from predictions using priors to undo the encoding we did for offset regression at train\n time.\n\n Args:\n loc:location predictions for loc layers. Shape: [num_priors,4].\n priors: Prior boxes in center-offset form. Shape: [num_priors,4].\n variances: (list[float]) Variances of priorboxes.\n\n Return:\n Tensor containing decoded bounding box predictions.\n \"\"\"\n boxes = torch.cat((\n priors[:, 0:2] + loc[:, 0:2] * variances[0] * priors[:, 2:4],\n priors[:, 2:4] * torch.exp(loc[:, 2:4] * variances[1]),\n priors[:, 0:2] + loc[:, 4:6] * variances[0] * priors[:, 2:4],\n priors[:, 0:2] + loc[:, 6:8] * variances[0] * priors[:, 2:4],\n priors[:, 0:2] + loc[:, 8:10] * variances[0] * priors[:, 2:4],\n priors[:, 0:2] + loc[:, 10:12] * variances[0] * priors[:, 2:4],\n priors[:, 0:2] + loc[:, 12:14] * variances[0] * priors[:, 2:4]), 1)\n # prepare final output\n tmp = boxes[:, 0:2] - boxes[:, 2:4] / 2\n return torch.cat((tmp, boxes[:, 2:4] + tmp, boxes[:, 4:]), dim=-1)\n\n\nclass _PriorBox:\n def __init__(self, min_sizes: List[List[int]], steps: List[int], clip: bool, image_size: Tuple[int, int]) -> None:\n self.min_sizes = min_sizes\n self.steps = steps\n self.clip = clip\n self.image_size = image_size\n\n self.device: torch.device = torch.device('cpu')\n self.dtype: torch.dtype = torch.float32\n\n for i in range(4):\n if(self.steps[i] != math.pow(2, (i + 3))):\n raise ValueError(\"steps must be [8,16,32,64]\")\n\n self.feature_map_2th = [int(int((self.image_size[0] + 1) / 2) / 2),\n int(int((self.image_size[1] + 1) / 2) / 2)]\n self.feature_map_3th = [int(self.feature_map_2th[0] / 2),\n int(self.feature_map_2th[1] / 2)]\n self.feature_map_4th = [int(self.feature_map_3th[0] / 2),\n int(self.feature_map_3th[1] / 2)]\n self.feature_map_5th = [int(self.feature_map_4th[0] / 2),\n int(self.feature_map_4th[1] / 2)]\n self.feature_map_6th = [int(self.feature_map_5th[0] / 2),\n int(self.feature_map_5th[1] / 2)]\n\n self.feature_maps = [self.feature_map_3th, self.feature_map_4th,\n self.feature_map_5th, self.feature_map_6th]\n\n def to(self, device: torch.device, dtype: torch.dtype) -> '_PriorBox':\n self.device = device\n self.dtype = dtype\n return self\n\n def __call__(self) -> torch.Tensor:\n anchors: List[float] = []\n for k, f in enumerate(self.feature_maps):\n min_sizes: List[int] = self.min_sizes[k]\n # NOTE: the nested loop it's to make torchscript happy\n for i in range(f[0]):\n for j in range(f[1]):\n for min_size in min_sizes:\n s_kx = min_size / self.image_size[1]\n s_ky = min_size / self.image_size[0]\n\n cx = (j + 0.5) * self.steps[k] / self.image_size[1]\n cy = (i + 0.5) * self.steps[k] / self.image_size[0]\n anchors += [cx, cy, s_kx, s_ky]\n # back to torch land\n output = torch.tensor(anchors, device=self.device, dtype=self.dtype).view(-1, 4)\n if self.clip:\n output = output.clamp(max=1, min=0)\n return output\n", "import os\n\nimport cv2\nimport imageio\nimport torch\n\nimport kornia as K\nimport kornia.geometry as KG\n\n\ndef load_timg(file_name):\n \"\"\"Loads the image with OpenCV and converts to torch.Tensor.\"\"\"\n assert os.path.isfile(file_name), f\"Invalid file {file_name}\" # nosec\n # load image with OpenCV\n img = cv2.imread(file_name, cv2.IMREAD_COLOR)\n # convert image to torch tensor\n tensor = K.image_to_tensor(img, None).float() / 255.\n return K.color.bgr_to_rgb(tensor)\n\n\nregistrator = KG.ImageRegistrator('similarity')\n\nimg1 = K.resize(load_timg('/Users/oldufo/datasets/stewart/MR-CT/CT.png'), (400, 600))\nimg2 = K.resize(load_timg('/Users/oldufo/datasets/stewart/MR-CT/MR.png'), (400, 600))\nmodel, intermediate = registrator.register(img1, img2, output_intermediate_models=True)\n\nvideo_writer = imageio.get_writer('medical_registration.gif', fps=2)\n\ntimg_dst_first = img1.clone()\ntimg_dst_first[0, 0, :, :] = img2[0, 0, :, :]\nvideo_writer.append_data(K.tensor_to_image((timg_dst_first * 255.).byte()))\n\nwith torch.no_grad():\n for m in intermediate:\n timg_dst = KG.homography_warp(img1, m, img2.shape[-2:])\n timg_dst[0, 0, :, :] = img2[0, 0, :, :]\n video_writer.append_data(K.tensor_to_image((timg_dst_first * 255.).byte()))\nvideo_writer.close()\n", "import pytest\nimport torch\nfrom torch.autograd import gradcheck\n\nimport kornia\nimport kornia.testing as utils # test utils\nfrom kornia.testing import assert_close\n\n\nclass Testunsharp:\n @pytest.mark.parametrize(\"batch_shape\", [(1, 4, 8, 15), (2, 3, 11, 7)])\n def test_cardinality(self, batch_shape, device, dtype):\n kernel_size = (5, 7)\n sigma = (1.5, 2.1)\n\n input = torch.rand(batch_shape, device=device, dtype=dtype)\n actual = kornia.filters.unsharp_mask(input, kernel_size, sigma, \"replicate\")\n assert actual.shape == batch_shape\n\n def test_noncontiguous(self, device, dtype):\n batch_size = 3\n input = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)\n\n kernel_size = (3, 3)\n sigma = (1.5, 2.1)\n actual = kornia.filters.unsharp_mask(input, kernel_size, sigma, \"replicate\")\n assert_close(actual, actual)\n\n def test_gradcheck(self, device, dtype):\n # test parameters\n batch_shape = (1, 3, 5, 5)\n kernel_size = (3, 3)\n sigma = (1.5, 2.1)\n\n # evaluate function gradient\n input = torch.rand(batch_shape, device=device, dtype=dtype)\n input = utils.tensor_to_gradcheck_var(input) # to var\n assert gradcheck(kornia.filters.unsharp_mask, (input, kernel_size, sigma, \"replicate\"), raise_exception=True)\n\n def test_jit(self, device, dtype):\n op = kornia.filters.unsharp_mask\n op_script = torch.jit.script(op)\n params = [(3, 3), (1.5, 1.5)]\n\n img = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)\n assert_close(op(img, *params), op_script(img, *params))\n\n def test_module(self, device, dtype):\n params = [(3, 3), (1.5, 1.5)]\n op = kornia.filters.unsharp_mask\n op_module = kornia.filters.UnsharpMask(*params)\n\n img = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)\n assert_close(op(img, *params), op_module(img))\n", "from math import pi\n\nimport pytest\nimport torch\nfrom torch.autograd import gradcheck\n\nimport kornia.testing as utils # test utils\nfrom kornia.feature.mkd import (\n COEFFS,\n EmbedGradients,\n ExplicitSpacialEncoding,\n MKDDescriptor,\n MKDGradients,\n SimpleKD,\n VonMisesKernel,\n Whitening,\n get_grid_dict,\n get_kron_order,\n spatial_kernel_embedding,\n)\nfrom kornia.testing import assert_close\n\n\[email protected](\"ps\", [5, 13, 25])\ndef test_get_grid_dict(ps):\n grid_dict = get_grid_dict(ps)\n param_keys = ['x', 'y', 'phi', 'rho']\n assert set(grid_dict.keys()) == set(param_keys)\n for k in param_keys:\n assert grid_dict[k].shape == (ps, ps)\n\n\[email protected](\"d1,d2\", [(1, 1), (1, 2), (2, 1), (5, 6)])\ndef test_get_kron_order(d1, d2):\n out = get_kron_order(d1, d2)\n assert out.shape == (d1 * d2, 2)\n\n\nclass TestMKDGradients:\n @pytest.mark.parametrize(\"ps\", [5, 13, 25])\n def test_shape(self, ps, device):\n inp = torch.ones(1, 1, ps, ps).to(device)\n gradients = MKDGradients().to(device)\n out = gradients(inp)\n assert out.shape == (1, 2, ps, ps)\n\n @pytest.mark.parametrize(\"bs\", [1, 5, 13])\n def test_batch_shape(self, bs, device):\n inp = torch.ones(bs, 1, 15, 15).to(device)\n gradients = MKDGradients().to(device)\n out = gradients(inp)\n assert out.shape == (bs, 2, 15, 15)\n\n def test_print(self, device):\n gradients = MKDGradients().to(device)\n gradients.__repr__()\n\n def test_toy(self, device):\n patch = torch.ones(1, 1, 6, 6).to(device).float()\n patch[0, 0, :, 3:] = 0\n gradients = MKDGradients().to(device)\n out = gradients(patch)\n expected_mags_1 = torch.Tensor([0, 0, 1.0, 1.0, 0, 0]).to(device)\n expected_mags = expected_mags_1.unsqueeze(0).repeat(6, 1)\n expected_oris_1 = torch.Tensor([-pi, -pi, 0, 0, -pi, -pi]).to(device)\n expected_oris = expected_oris_1.unsqueeze(0).repeat(6, 1)\n assert_close(out[0, 0, :, :], expected_mags, atol=1e-3, rtol=1e-3)\n assert_close(out[0, 1, :, :], expected_oris, atol=1e-3, rtol=1e-3)\n\n def test_gradcheck(self, device):\n batch_size, channels, height, width = 1, 1, 13, 13\n patches = torch.rand(batch_size, channels, height, width).to(device)\n patches = utils.tensor_to_gradcheck_var(patches) # to var\n\n def grad_describe(patches):\n mkd_grads = MKDGradients()\n mkd_grads.to(device)\n return mkd_grads(patches)\n\n assert gradcheck(grad_describe, (patches), raise_exception=True, nondet_tol=1e-4)\n\n @pytest.mark.jit\n def test_jit(self, device, dtype):\n B, C, H, W = 2, 1, 13, 13\n patches = torch.rand(B, C, H, W, device=device, dtype=dtype)\n model = MKDGradients().to(patches.device, patches.dtype).eval()\n model_jit = torch.jit.script(MKDGradients().to(patches.device, patches.dtype).eval())\n assert_close(model(patches), model_jit(patches))\n\n\nclass TestVonMisesKernel:\n @pytest.mark.parametrize(\"ps\", [5, 13, 25])\n def test_shape(self, ps, device):\n inp = torch.ones(1, 1, ps, ps).to(device)\n vm = VonMisesKernel(patch_size=ps, coeffs=[0.38214156, 0.48090413]).to(device)\n out = vm(inp)\n assert out.shape == (1, 3, ps, ps)\n\n @pytest.mark.parametrize(\"bs\", [1, 5, 13])\n def test_batch_shape(self, bs, device):\n inp = torch.ones(bs, 1, 15, 15).to(device)\n vm = VonMisesKernel(patch_size=15, coeffs=[0.38214156, 0.48090413]).to(device)\n out = vm(inp)\n assert out.shape == (bs, 3, 15, 15)\n\n @pytest.mark.parametrize(\"coeffs\", COEFFS.values())\n def test_coeffs(self, coeffs, device):\n inp = torch.ones(1, 1, 15, 15).to(device)\n vm = VonMisesKernel(patch_size=15, coeffs=coeffs).to(device)\n out = vm(inp)\n assert out.shape == (1, 2 * len(coeffs) - 1, 15, 15)\n\n def test_print(self, device):\n vm = VonMisesKernel(patch_size=32, coeffs=[0.38214156, 0.48090413]).to(device)\n vm.__repr__()\n\n def test_toy(self, device):\n patch = torch.ones(1, 1, 6, 6).float().to(device)\n patch[0, 0, :, 3:] = 0\n vm = VonMisesKernel(patch_size=6, coeffs=[0.38214156, 0.48090413]).to(device)\n out = vm(patch)\n expected = torch.ones_like(out[0, 0, :, :]).to(device)\n assert_close(out[0, 0, :, :], expected * 0.6182, atol=1e-3, rtol=1e-3)\n\n expected = torch.Tensor([0.3747, 0.3747, 0.3747, 0.6935, 0.6935, 0.6935]).to(device)\n expected = expected.unsqueeze(0).repeat(6, 1)\n assert_close(out[0, 1, :, :], expected, atol=1e-3, rtol=1e-3)\n\n expected = torch.Tensor([0.5835, 0.5835, 0.5835, 0.0000, 0.0000, 0.0000]).to(device)\n expected = expected.unsqueeze(0).repeat(6, 1)\n assert_close(out[0, 2, :, :], expected, atol=1e-3, rtol=1e-3)\n\n def test_gradcheck(self, device):\n batch_size, channels, ps = 1, 1, 13\n patches = torch.rand(batch_size, channels, ps, ps).to(device)\n patches = utils.tensor_to_gradcheck_var(patches) # to var\n\n def vm_describe(patches, ps=13):\n vmkernel = VonMisesKernel(patch_size=ps, coeffs=[0.38214156, 0.48090413]).double()\n vmkernel.to(device)\n return vmkernel(patches.double())\n\n assert gradcheck(vm_describe, (patches, ps), raise_exception=True, nondet_tol=1e-4)\n\n @pytest.mark.jit\n def test_jit(self, device, dtype):\n B, C, H, W = 2, 1, 13, 13\n patches = torch.rand(B, C, H, W, device=device, dtype=dtype)\n model = VonMisesKernel(patch_size=13, coeffs=[0.38214156, 0.48090413]).to(patches.device, patches.dtype).eval()\n model_jit = torch.jit.script(\n VonMisesKernel(patch_size=13, coeffs=[0.38214156, 0.48090413]).to(patches.device, patches.dtype).eval()\n )\n assert_close(model(patches), model_jit(patches))\n\n\nclass TestEmbedGradients:\n @pytest.mark.parametrize(\"ps,relative\", [(5, True), (13, True), (25, True), (5, False), (13, False), (25, False)])\n def test_shape(self, ps, relative, device):\n inp = torch.ones(1, 2, ps, ps).to(device)\n emb_grads = EmbedGradients(patch_size=ps, relative=relative).to(device)\n out = emb_grads(inp)\n assert out.shape == (1, 7, ps, ps)\n\n @pytest.mark.parametrize(\"bs\", [1, 5, 13])\n def test_batch_shape(self, bs, device):\n inp = torch.ones(bs, 2, 15, 15).to(device)\n emb_grads = EmbedGradients(patch_size=15, relative=True).to(device)\n out = emb_grads(inp)\n assert out.shape == (bs, 7, 15, 15)\n\n def test_print(self, device):\n emb_grads = EmbedGradients(patch_size=15, relative=True).to(device)\n emb_grads.__repr__()\n\n def test_toy(self, device):\n grads = torch.ones(1, 2, 6, 6).float().to(device)\n grads[0, 0, :, 3:] = 0\n emb_grads = EmbedGradients(patch_size=6, relative=True).to(device)\n out = emb_grads(grads)\n expected = torch.ones_like(out[0, 0, :, :3]).to(device)\n assert_close(out[0, 0, :, :3], expected * 0.3787, atol=1e-3, rtol=1e-3)\n assert_close(out[0, 0, :, 3:], expected * 0, atol=1e-3, rtol=1e-3)\n\n # TODO: review this test implementation\n @pytest.mark.xfail(reason=\"RuntimeError: Jacobian mismatch for output 0 with respect to input 0,\")\n def test_gradcheck(self, device):\n batch_size, channels, ps = 1, 2, 13\n patches = torch.rand(batch_size, channels, ps, ps).to(device)\n patches = utils.tensor_to_gradcheck_var(patches) # to var\n\n def emb_grads_describe(patches, ps=13):\n emb_grads = EmbedGradients(patch_size=ps, relative=True).double()\n emb_grads.to(device)\n return emb_grads(patches.double())\n\n assert gradcheck(emb_grads_describe, (patches, ps), raise_exception=True, nondet_tol=1e-4)\n\n @pytest.mark.jit\n def test_jit(self, device, dtype):\n B, C, H, W = 2, 2, 13, 13\n patches = torch.rand(B, C, H, W, device=device, dtype=dtype)\n model = EmbedGradients(patch_size=W, relative=True).to(patches.device, patches.dtype).eval()\n model_jit = torch.jit.script(\n EmbedGradients(patch_size=W, relative=True).to(patches.device, patches.dtype).eval()\n )\n assert_close(model(patches), model_jit(patches))\n\n\[email protected](\"kernel_type,d,ps\", [('cart', 9, 9), ('polar', 25, 9), ('cart', 9, 16), ('polar', 25, 16)])\ndef test_spatial_kernel_embedding(kernel_type, ps, d):\n grids = get_grid_dict(ps)\n spatial_kernel = spatial_kernel_embedding(kernel_type, grids)\n assert spatial_kernel.shape == (d, ps, ps)\n\n\nclass TestExplicitSpacialEncoding:\n @pytest.mark.parametrize(\n \"kernel_type,ps,in_dims\", [('cart', 9, 3), ('polar', 9, 3), ('cart', 13, 7), ('polar', 13, 7)]\n )\n def test_shape(self, kernel_type, ps, in_dims, device):\n inp = torch.ones(1, in_dims, ps, ps).to(device)\n ese = ExplicitSpacialEncoding(kernel_type=kernel_type, fmap_size=ps, in_dims=in_dims).to(device)\n out = ese(inp)\n d_ = 9 if kernel_type == 'cart' else 25\n assert out.shape == (1, d_ * in_dims)\n\n @pytest.mark.parametrize(\n \"kernel_type,bs\", [('cart', 1), ('cart', 5), ('cart', 13), ('polar', 1), ('polar', 5), ('polar', 13)]\n )\n def test_batch_shape(self, kernel_type, bs, device):\n inp = torch.ones(bs, 7, 15, 15).to(device)\n ese = ExplicitSpacialEncoding(kernel_type=kernel_type, fmap_size=15, in_dims=7).to(device)\n out = ese(inp)\n d_ = 9 if kernel_type == 'cart' else 25\n assert out.shape == (bs, d_ * 7)\n\n @pytest.mark.parametrize(\"kernel_type\", ['cart', 'polar'])\n def test_print(self, kernel_type, device):\n ese = ExplicitSpacialEncoding(kernel_type=kernel_type, fmap_size=15, in_dims=7).to(device)\n ese.__repr__()\n\n def test_toy(self, device):\n inp = torch.ones(1, 2, 6, 6).to(device).float()\n inp[0, 0, :, :] = 0\n cart_ese = ExplicitSpacialEncoding(kernel_type='cart', fmap_size=6, in_dims=2).to(device)\n out = cart_ese(inp)\n out_part = out[:, :9]\n expected = torch.zeros_like(out_part).to(device)\n assert_close(out_part, expected, atol=1e-3, rtol=1e-3)\n\n polar_ese = ExplicitSpacialEncoding(kernel_type='polar', fmap_size=6, in_dims=2).to(device)\n out = polar_ese(inp)\n out_part = out[:, :25]\n expected = torch.zeros_like(out_part).to(device)\n assert_close(out_part, expected, atol=1e-3, rtol=1e-3)\n\n @pytest.mark.parametrize(\"kernel_type\", ['cart', 'polar'])\n def test_gradcheck(self, kernel_type, device):\n batch_size, channels, ps = 1, 2, 13\n patches = torch.rand(batch_size, channels, ps, ps).to(device)\n patches = utils.tensor_to_gradcheck_var(patches) # to var\n\n def explicit_spatial_describe(patches, ps=13):\n ese = ExplicitSpacialEncoding(kernel_type=kernel_type, fmap_size=ps, in_dims=2)\n ese.to(device)\n return ese(patches)\n\n assert gradcheck(explicit_spatial_describe, (patches, ps), raise_exception=True, nondet_tol=1e-4)\n\n @pytest.mark.jit\n def test_jit(self, device, dtype):\n B, C, H, W = 2, 2, 13, 13\n patches = torch.rand(B, C, H, W, device=device, dtype=dtype)\n model = (\n ExplicitSpacialEncoding(kernel_type='cart', fmap_size=W, in_dims=2).to(patches.device, patches.dtype).eval()\n )\n model_jit = torch.jit.script(\n ExplicitSpacialEncoding(kernel_type='cart', fmap_size=W, in_dims=2).to(patches.device, patches.dtype).eval()\n )\n assert_close(model(patches), model_jit(patches))\n\n\nclass TestWhitening:\n @pytest.mark.parametrize(\n \"kernel_type,xform,output_dims\",\n [\n ('cart', None, 3),\n ('polar', None, 3),\n ('cart', 'lw', 7),\n ('polar', 'lw', 7),\n ('cart', 'pca', 9),\n ('polar', 'pca', 9),\n ],\n )\n def test_shape(self, kernel_type, xform, output_dims, device):\n in_dims = 63 if kernel_type == 'cart' else 175\n wh = Whitening(xform=xform, whitening_model=None, in_dims=in_dims, output_dims=output_dims).to(device)\n inp = torch.ones(1, in_dims).to(device)\n out = wh(inp)\n assert out.shape == (1, output_dims)\n\n @pytest.mark.parametrize(\"bs\", [1, 3, 7])\n def test_batch_shape(self, bs, device):\n wh = Whitening(xform='lw', whitening_model=None, in_dims=175, output_dims=128).to(device)\n inp = torch.ones(bs, 175).to(device)\n out = wh(inp)\n assert out.shape == (bs, 128)\n\n def test_print(self, device):\n wh = Whitening(xform='lw', whitening_model=None, in_dims=175, output_dims=128).to(device)\n wh.__repr__()\n\n def test_toy(self, device):\n wh = Whitening(xform='lw', whitening_model=None, in_dims=175, output_dims=175).to(device)\n inp = torch.ones(1, 175).to(device).float()\n out = wh(inp)\n expected = torch.ones_like(inp).to(device) * 0.0756\n assert_close(out, expected, atol=1e-3, rtol=1e-3)\n\n def test_gradcheck(self, device):\n batch_size, in_dims = 1, 175\n patches = torch.rand(batch_size, in_dims).to(device)\n patches = utils.tensor_to_gradcheck_var(patches) # to var\n\n def whitening_describe(patches, in_dims=175):\n wh = Whitening(xform='lw', whitening_model=None, in_dims=in_dims).double()\n wh.to(device)\n return wh(patches.double())\n\n assert gradcheck(whitening_describe, (patches, in_dims), raise_exception=True, nondet_tol=1e-4)\n\n @pytest.mark.jit\n def test_jit(self, device, dtype):\n batch_size, in_dims = 1, 175\n patches = torch.rand(batch_size, in_dims).to(device)\n model = Whitening(xform='lw', whitening_model=None, in_dims=in_dims).to(patches.device, patches.dtype).eval()\n model_jit = torch.jit.script(\n Whitening(xform='lw', whitening_model=None, in_dims=in_dims).to(patches.device, patches.dtype).eval()\n )\n assert_close(model(patches), model_jit(patches))\n\n\nclass TestMKDDescriptor:\n dims = {'cart': 63, 'polar': 175, 'concat': 238}\n\n @pytest.mark.parametrize(\n \"ps,kernel_type\", [(9, 'concat'), (9, 'cart'), (9, 'polar'), (32, 'concat'), (32, 'cart'), (32, 'polar')]\n )\n def test_shape(self, ps, kernel_type, device):\n mkd = MKDDescriptor(patch_size=ps, kernel_type=kernel_type, whitening=None).to(device)\n inp = torch.ones(1, 1, ps, ps).to(device)\n out = mkd(inp)\n assert out.shape == (1, self.dims[kernel_type])\n\n @pytest.mark.parametrize(\n \"ps,kernel_type,whitening\",\n [\n (9, 'concat', 'lw'),\n (9, 'cart', 'lw'),\n (9, 'polar', 'lw'),\n (9, 'concat', 'pcawt'),\n (9, 'cart', 'pcawt'),\n (9, 'polar', 'pcawt'),\n ],\n )\n def test_whitened_shape(self, ps, kernel_type, whitening, device):\n mkd = MKDDescriptor(patch_size=ps, kernel_type=kernel_type, whitening=whitening).to(device)\n inp = torch.ones(1, 1, ps, ps).to(device)\n out = mkd(inp)\n output_dims = min(self.dims[kernel_type], 128)\n assert out.shape == (1, output_dims)\n\n @pytest.mark.parametrize(\"bs\", [1, 3, 7])\n def test_batch_shape(self, bs, device):\n mkd = MKDDescriptor(patch_size=19, kernel_type='concat', whitening=None).to(device)\n inp = torch.ones(bs, 1, 19, 19).to(device)\n out = mkd(inp)\n assert out.shape == (bs, 238)\n\n def test_print(self, device):\n mkd = MKDDescriptor(patch_size=32, whitening='lw', training_set='liberty', output_dims=128).to(device)\n mkd.__repr__()\n\n def test_toy(self, device):\n inp = torch.ones(1, 1, 6, 6).to(device).float()\n inp[0, 0, :, :] = 0\n mkd = MKDDescriptor(patch_size=6, kernel_type='concat', whitening=None).to(device)\n out = mkd(inp)\n out_part = out[0, -28:]\n expected = torch.zeros_like(out_part).to(device)\n assert_close(out_part, expected, atol=1e-3, rtol=1e-3)\n\n @pytest.mark.skip(\"Just because\")\n @pytest.mark.parametrize(\"whitening\", [None, 'lw', 'pca'])\n def test_gradcheck(self, whitening, device):\n batch_size, channels, ps = 1, 1, 19\n patches = torch.rand(batch_size, channels, ps, ps).to(device)\n patches = utils.tensor_to_gradcheck_var(patches) # to var\n\n def mkd_describe(patches, patch_size=19):\n mkd = MKDDescriptor(patch_size=patch_size, kernel_type='concat', whitening=whitening).double()\n mkd.to(device)\n return mkd(patches.double())\n\n assert gradcheck(mkd_describe, (patches, ps), raise_exception=True, nondet_tol=1e-4)\n\n @pytest.mark.skip(\"neither dict, nor nn.ModuleDict works\")\n @pytest.mark.jit\n def test_jit(self, device, dtype):\n batch_size, channels, ps = 1, 1, 19\n patches = torch.rand(batch_size, channels, ps, ps).to(device)\n kt = 'concat'\n wt = 'lw'\n model = MKDDescriptor(patch_size=ps, kernel_type=kt, whitening=wt).to(patches.device, patches.dtype).eval()\n model_jit = torch.jit.script(\n MKDDescriptor(patch_size=ps, kernel_type=kt, whitening=wt).to(patches.device, patches.dtype).eval()\n )\n assert_close(model(patches), model_jit(patches))\n\n\nclass TestSimpleKD:\n dims = {'cart': 63, 'polar': 175}\n\n @pytest.mark.parametrize(\"ps,kernel_type\", [(9, 'cart'), (9, 'polar'), (32, 'cart'), (32, 'polar')])\n def test_shape(self, ps, kernel_type, device):\n skd = SimpleKD(patch_size=ps, kernel_type=kernel_type).to(device)\n inp = torch.ones(1, 1, ps, ps).to(device)\n out = skd(inp)\n assert out.shape == (1, min(128, self.dims[kernel_type]))\n\n @pytest.mark.parametrize(\"bs\", [1, 3, 7])\n def test_batch_shape(self, bs, device):\n skd = SimpleKD(patch_size=19, kernel_type='polar').to(device)\n inp = torch.ones(bs, 1, 19, 19).to(device)\n out = skd(inp)\n assert out.shape == (bs, 128)\n\n def test_print(self, device):\n skd = SimpleKD(patch_size=19, kernel_type='polar').to(device)\n skd.__repr__()\n\n def test_gradcheck(self, device):\n batch_size, channels, ps = 1, 1, 19\n patches = torch.rand(batch_size, channels, ps, ps).to(device)\n patches = utils.tensor_to_gradcheck_var(patches) # to var\n\n def skd_describe(patches, patch_size=19):\n skd = SimpleKD(patch_size=ps, kernel_type='polar', whitening='lw').double()\n skd.to(device)\n return skd(patches.double())\n\n assert gradcheck(skd_describe, (patches, ps), raise_exception=True, nondet_tol=1e-4)\n\n @pytest.mark.jit\n def test_jit(self, device, dtype):\n batch_size, channels, ps = 1, 1, 19\n patches = torch.rand(batch_size, channels, ps, ps).to(device)\n model = SimpleKD(patch_size=ps, kernel_type='polar', whitening='lw').to(patches.device, patches.dtype).eval()\n model_jit = torch.jit.script(\n SimpleKD(patch_size=ps, kernel_type='polar', whitening='lw').to(patches.device, patches.dtype).eval()\n )\n assert_close(model(patches), model_jit(patches))\n", "import torch\n\nfrom kornia.testing import check_is_tensor\n\nfrom .conversions import convert_points_from_homogeneous, convert_points_to_homogeneous\n\n__all__ = [\n \"compose_transformations\",\n \"relative_transformation\",\n \"inverse_transformation\",\n \"transform_points\",\n]\n\n\ndef compose_transformations(trans_01: torch.Tensor, trans_12: torch.Tensor) -> torch.Tensor:\n r\"\"\"Function that composes two homogeneous transformations.\n\n .. math::\n T_0^{2} = \\begin{bmatrix} R_0^1 R_1^{2} & R_0^{1} t_1^{2} + t_0^{1} \\\\\n \\mathbf{0} & 1\\end{bmatrix}\n\n Args:\n trans_01: tensor with the homogeneous transformation from\n a reference frame 1 respect to a frame 0. The tensor has must have a\n shape of :math:`(N, 4, 4)` or :math:`(4, 4)`.\n trans_12: tensor with the homogeneous transformation from\n a reference frame 2 respect to a frame 1. The tensor has must have a\n shape of :math:`(N, 4, 4)` or :math:`(4, 4)`.\n\n Returns:\n the transformation between the two frames with shape :math:`(N, 4, 4)` or :math:`(4, 4)`.\n\n Example::\n >>> trans_01 = torch.eye(4) # 4x4\n >>> trans_12 = torch.eye(4) # 4x4\n >>> trans_02 = compose_transformations(trans_01, trans_12) # 4x4\n\n \"\"\"\n if not torch.is_tensor(trans_01):\n raise TypeError(f\"Input trans_01 type is not a torch.Tensor. Got {type(trans_01)}\")\n\n if not torch.is_tensor(trans_12):\n raise TypeError(f\"Input trans_12 type is not a torch.Tensor. Got {type(trans_12)}\")\n\n if not ((trans_01.dim() in (2, 3)) and (trans_01.shape[-2:] == (4, 4))):\n raise ValueError(\"Input trans_01 must be a of the shape Nx4x4 or 4x4.\" \" Got {}\".format(trans_01.shape))\n\n if not ((trans_12.dim() in (2, 3)) and (trans_12.shape[-2:] == (4, 4))):\n raise ValueError(\"Input trans_12 must be a of the shape Nx4x4 or 4x4.\" \" Got {}\".format(trans_12.shape))\n\n if not trans_01.dim() == trans_12.dim():\n raise ValueError(f\"Input number of dims must match. Got {trans_01.dim()} and {trans_12.dim()}\")\n\n # unpack input data\n rmat_01: torch.Tensor = trans_01[..., :3, :3] # Nx3x3\n rmat_12: torch.Tensor = trans_12[..., :3, :3] # Nx3x3\n tvec_01: torch.Tensor = trans_01[..., :3, -1:] # Nx3x1\n tvec_12: torch.Tensor = trans_12[..., :3, -1:] # Nx3x1\n\n # compute the actual transforms composition\n rmat_02: torch.Tensor = torch.matmul(rmat_01, rmat_12)\n tvec_02: torch.Tensor = torch.matmul(rmat_01, tvec_12) + tvec_01\n\n # pack output tensor\n trans_02: torch.Tensor = torch.zeros_like(trans_01)\n trans_02[..., :3, 0:3] += rmat_02\n trans_02[..., :3, -1:] += tvec_02\n trans_02[..., -1, -1:] += 1.0\n return trans_02\n\n\ndef inverse_transformation(trans_12):\n r\"\"\"Function that inverts a 4x4 homogeneous transformation\n :math:`T_1^{2} = \\begin{bmatrix} R_1 & t_1 \\\\ \\mathbf{0} & 1 \\end{bmatrix}`\n\n The inverse transformation is computed as follows:\n\n .. math::\n\n T_2^{1} = (T_1^{2})^{-1} = \\begin{bmatrix} R_1^T & -R_1^T t_1 \\\\\n \\mathbf{0} & 1\\end{bmatrix}\n\n Args:\n trans_12: transformation tensor of shape :math:`(N, 4, 4)` or :math:`(4, 4)`.\n\n Returns:\n tensor with inverted transformations with shape :math:`(N, 4, 4)` or :math:`(4, 4)`.\n\n Example:\n >>> trans_12 = torch.rand(1, 4, 4) # Nx4x4\n >>> trans_21 = inverse_transformation(trans_12) # Nx4x4\n \"\"\"\n if not torch.is_tensor(trans_12):\n raise TypeError(f\"Input type is not a torch.Tensor. Got {type(trans_12)}\")\n if not ((trans_12.dim() in (2, 3)) and (trans_12.shape[-2:] == (4, 4))):\n raise ValueError(f\"Input size must be a Nx4x4 or 4x4. Got {trans_12.shape}\")\n # unpack input tensor\n rmat_12: torch.Tensor = trans_12[..., :3, 0:3] # Nx3x3\n tvec_12: torch.Tensor = trans_12[..., :3, 3:4] # Nx3x1\n\n # compute the actual inverse\n rmat_21: torch.Tensor = torch.transpose(rmat_12, -1, -2)\n tvec_21: torch.Tensor = torch.matmul(-rmat_21, tvec_12)\n\n # pack to output tensor\n trans_21: torch.Tensor = torch.zeros_like(trans_12)\n trans_21[..., :3, 0:3] += rmat_21\n trans_21[..., :3, -1:] += tvec_21\n trans_21[..., -1, -1:] += 1.0\n return trans_21\n\n\ndef relative_transformation(trans_01: torch.Tensor, trans_02: torch.Tensor) -> torch.Tensor:\n r\"\"\"Function that computes the relative homogeneous transformation from a\n reference transformation :math:`T_1^{0} = \\begin{bmatrix} R_1 & t_1 \\\\\n \\mathbf{0} & 1 \\end{bmatrix}` to destination :math:`T_2^{0} =\n \\begin{bmatrix} R_2 & t_2 \\\\ \\mathbf{0} & 1 \\end{bmatrix}`.\n\n The relative transformation is computed as follows:\n\n .. math::\n\n T_1^{2} = (T_0^{1})^{-1} \\cdot T_0^{2}\n\n Args:\n trans_01: reference transformation tensor of shape :math:`(N, 4, 4)` or :math:`(4, 4)`.\n trans_02: destination transformation tensor of shape :math:`(N, 4, 4)` or :math:`(4, 4)`.\n\n Returns:\n the relative transformation between the transformations with shape :math:`(N, 4, 4)` or :math:`(4, 4)`.\n\n Example::\n >>> trans_01 = torch.eye(4) # 4x4\n >>> trans_02 = torch.eye(4) # 4x4\n >>> trans_12 = relative_transformation(trans_01, trans_02) # 4x4\n \"\"\"\n if not torch.is_tensor(trans_01):\n raise TypeError(f\"Input trans_01 type is not a torch.Tensor. Got {type(trans_01)}\")\n if not torch.is_tensor(trans_02):\n raise TypeError(f\"Input trans_02 type is not a torch.Tensor. Got {type(trans_02)}\")\n if not ((trans_01.dim() in (2, 3)) and (trans_01.shape[-2:] == (4, 4))):\n raise ValueError(\"Input must be a of the shape Nx4x4 or 4x4.\" \" Got {}\".format(trans_01.shape))\n if not ((trans_02.dim() in (2, 3)) and (trans_02.shape[-2:] == (4, 4))):\n raise ValueError(\"Input must be a of the shape Nx4x4 or 4x4.\" \" Got {}\".format(trans_02.shape))\n if not trans_01.dim() == trans_02.dim():\n raise ValueError(f\"Input number of dims must match. Got {trans_01.dim()} and {trans_02.dim()}\")\n trans_10: torch.Tensor = inverse_transformation(trans_01)\n trans_12: torch.Tensor = compose_transformations(trans_10, trans_02)\n return trans_12\n\n\ndef transform_points(trans_01: torch.Tensor, points_1: torch.Tensor) -> torch.Tensor:\n r\"\"\"Function that applies transformations to a set of points.\n\n Args:\n trans_01 (torch.Tensor): tensor for transformations of shape\n :math:`(B, D+1, D+1)`.\n points_1 (torch.Tensor): tensor of points of shape :math:`(B, N, D)`.\n Returns:\n torch.Tensor: tensor of N-dimensional points.\n\n Shape:\n - Output: :math:`(B, N, D)`\n\n Examples:\n\n >>> points_1 = torch.rand(2, 4, 3) # BxNx3\n >>> trans_01 = torch.eye(4).view(1, 4, 4) # Bx4x4\n >>> points_0 = transform_points(trans_01, points_1) # BxNx3\n \"\"\"\n check_is_tensor(trans_01)\n check_is_tensor(points_1)\n if not trans_01.shape[0] == points_1.shape[0] and trans_01.shape[0] != 1:\n raise ValueError(\n \"Input batch size must be the same for both tensors or 1.\"\n f\"Got {trans_01.shape} and {points_1.shape}\"\n )\n if not trans_01.shape[-1] == (points_1.shape[-1] + 1):\n raise ValueError(\n \"Last input dimensions must differ by one unit\"\n f\"Got{trans_01} and {points_1}\"\n )\n\n # We reshape to BxNxD in case we get more dimensions, e.g., MxBxNxD\n shape_inp = list(points_1.shape)\n points_1 = points_1.reshape(-1, points_1.shape[-2], points_1.shape[-1])\n trans_01 = trans_01.reshape(-1, trans_01.shape[-2], trans_01.shape[-1])\n # We expand trans_01 to match the dimensions needed for bmm\n trans_01 = torch.repeat_interleave(trans_01, repeats=points_1.shape[0] // trans_01.shape[0], dim=0)\n # to homogeneous\n points_1_h = convert_points_to_homogeneous(points_1) # BxNxD+1\n # transform coordinates\n points_0_h = torch.bmm(points_1_h, trans_01.permute(0, 2, 1))\n points_0_h = torch.squeeze(points_0_h, dim=-1)\n # to euclidean\n points_0 = convert_points_from_homogeneous(points_0_h) # BxNxD\n # reshape to the input shape\n shape_inp[-2] = points_0.shape[-2]\n shape_inp[-1] = points_0.shape[-1]\n points_0 = points_0.reshape(shape_inp)\n return points_0\n\n# TODO:\n# - project_points: from opencv\n", "from typing import Dict, Optional, Tuple, Union, cast\n\nimport torch\nfrom torch.distributions import Uniform\n\nfrom kornia.augmentation.random_generator.base import RandomGeneratorBase\nfrom kornia.augmentation.utils import (\n _adapted_rsampling,\n _adapted_uniform,\n _common_param_check,\n _joint_range_check,\n _range_bound,\n)\nfrom kornia.utils.helpers import _deprecated, _extract_device_dtype\n\n\nclass AffineGenerator(RandomGeneratorBase):\n r\"\"\"Get parameters for ``affine`` for a random affine transform.\n\n Args:\n degrees: Range of degrees to select from like (min, max).\n translate: tuple of maximum absolute fraction for horizontal\n and vertical translations. For example translate=(a, b), then horizontal shift\n is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is\n randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default.\n scale: scaling factor interval, e.g (a, b), then scale is\n randomly sampled from the range a <= scale <= b. Will keep original scale by default.\n shear: Range of degrees to select from.\n If float, a shear parallel to the x axis in the range (-shear, +shear) will be applied.\n If (a, b), a shear parallel to the x axis in the range (-shear, +shear) will be applied.\n If (a, b, c, d), then x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3])\n will be applied. Will not apply shear by default.\n If tensor, shear is a 2x2 tensor, a x-axis shear in (shear[0][0], shear[0][1]) and y-axis shear in\n (shear[1][0], shear[1][1]) will be applied. Will not apply shear by default.\n\n Returns:\n A dict of parameters to be passed for transformation.\n - translations (torch.Tensor): element-wise translations with a shape of (B, 2).\n - center (torch.Tensor): element-wise center with a shape of (B, 2).\n - scale (torch.Tensor): element-wise scales with a shape of (B, 2).\n - angle (torch.Tensor): element-wise rotation angles with a shape of (B,).\n - sx (torch.Tensor): element-wise x-axis shears with a shape of (B,).\n - sy (torch.Tensor): element-wise y-axis shears with a shape of (B,).\n\n Note:\n The generated random numbers are not reproducible across different devices and dtypes. By default,\n the parameters will be generated on CPU in float32. This can be changed by calling\n ``self.set_rng_device_and_dtype(device=\"cuda\", dtype=torch.float64)``.\n \"\"\"\n\n def __init__(\n self,\n degrees: Union[torch.Tensor, float, Tuple[float, float]],\n translate: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,\n scale: Optional[Union[torch.Tensor, Tuple[float, float], Tuple[float, float, float, float]]] = None,\n shear: Optional[Union[torch.Tensor, float, Tuple[float, float]]] = None,\n ) -> None:\n super().__init__()\n self.degrees = degrees\n self.translate = translate\n self.scale = scale\n self.shear = shear\n\n def __repr__(self) -> str:\n repr = f\"degrees={self.degrees}, translate={self.translate}, scale={self.scale}, shear={self.shear}\"\n return repr\n\n def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:\n _degrees = _range_bound(self.degrees, 'degrees', 0, (-360, 360)).to(device=device, dtype=dtype)\n _translate = (\n self.translate\n if self.translate is None\n else _range_bound(self.translate, 'translate', bounds=(0, 1), check='singular').to(\n device=device, dtype=dtype\n )\n )\n _scale: Optional[torch.Tensor] = None\n if self.scale is not None:\n if len(self.scale) == 2:\n _scale = _range_bound(self.scale[:2], 'scale', bounds=(0, float('inf')), check='singular').to(\n device=device, dtype=dtype\n )\n elif len(self.scale) == 4:\n _scale = torch.cat(\n [\n _range_bound(self.scale[:2], 'scale_x', bounds=(0, float('inf')), check='singular'),\n _range_bound(\n self.scale[2:], 'scale_y', bounds=(0, float('inf')), check='singular' # type:ignore\n ),\n ]\n ).to(device=device, dtype=dtype)\n else:\n raise ValueError(f\"'scale' expected to be either 2 or 4 elements. Got {self.scale}\")\n _shear: Optional[torch.Tensor] = None\n if self.shear is not None:\n shear = torch.as_tensor(self.shear, device=device, dtype=dtype)\n if shear.shape == torch.Size([2, 2]):\n _shear = shear\n else:\n _shear = torch.stack(\n [\n _range_bound(shear if shear.dim() == 0 else shear[:2], 'shear-x', 0, (-360, 360)),\n torch.tensor([0, 0], device=device, dtype=dtype)\n if shear.dim() == 0 or len(shear) == 2\n else _range_bound(shear[2:], 'shear-y', 0, (-360, 360)),\n ]\n )\n\n translate_x_sampler: Optional[Uniform] = None\n translate_y_sampler: Optional[Uniform] = None\n scale_2_sampler: Optional[Uniform] = None\n scale_4_sampler: Optional[Uniform] = None\n shear_x_sampler: Optional[Uniform] = None\n shear_y_sampler: Optional[Uniform] = None\n\n if _translate is not None:\n translate_x_sampler = Uniform(-_translate[0], _translate[0], validate_args=False)\n translate_y_sampler = Uniform(-_translate[1], _translate[1], validate_args=False)\n if _scale is not None:\n if len(_scale) == 2:\n scale_2_sampler = Uniform(_scale[0], _scale[1], validate_args=False)\n elif len(_scale) == 4:\n scale_2_sampler = Uniform(_scale[0], _scale[1], validate_args=False)\n scale_4_sampler = Uniform(_scale[2], _scale[3], validate_args=False)\n else:\n raise ValueError(f\"'scale' expected to be either 2 or 4 elements. Got {self.scale}\")\n if _shear is not None:\n _joint_range_check(cast(torch.Tensor, _shear)[0], \"shear\")\n _joint_range_check(cast(torch.Tensor, _shear)[1], \"shear\")\n shear_x_sampler = Uniform(_shear[0][0], _shear[0][1], validate_args=False)\n shear_y_sampler = Uniform(_shear[1][0], _shear[1][1], validate_args=False)\n\n self.degree_sampler = Uniform(_degrees[0], _degrees[1], validate_args=False)\n self.translate_x_sampler = translate_x_sampler\n self.translate_y_sampler = translate_y_sampler\n self.scale_2_sampler = scale_2_sampler\n self.scale_4_sampler = scale_4_sampler\n self.shear_x_sampler = shear_x_sampler\n self.shear_y_sampler = shear_y_sampler\n\n def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type: ignore\n batch_size = batch_shape[0]\n height = batch_shape[-2]\n width = batch_shape[-1]\n\n _device, _dtype = _extract_device_dtype([self.degrees, self.translate, self.scale, self.shear])\n _common_param_check(batch_size, same_on_batch)\n if not (isinstance(width, (int,)) and isinstance(height, (int,)) and width > 0 and height > 0):\n raise AssertionError(f\"`width` and `height` must be positive integers. Got {width}, {height}.\")\n\n angle = _adapted_rsampling((batch_size,), self.degree_sampler, same_on_batch).to(device=_device, dtype=_dtype)\n\n # compute tensor ranges\n if self.scale_2_sampler is not None:\n _scale = _adapted_rsampling((batch_size,), self.scale_2_sampler, same_on_batch).unsqueeze(1).repeat(1, 2)\n if self.scale_4_sampler is not None:\n _scale[:, 1] = _adapted_rsampling((batch_size,), self.scale_4_sampler, same_on_batch)\n _scale = _scale.to(device=_device, dtype=_dtype)\n else:\n _scale = torch.ones((batch_size, 2), device=_device, dtype=_dtype)\n\n if self.translate_x_sampler is not None and self.translate_y_sampler is not None:\n translations = torch.stack(\n [\n _adapted_rsampling((batch_size,), self.translate_x_sampler, same_on_batch) * width,\n _adapted_rsampling((batch_size,), self.translate_y_sampler, same_on_batch) * height,\n ],\n dim=-1,\n )\n translations = translations.to(device=_device, dtype=_dtype)\n else:\n translations = torch.zeros((batch_size, 2), device=_device, dtype=_dtype)\n\n center: torch.Tensor = torch.tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5\n center = center.expand(batch_size, -1)\n\n if self.shear_x_sampler is not None and self.shear_y_sampler is not None:\n sx = _adapted_rsampling((batch_size,), self.shear_x_sampler, same_on_batch)\n sy = _adapted_rsampling((batch_size,), self.shear_y_sampler, same_on_batch)\n sx = sx.to(device=_device, dtype=_dtype)\n sy = sy.to(device=_device, dtype=_dtype)\n else:\n sx = sy = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)\n\n return dict(translations=translations, center=center, scale=_scale, angle=angle, sx=sx, sy=sy)\n\n\n@_deprecated(replace_with=AffineGenerator.__name__)\ndef random_affine_generator(\n batch_size: int,\n height: int,\n width: int,\n degrees: torch.Tensor,\n translate: Optional[torch.Tensor] = None,\n scale: Optional[torch.Tensor] = None,\n shear: Optional[torch.Tensor] = None,\n same_on_batch: bool = False,\n device: torch.device = torch.device('cpu'),\n dtype: torch.dtype = torch.float32,\n) -> Dict[str, torch.Tensor]:\n r\"\"\"Get parameters for ``affine`` for a random affine transform.\n\n Args:\n batch_size (int): the tensor batch size.\n height (int) : height of the image.\n width (int): width of the image.\n degrees (torch.Tensor): Range of degrees to select from like (min, max).\n translate (tensor, optional): tuple of maximum absolute fraction for horizontal\n and vertical translations. For example translate=(a, b), then horizontal shift\n is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is\n randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default.\n scale (tensor, optional): scaling factor interval, e.g (a, b), then scale is\n randomly sampled from the range a <= scale <= b. Will keep original scale by default.\n shear (tensor, optional): Range of degrees to select from.\n Shear is a 2x2 tensor, a x-axis shear in (shear[0][0], shear[0][1]) and y-axis shear in\n (shear[1][0], shear[1][1]) will be applied. Will not apply shear by default.\n same_on_batch (bool): apply the same transformation across the batch. Default: False.\n device (torch.device): the device on which the random numbers will be generated. Default: cpu.\n dtype (torch.dtype): the data type of the generated random numbers. Default: float32.\n\n Returns:\n params Dict[str, torch.Tensor]: parameters to be passed for transformation.\n - translations (torch.Tensor): element-wise translations with a shape of (B, 2).\n - center (torch.Tensor): element-wise center with a shape of (B, 2).\n - scale (torch.Tensor): element-wise scales with a shape of (B, 2).\n - angle (torch.Tensor): element-wise rotation angles with a shape of (B,).\n - sx (torch.Tensor): element-wise x-axis shears with a shape of (B,).\n - sy (torch.Tensor): element-wise y-axis shears with a shape of (B,).\n\n Note:\n The generated random numbers are not reproducible across different devices and dtypes.\n \"\"\"\n _common_param_check(batch_size, same_on_batch)\n _joint_range_check(degrees, \"degrees\")\n if not (isinstance(width, (int,)) and isinstance(height, (int,)) and width > 0 and height > 0):\n raise AssertionError(f\"`width` and `height` must be positive integers. Got {width}, {height}.\")\n\n _device, _dtype = _extract_device_dtype([degrees, translate, scale, shear])\n degrees = degrees.to(device=device, dtype=dtype)\n angle = _adapted_uniform((batch_size,), degrees[0], degrees[1], same_on_batch)\n angle = angle.to(device=_device, dtype=_dtype)\n\n # compute tensor ranges\n if scale is not None:\n scale = scale.to(device=device, dtype=dtype)\n if not (len(scale.shape) == 1 and len(scale) in (2, 4)):\n raise AssertionError(f\"`scale` shall have 2 or 4 elements. Got {scale}.\")\n _joint_range_check(cast(torch.Tensor, scale[:2]), \"scale\")\n _scale = _adapted_uniform((batch_size,), scale[0], scale[1], same_on_batch).unsqueeze(1).repeat(1, 2)\n if len(scale) == 4:\n _joint_range_check(cast(torch.Tensor, scale[2:]), \"scale_y\")\n _scale[:, 1] = _adapted_uniform((batch_size,), scale[2], scale[3], same_on_batch)\n _scale = _scale.to(device=_device, dtype=_dtype)\n else:\n _scale = torch.ones((batch_size, 2), device=_device, dtype=_dtype)\n\n if translate is not None:\n translate = translate.to(device=device, dtype=dtype)\n if not (0.0 <= translate[0] <= 1.0 and 0.0 <= translate[1] <= 1.0 and translate.shape == torch.Size([2])):\n raise AssertionError(f\"Expect translate contains two elements and ranges are in [0, 1]. Got {translate}.\")\n max_dx: torch.Tensor = translate[0] * width\n max_dy: torch.Tensor = translate[1] * height\n translations = torch.stack(\n [\n _adapted_uniform((batch_size,), -max_dx, max_dx, same_on_batch),\n _adapted_uniform((batch_size,), -max_dy, max_dy, same_on_batch),\n ],\n dim=-1,\n )\n translations = translations.to(device=_device, dtype=_dtype)\n else:\n translations = torch.zeros((batch_size, 2), device=_device, dtype=_dtype)\n\n center: torch.Tensor = torch.tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5\n center = center.expand(batch_size, -1)\n\n if shear is not None:\n shear = shear.to(device=device, dtype=dtype)\n _joint_range_check(cast(torch.Tensor, shear)[0], \"shear\")\n _joint_range_check(cast(torch.Tensor, shear)[1], \"shear\")\n sx = _adapted_uniform((batch_size,), shear[0][0], shear[0][1], same_on_batch)\n sy = _adapted_uniform((batch_size,), shear[1][0], shear[1][1], same_on_batch)\n sx = sx.to(device=_device, dtype=_dtype)\n sy = sy.to(device=_device, dtype=_dtype)\n else:\n sx = sy = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)\n\n return dict(translations=translations, center=center, scale=_scale, angle=angle, sx=sx, sy=sy)\n" ]
[ [ "torch.mean", "torch.zeros_like", "torch.sum", "torch.exp", "torch.arange", "torch.ones_like" ], [ "torch.cat", "torch.nn.Conv2d", "torch.nn.init.xavier_normal_", "torch.tensor", "torch.exp", "torch.nn.BatchNorm2d", "torch.device", "torch.nn.ReLU", "torch.nn.functional.max_pool2d", "torch.hub.load_state_dict_from_url" ], [ "torch.no_grad" ], [ "torch.jit.script", "torch.autograd.gradcheck", "torch.rand", "torch.ones" ], [ "torch.ones", "torch.Tensor", "torch.zeros_like", "torch.rand", "torch.autograd.gradcheck", "torch.ones_like" ], [ "torch.transpose", "torch.zeros_like", "torch.is_tensor", "torch.matmul", "torch.repeat_interleave", "torch.squeeze" ], [ "torch.Size", "torch.ones", "torch.zeros", "torch.tensor", "torch.device", "torch.distributions.Uniform", "torch.as_tensor" ] ]
[ { "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": [] } ]
Rosna/P4ML-UI
[ "edf0dd830588f03b197e4d6532830a5aedd88424" ]
[ "spider/featurization/load_subclip_audio.py" ]
[ "import argparse\nimport librosa\nimport numpy as np\n\ndef make_subclips(audio, sr, clip_size, pad=True):\n # Given a list of audio files and corresponding sample rates,\n # return a 2D list of subclips, each of size clip_size\n # Optional padding takes care of audio files shorter than clip size\n clips = []\n for idx, a in enumerate(audio):\n\n # Size of a single clip in samples\n step = int(sr[idx] * clip_size)\n\n # Optional padding for short clips\n overhang = len(a) % step\n if overhang != 0 and pad:\n a = np.concatenate([a, np.zeros(step - overhang)])\n\n subclips = []\n for start in range(0, len(a), step):\n\n end = start + step\n if end > len(a):\n break\n\n subclips.append(a[start : end])\n\n return subclips\n\ndef main(audio_file, clip_size):\n\n # In python 2.7, librosa.load does not correctly handle 24-bit wav files.\n # This is resolved in python 3.x\n # \n # If the sr parameter is set to None, loads the actual sampling rate\n # from the audio file. Otherwise, will load the audio file and resample\n # it to the given sample rate. This is good if you want all audio at the\n # same sample rate, but can be slow. Default is 22050 Hz.\n audio, sr = librosa.load(audio_file, sr=None)\n\n # We just have one audio file here, but this should work for any number\n audio_subclips = make_subclips([audio], [sr], 1.0)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--audio_file', type=str, required=True)\n parser.add_argument('--clip_size', type=float, default=0)\n args = parser.parse_args()\n main(args.audio_file, args.clip_size)\n" ]
[ [ "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Johnzhjw/CIT2FR-FL-NAS
[ "53e93075ff1834ab817ad6359025ddafd20e6ef4", "53e93075ff1834ab817ad6359025ddafd20e6ef4" ]
[ "run_manager.py", "moead.py" ]
[ "# Once for All: Train One Network and Specialize it for Efficient Deployment\n# Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han\n# International Conference on Learning Representations (ICLR), 2020.\n\nimport os\nimport time\nimport json\nimport math\nfrom tqdm import tqdm\n\nimport numpy as np\n\nimport copy\n\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim\nimport torchvision\n\n# from imagenet_codebase.utils import *\nfrom ofa.imagenet_codebase.utils import count_parameters, count_net_flops, measure_net_latency, \\\n cross_entropy_loss_with_soft_target, cross_entropy_with_label_smoothing\nfrom ofa.utils import AverageMeter, accuracy\n\n\nclass RunConfig:\n\n def __init__(self, n_epochs, init_lr, lr_schedule_type, lr_schedule_param,\n dataset, train_batch_size, test_batch_size, valid_size,\n opt_type, opt_param, weight_decay, label_smoothing, no_decay_keys,\n mixup_alpha,\n model_init, validation_frequency, print_frequency):\n self.n_epochs = n_epochs\n self.init_lr = init_lr\n self.lr_schedule_type = lr_schedule_type\n self.lr_schedule_param = lr_schedule_param\n\n self.dataset = dataset\n self.train_batch_size = train_batch_size\n self.test_batch_size = test_batch_size\n self.valid_size = valid_size\n\n self.opt_type = opt_type\n self.opt_param = opt_param\n self.weight_decay = weight_decay\n self.label_smoothing = label_smoothing\n self.no_decay_keys = no_decay_keys\n\n self.mixup_alpha = mixup_alpha\n\n self.model_init = model_init\n self.validation_frequency = validation_frequency\n self.print_frequency = print_frequency\n\n @property\n def config(self):\n config = {}\n for key in self.__dict__:\n if not key.startswith('_'):\n config[key] = self.__dict__[key]\n return config\n\n def copy(self):\n return RunConfig(**self.config)\n\n \"\"\" learning rate \"\"\"\n\n def calc_learning_rate(self, epoch, batch=0, nBatch=None):\n if self.lr_schedule_type == 'cosine':\n T_total = self.n_epochs * nBatch\n T_cur = epoch * nBatch + batch\n lr = 0.5 * self.init_lr * (1 + math.cos(math.pi * T_cur / T_total))\n elif self.lr_schedule_type is None:\n lr = self.init_lr\n else:\n raise ValueError('do not support: %s' % self.lr_schedule_type)\n return lr\n\n def adjust_learning_rate(self, optimizer, epoch, batch=0, nBatch=None):\n \"\"\" adjust learning of a given optimizer and return the new learning rate \"\"\"\n new_lr = self.calc_learning_rate(epoch, batch, nBatch)\n for param_group in optimizer.param_groups:\n param_group['lr'] = new_lr\n return new_lr\n\n def warmup_adjust_learning_rate(self, optimizer, T_total, nBatch, epoch, batch=0, warmup_lr=0):\n T_cur = epoch * nBatch + batch + 1\n new_lr = T_cur / T_total * (self.init_lr - warmup_lr) + warmup_lr\n for param_group in optimizer.param_groups:\n param_group['lr'] = new_lr\n return new_lr\n\n \"\"\" data provider \"\"\"\n\n @property\n def data_provider(self):\n raise NotImplementedError\n\n def train_FL_loader(self, _):\n return self.data_provider.train_splits[_]\n\n @property\n def train_loader(self):\n return self.data_provider.train\n\n @property\n def valid_loader(self):\n return self.data_provider.valid\n\n @property\n def test_loader(self):\n return self.data_provider.test\n\n def random_sub_train_loader(self, n_images, batch_size, num_worker=None, num_replicas=None, rank=None, tag_FL=-1):\n return self.data_provider.build_sub_train_loader(n_images, batch_size, num_worker, num_replicas, rank, tag_FL)\n\n \"\"\" optimizer \"\"\"\n\n def build_optimizer(self, net_params):\n if self.no_decay_keys is not None:\n assert isinstance(net_params, list) and len(net_params) == 2\n net_params = [\n {'params': net_params[0], 'weight_decay': self.weight_decay},\n {'params': net_params[1], 'weight_decay': 0},\n ]\n else:\n net_params = [{'params': net_params, 'weight_decay': self.weight_decay}]\n\n if self.opt_type == 'sgd':\n opt_param = {} if self.opt_param is None else self.opt_param\n momentum, nesterov = opt_param.get('momentum', 0.9), opt_param.get('nesterov', True)\n optimizer = torch.optim.SGD(net_params, self.init_lr, momentum=momentum, nesterov=nesterov)\n elif self.opt_type == 'adam':\n optimizer = torch.optim.Adam(net_params, self.init_lr)\n else:\n raise NotImplementedError\n return optimizer\n\n\ndef get_net_info(net, input_shape=(3, 224, 224), measure_latency=None, print_info=True):\n net_info = {}\n if isinstance(net, nn.DataParallel):\n net = net.module\n\n # parameters\n net_info['params'] = count_parameters(net)\n\n # flops\n net_info['flops'] = count_net_flops(net, [2] + list(input_shape))/2\n\n # latencies\n latency_types = [] if measure_latency is None else measure_latency.split('#')\n for l_type in latency_types:\n latency, measured_latency = measure_net_latency(net, l_type, fast=False, input_shape=input_shape)\n net_info['%s latency' % l_type] = {\n 'val': latency,\n 'hist': measured_latency\n }\n\n if print_info:\n print(net)\n print('Total training params: %.2fM' % (net_info['params'] / 1e6))\n print('Total FLOPs: %.2fM' % (net_info['flops'] / 1e6))\n for l_type in latency_types:\n print('Estimated %s latency: %.3fms' % (l_type, net_info['%s latency' % l_type]['val']))\n\n return net_info\n\n\nclass RunManager:\n\n def __init__(self, path, net, run_config: RunConfig, init=True, measure_latency=None, no_gpu=False, mix_prec=None):\n self.path = path\n self.net = net\n self.run_config = run_config\n self.mix_prec = mix_prec\n\n self.best_acc = 0\n self.start_epoch = 0\n\n os.makedirs(self.path, exist_ok=True)\n\n # move network to GPU if available\n if torch.cuda.is_available() and (not no_gpu):\n self.device = torch.device('cuda:0')\n self.net = self.net.to(self.device)\n cudnn.benchmark = True\n else:\n self.device = torch.device('cpu')\n # initialize model (default)\n if init:\n self.network.init_model(run_config.model_init)\n\n # net info\n net_info = get_net_info(self.net, self.run_config.data_provider.data_shape, measure_latency, True)\n with open('%s/net_info.txt' % self.path, 'w') as fout:\n fout.write(json.dumps(net_info, indent=4) + '\\n')\n try:\n fout.write(self.network.module_str)\n except Exception:\n pass\n\n # criterion\n if isinstance(self.run_config.mixup_alpha, float):\n self.train_criterion = cross_entropy_loss_with_soft_target\n elif self.run_config.label_smoothing > 0:\n self.train_criterion = lambda pred, target: \\\n cross_entropy_with_label_smoothing(pred, target, self.run_config.label_smoothing)\n else:\n self.train_criterion = nn.CrossEntropyLoss()\n self.test_criterion = nn.CrossEntropyLoss()\n\n # optimizer\n if self.run_config.no_decay_keys:\n keys = self.run_config.no_decay_keys.split('#')\n net_params = [\n self.network.get_parameters(keys, mode='exclude'), # parameters with weight decay\n self.network.get_parameters(keys, mode='include'), # parameters without weight decay\n ]\n else:\n try:\n net_params = self.network.weight_parameters()\n except Exception:\n net_params = self.network.parameters()\n self.optimizer = self.run_config.build_optimizer(net_params)\n\n if mix_prec is not None:\n from apex import amp\n self.network, self.optimizer = amp.initialize(self.network, self.optimizer, opt_level=mix_prec)\n\n self.net = torch.nn.DataParallel(self.net)\n\n def init_FL(self, flag_reset_running_statistics):\n \"\"\" FL \"\"\"\n if self.run_config.flag_FL:\n self.nets_FL = []\n self.optimizers_FL = []\n for _ in range(self.run_config.size_FL):\n self.nets_FL.append(copy.deepcopy(self.net))\n if flag_reset_running_statistics:\n self.reset_running_statistics(self.network_FL(_), _)\n for _ in range(self.run_config.size_FL):\n if self.run_config.no_decay_keys:\n keys = self.run_config.no_decay_keys.split('#')\n net_params = [\n self.network_FL(_).get_parameters(keys, mode='exclude'), # parameters with weight decay\n self.network_FL(_).get_parameters(keys, mode='include'), # parameters without weight decay\n ]\n else:\n try:\n net_params = self.network_FL(_).weight_parameters()\n except Exception:\n net_params = self.network_FL(_).parameters()\n self.optimizers_FL.append(self.run_config.build_optimizer(net_params))\n\n \"\"\" save path and log path \"\"\"\n\n @property\n def save_path(self):\n if self.__dict__.get('_save_path', None) is None:\n save_path = os.path.join(self.path, 'checkpoint')\n os.makedirs(save_path, exist_ok=True)\n self.__dict__['_save_path'] = save_path\n return self.__dict__['_save_path']\n\n @property\n def logs_path(self):\n if self.__dict__.get('_logs_path', None) is None:\n logs_path = os.path.join(self.path, 'logs')\n os.makedirs(logs_path, exist_ok=True)\n self.__dict__['_logs_path'] = logs_path\n return self.__dict__['_logs_path']\n\n def network_FL(self, _):\n if isinstance(self.nets_FL[_], nn.DataParallel):\n return self.nets_FL[_].module\n else:\n return self.nets_FL[_]\n\n @property\n def network(self):\n if isinstance(self.net, nn.DataParallel):\n return self.net.module\n else:\n return self.net\n\n @network.setter\n def network(self, new_val):\n if isinstance(self.net, nn.DataParallel):\n self.net.module = new_val\n else:\n self.net = new_val\n\n def write_log(self, log_str, prefix='valid', should_print=True):\n \"\"\" prefix: valid, train, test \"\"\"\n if prefix in ['valid', 'test']:\n with open(os.path.join(self.logs_path, 'valid_console.txt'), 'a') as fout:\n fout.write(log_str + '\\n')\n fout.flush()\n if prefix in ['valid', 'test', 'train']:\n with open(os.path.join(self.logs_path, 'train_console.txt'), 'a') as fout:\n if prefix in ['valid', 'test']:\n fout.write('=' * 10)\n fout.write(log_str + '\\n')\n fout.flush()\n else:\n with open(os.path.join(self.logs_path, '%s.txt' % prefix), 'a') as fout:\n fout.write(log_str + '\\n')\n fout.flush()\n if should_print:\n print(log_str)\n\n \"\"\" save and load models \"\"\"\n\n def save_model(self, checkpoint=None, is_best=False, model_name=None):\n if checkpoint is None:\n checkpoint = {'state_dict': self.network.state_dict()}\n\n if model_name is None:\n model_name = 'checkpoint.pth.tar'\n\n if self.mix_prec is not None:\n from apex import amp\n checkpoint['amp'] = amp.state_dict()\n\n checkpoint['dataset'] = self.run_config.dataset # add `dataset` info to the checkpoint\n latest_fname = os.path.join(self.save_path, 'latest.txt')\n model_path = os.path.join(self.save_path, model_name)\n with open(latest_fname, 'w') as fout:\n fout.write(model_path + '\\n')\n torch.save(checkpoint, model_path)\n\n if is_best:\n best_path = os.path.join(self.save_path, 'model_best.pth.tar')\n torch.save({'state_dict': checkpoint['state_dict']}, best_path)\n\n def load_model(self, model_fname=None):\n latest_fname = os.path.join(self.save_path, 'latest.txt')\n if model_fname is None and os.path.exists(latest_fname):\n with open(latest_fname, 'r') as fin:\n model_fname = fin.readline()\n if model_fname[-1] == '\\n':\n model_fname = model_fname[:-1]\n try:\n if model_fname is None or not os.path.exists(model_fname):\n model_fname = '%s/checkpoint.pth.tar' % self.save_path\n with open(latest_fname, 'w') as fout:\n fout.write(model_fname + '\\n')\n print(\"=> loading checkpoint '{}'\".format(model_fname))\n\n if torch.cuda.is_available():\n checkpoint = torch.load(model_fname)\n else:\n checkpoint = torch.load(model_fname, map_location='cpu')\n\n self.network.load_state_dict(checkpoint['state_dict'])\n\n if 'epoch' in checkpoint:\n self.start_epoch = checkpoint['epoch'] + 1\n if 'best_acc' in checkpoint:\n self.best_acc = checkpoint['best_acc']\n if 'optimizer' in checkpoint:\n self.optimizer.load_state_dict(checkpoint['optimizer'])\n if self.mix_prec is not None and 'amp' in checkpoint:\n from apex import amp\n amp.load_state_dict(checkpoint['amp'])\n\n print(\"=> loaded checkpoint '{}'\".format(model_fname))\n except Exception:\n print('fail to load checkpoint from %s' % self.save_path)\n\n def save_config(self):\n \"\"\" dump run_config and net_config to the model_folder \"\"\"\n net_save_path = os.path.join(self.path, 'net.config')\n json.dump(self.network.config, open(net_save_path, 'w'), indent=4)\n print('Network configs dump to %s' % net_save_path)\n\n run_save_path = os.path.join(self.path, 'run.config')\n json.dump(self.run_config.config, open(run_save_path, 'w'), indent=4)\n print('Run configs dump to %s' % run_save_path)\n\n \"\"\" train and test \"\"\"\n\n def validate(self, epoch=0, is_test=True, run_str='', net=None, data_loader=None, no_logs=False):\n if net is None:\n net = self.net\n if not isinstance(net, nn.DataParallel):\n net = nn.DataParallel(net)\n\n if data_loader is None:\n if is_test:\n data_loader = self.run_config.test_loader\n else:\n data_loader = self.run_config.valid_loader\n\n net.eval()\n\n losses = AverageMeter()\n top1 = AverageMeter()\n top5 = AverageMeter()\n\n with torch.no_grad():\n with tqdm(total=len(data_loader),\n desc='Validate Epoch #{} {}'.format(epoch + 1, run_str), disable=no_logs) as t:\n for i, (images, labels) in enumerate(data_loader):\n images, labels = images.to(self.device), labels.to(self.device)\n # compute output\n output = net(images)\n loss = self.test_criterion(output, labels.long())\n # measure accuracy and record loss\n acc1 = accuracy(output, labels, topk=(1,))\n\n losses.update(loss.item(), images.size(0))\n top1.update(acc1[0].item(), images.size(0))\n t.set_postfix({\n 'loss': losses.avg,\n 'top1': top1.avg,\n 'img_size': images.size(2),\n })\n t.update(1)\n return losses.avg, top1.avg\n\n def validate_all_resolution(self, epoch=0, is_test=True, net=None):\n if net is None:\n net = self.network\n if isinstance(self.run_config.data_provider.image_size, list):\n img_size_list, loss_list, top1_list, top5_list = [], [], [], []\n for img_size in self.run_config.data_provider.image_size:\n img_size_list.append(img_size)\n self.run_config.data_provider.assign_active_img_size(img_size)\n if not self.run_config.flag_FL:\n self.reset_running_statistics(net=net)\n else:\n self.reset_running_statistics(net=None, tag_FL=self.run_config.size_FL)\n loss, top1 = self.validate(epoch, is_test, net=net)\n loss_list.append(loss)\n top1_list.append(top1)\n return img_size_list, loss_list, top1_list\n else:\n loss, top1 = self.validate(epoch, is_test, net=net)\n return [self.run_config.data_provider.active_img_size], [loss], [top1]\n\n def train_one_epoch(self, args, epoch, warmup_epochs=0, warmup_lr=0, tag_FL=-1):\n # switch to train mode\n if tag_FL >= 0:\n self.nets_FL[tag_FL].train()\n else:\n self.net.train()\n\n if tag_FL >= 0:\n data_loader = self.run_config.train_FL_loader(tag_FL)\n else:\n data_loader = self.run_config.train_loader\n nBatch = len(data_loader)\n\n losses = AverageMeter()\n top1 = AverageMeter()\n top5 = AverageMeter()\n data_time = AverageMeter()\n\n with tqdm(total=nBatch,\n desc='Train Epoch #{}'.format(epoch + 1)) as t:\n end = time.time()\n for i, (images, labels) in enumerate(data_loader):\n data_time.update(time.time() - end)\n if tag_FL >= 0:\n if epoch < warmup_epochs:\n new_lr = self.run_config.warmup_adjust_learning_rate(\n self.optimizers_FL[tag_FL], warmup_epochs * nBatch, nBatch, epoch, i, warmup_lr,\n )\n else:\n new_lr = self.run_config.adjust_learning_rate(self.optimizers_FL[tag_FL], epoch - warmup_epochs, i, nBatch)\n else:\n if epoch < warmup_epochs:\n new_lr = self.run_config.warmup_adjust_learning_rate(\n self.optimizer, warmup_epochs * nBatch, nBatch, epoch, i, warmup_lr,\n )\n else:\n new_lr = self.run_config.adjust_learning_rate(self.optimizer, epoch - warmup_epochs, i, nBatch)\n\n images, labels = images.to(self.device), labels.to(self.device)\n target = labels\n\n # soft target\n if args.teacher_model is not None:\n args.teacher_model.train()\n with torch.no_grad():\n soft_logits = args.teacher_model(images).detach()\n soft_label = F.softmax(soft_logits, dim=1)\n\n # compute output\n if isinstance(self.network, torchvision.models.Inception3):\n if tag_FL >= 0:\n output, aux_outputs = self.nets_FL[tag_FL](images)\n else:\n output, aux_outputs = self.net(images)\n loss1 = self.train_criterion(output, labels.long())\n loss2 = self.train_criterion(aux_outputs, labels.long())\n loss = loss1 + 0.4 * loss2\n else:\n if tag_FL >= 0:\n output = self.nets_FL[tag_FL](images)\n else:\n output = self.net(images)\n loss = self.train_criterion(output, labels.long())\n\n if args.teacher_model is None:\n loss_type = 'ce'\n else:\n if args.kd_type == 'ce':\n kd_loss = cross_entropy_loss_with_soft_target(output, soft_label)\n else:\n kd_loss = F.mse_loss(output, soft_logits)\n loss = args.kd_ratio * kd_loss + loss\n loss_type = '%.1fkd-%s & ce' % (args.kd_ratio, args.kd_type)\n\n # compute gradient and do SGD step\n if tag_FL >= 0:\n self.nets_FL[tag_FL].zero_grad() # or self.optimizer.zero_grad()\n else:\n self.net.zero_grad() # or self.optimizer.zero_grad()\n if self.mix_prec is not None:\n from apex import amp\n if tag_FL >= 0:\n with amp.scale_loss(loss, self.optimizers_FL[tag_FL]) as scaled_loss:\n scaled_loss.backward()\n else:\n with amp.scale_loss(loss, self.optimizer) as scaled_loss:\n scaled_loss.backward()\n else:\n loss.backward()\n if tag_FL >= 0:\n self.optimizers_FL[tag_FL].step()\n else:\n self.optimizer.step()\n\n # measure accuracy and record loss\n acc1 = accuracy(output, target, topk=(1,))\n losses.update(loss.item(), images.size(0))\n top1.update(acc1[0].item(), images.size(0))\n\n t.set_postfix({\n 'loss': losses.avg,\n 'top1': top1.avg,\n 'img_size': images.size(2),\n 'lr': new_lr,\n 'loss_type': loss_type,\n 'data_time': data_time.avg,\n })\n t.update(1)\n end = time.time()\n return losses.avg, top1.avg\n\n def FedAvg(self):\n if self.run_config.flag_FL:\n with torch.no_grad():\n base_state = self.network.state_dict()\n all_states = []\n for _ in range(self.run_config.size_FL):\n model = self.network_FL(_)\n all_states.append(model.state_dict())\n for name in base_state:\n for _ in range(self.run_config.size_FL):\n # print(all_states[_][name].shape)\n # print(all_states[_][name])\n tmp_state = (all_states[_][name] / self.run_config.size_FL) if _ == 0 else \\\n tmp_state + (all_states[_][name] / self.run_config.size_FL)\n base_state[name].copy_(tmp_state)\n self.network.load_state_dict(base_state)\n for _ in range(self.run_config.size_FL):\n self.network_FL(_).load_state_dict(base_state)\n\n def train(self, args, warmup_epoch=0, warmup_lr=0, flag_reset_running_statistics=False):\n self.init_FL(flag_reset_running_statistics)\n\n for epoch in range(self.start_epoch, self.run_config.n_epochs + warmup_epoch):\n if not self.run_config.flag_FL:\n train_loss, train_top1 = self.train_one_epoch(args, epoch, warmup_epoch, warmup_lr)\n else:\n train_loss, train_top1 = [], []\n for _ in range(self.run_config.size_FL):\n loss, top1 = self.train_one_epoch(args, epoch, warmup_epoch, warmup_lr, _)\n train_loss.append(loss)\n train_top1.append(top1)\n train_loss = np.mean(train_loss)\n train_top1 = np.mean(train_top1)\n self.FedAvg()\n\n if (epoch + 1) % self.run_config.validation_frequency == 0:\n img_size, val_loss, val_acc = self.validate_all_resolution(epoch=epoch, is_test=False)\n\n is_best = np.mean(val_acc) > self.best_acc\n self.best_acc = max(self.best_acc, np.mean(val_acc))\n val_log = 'Valid [{0}/{1}]\\tloss {2:.3f}\\ttop-1 acc {3:.3f} ({4:.3f})'. \\\n format(epoch + 1 - warmup_epoch, self.run_config.n_epochs,\n np.mean(val_loss), np.mean(val_acc), self.best_acc)\n val_log += '\\tTrain top-1 {top1:.3f}\\tloss {train_loss:.3f}\\t'. \\\n format(top1=train_top1, train_loss=train_loss)\n for i_s, v_a in zip(img_size, val_acc):\n val_log += '(%d, %.3f), ' % (i_s, v_a)\n self.write_log(val_log, prefix='valid', should_print=False)\n else:\n is_best = False\n\n self.save_model({\n 'epoch': epoch,\n 'best_acc': self.best_acc,\n 'optimizer': self.optimizer.state_dict(),\n 'state_dict': self.network.state_dict(),\n }, is_best=is_best)\n\n return self.network\n\n def reset_running_statistics(self, net=None, tag_FL=-1):\n from ofa.elastic_nn.utils import set_running_statistics\n if tag_FL == -1:\n if net is None:\n net = self.network\n sub_train_loader = self.run_config.random_sub_train_loader(2000, 100)\n set_running_statistics(net, sub_train_loader)\n elif tag_FL == self.run_config.size_FL:\n if not self.run_config.flag_FL:\n print('Wrong FL client ID')\n import sys\n sys.exit()\n for _ in range(tag_FL):\n self.reset_running_statistics(self.network_FL(_), _)\n self.FedAvg()\n else:\n if tag_FL < 0 or tag_FL >= self.run_config.size_FL or not self.run_config.flag_FL:\n print('Wrong FL client ID')\n import sys\n sys.exit()\n if net is None:\n net = self.network_FL(tag_FL)\n sub_train_loader = self.run_config.random_sub_train_loader(2000, 100, tag_FL=tag_FL)\n set_running_statistics(net, sub_train_loader)\n", "import numpy as np\nfrom scipy.spatial.distance import cdist\n\nfrom pymoo.algorithms.genetic_algorithm import GeneticAlgorithm\n# from pymoo.factory import get_decomposition\nfrom pymoo.factory import get_from_list\nfrom pymoo.operators.crossover.simulated_binary_crossover import SimulatedBinaryCrossover\nfrom pymoo.operators.mutation.polynomial_mutation import PolynomialMutation\nfrom pymoo.operators.sampling.random_sampling import FloatRandomSampling\nfrom pymoo.util.display import MultiObjectiveDisplay\nfrom pymoo.util.misc import set_if_none\n\nimport autograd.numpy as anp\n\nfrom pymoo.model.decomposition import Decomposition\n\n\nclass Tchebicheff_ed(Decomposition):\n\n def _do(self, F, weights, **kwargs):\n # v = anp.abs(F - self.utopian_point) * weights\n v = anp.abs(F - self.ideal_point) / (anp.abs(self.nadir_point - self.ideal_point) + 1e-5) / (weights + 1e-5)\n tchebi = v.max(axis=1)\n return tchebi\n\n\n# ---------------------------------------------------------------------------------------------------------\n# Binary Tournament Selection Function\n# ---------------------------------------------------------------------------------------------------------\nfrom pymoo.operators.selection.tournament_selection import compare\nimport math\nfrom pymoo.util.misc import random_permuations\n\n\ndef tournament_selection(utility, n_select, n_parents=2, pressure=2):\n # number of random individuals needed\n n_random = n_select * n_parents * pressure\n\n # number of permutations needed\n n_perms = math.ceil(n_random / len(utility))\n\n # get random permutations and reshape them\n P = random_permuations(n_perms, len(utility))[:n_random]\n P = np.reshape(P, (n_select * n_parents, pressure))\n\n S = np.full(P.shape[0], np.nan)\n\n for i in range(P.shape[0]):\n\n a, b = P[i, 0], P[i, 1]\n\n S[i] = compare(a, utility[a], b, utility[b],\n method='larger_is_better')\n\n # if rank or domination relation didn't make a decision compare by crowding\n if np.isnan(S[i]):\n S[i] = P[i, np.random.choice(pressure)]\n\n return S[:, None].astype(np.int, copy=False)\n\n\n# =========================================================================================================\n# DECOMPOSITION\n# =========================================================================================================\n\ndef get_decomposition_options():\n from pymoo.decomposition.pbi import PBI\n from pymoo.decomposition.tchebicheff import Tchebicheff\n from pymoo.decomposition.weighted_sum import WeightedSum\n from pymoo.decomposition.asf import ASF\n from pymoo.decomposition.aasf import AASF\n from pymoo.decomposition.perp_dist import PerpendicularDistance\n\n DECOMPOSITION = [\n (\"weighted-sum\", WeightedSum),\n (\"tchebi\", Tchebicheff),\n (\"tchebi_ed\", Tchebicheff_ed),\n (\"pbi\", PBI),\n (\"asf\", ASF),\n (\"aasf\", AASF),\n (\"perp_dist\", PerpendicularDistance)\n ]\n\n return DECOMPOSITION\n\n\ndef get_decomposition(name, *args, d={}, **kwargs):\n return get_from_list(get_decomposition_options(), name, args, {**d, **kwargs})\n\n\n# =========================================================================================================\n# Implementation\n# =========================================================================================================\n\nclass MOEAD(GeneticAlgorithm):\n\n def __init__(self,\n ref_dirs,\n n_neighbors=20,\n decomposition='auto',\n prob_neighbor_mating=0.9,\n display=MultiObjectiveDisplay(),\n init_scheme=0,\n type_select='random',\n n_offsprings=20,\n utility_ini=0.1,\n utility_type='descend',\n **kwargs):\n \"\"\"\n\n Parameters\n ----------\n ref_dirs\n n_neighbors\n decomposition\n prob_neighbor_mating\n display\n kwargs\n \"\"\"\n\n self.n_neighbors = n_neighbors\n self.prob_neighbor_mating = prob_neighbor_mating\n self.decomposition = decomposition\n self.init_scheme = init_scheme\n self.type_select = type_select\n self.n_offspr = n_offsprings\n self.utility_ini = utility_ini\n self.utility_type = utility_type\n\n set_if_none(kwargs, 'pop_size', len(ref_dirs))\n set_if_none(kwargs, 'sampling', FloatRandomSampling())\n set_if_none(kwargs, 'crossover', SimulatedBinaryCrossover(prob=1.0, eta=20))\n set_if_none(kwargs, 'mutation', PolynomialMutation(prob=None, eta=20))\n set_if_none(kwargs, 'survival', None)\n set_if_none(kwargs, 'selection', None)\n\n super().__init__(display=display, **kwargs)\n\n # initialized when problem is known\n if isinstance(self.decomposition, Tchebicheff_ed) or self.decomposition == \"tchebi_ed\":\n self.ref_dirs = ref_dirs[ref_dirs[:, 0].argsort(), :]\n else:\n self.ref_dirs = ref_dirs[ref_dirs[:, 1].argsort(), :]\n\n if self.ref_dirs.shape[0] < self.n_neighbors or self.n_neighbors <= 0:\n print(\"Setting number of neighbours to population size: %s\" % self.ref_dirs.shape[0])\n self.n_neighbors = self.ref_dirs.shape[0]\n\n if self.ref_dirs.shape[0] < self.n_offspr or self.n_offspr <= 0:\n print(\"Setting number of offsprings to population size: %s\" % self.ref_dirs.shape[0])\n self.n_offspr = self.ref_dirs.shape[0]\n\n # neighbours includes the entry by itself intentionally for the survival method\n self.neighbors = np.argsort(cdist(self.ref_dirs, self.ref_dirs), axis=1, kind='quicksort')[:, :self.n_neighbors]\n\n self.n_max_rep = 2\n\n def _initialize(self):\n\n if isinstance(self.decomposition, str):\n\n # set a string\n decomp = self.decomposition\n\n # for one or two objectives use tchebi otherwise pbi\n if decomp == 'auto':\n if self.problem.n_obj <= 2:\n decomp = 'tchebi'\n else:\n decomp = 'pbi'\n\n # set the decomposition object\n self._decomposition = get_decomposition(decomp)\n\n else:\n self._decomposition = self.decomposition\n\n super()._initialize()\n self.ideal_point = np.min(self.pop.get(\"F\"), axis=0)\n self.nadir_point = np.max(self.pop.get(\"F\"), axis=0)\n\n #\n if isinstance(self._decomposition, Tchebicheff_ed):\n inds = self.pop.get(\"F\")[:, 0].argsort()\n else:\n inds = self.pop.get(\"F\")[:, 1].argsort()\n if self.init_scheme == 1:\n self.pop.set(\"X\", self.pop.get(\"X\")[inds])\n self.pop.set(\"F\", self.pop.get(\"F\")[inds])\n elif self.init_scheme == 2:\n f = self.pop.get(\"F\")\n inds_cur = []\n for i in range(len(inds)):\n if isinstance(self._decomposition, Tchebicheff_ed):\n _ = i\n else:\n _ = len(self.pop) - i - 1\n inds_rem = [i for i in inds.tolist() if i not in inds_cur]\n if len(inds_rem) > 1:\n FVs = self._decomposition.do(f[inds_rem, :], weights=self.ref_dirs[_][None, :],\n ideal_point=self.ideal_point, nadir_point=self.nadir_point)\n # print(FVs)\n # print(FVs.argsort())\n # print(inds_rem[FVs.argsort()[0]])\n if isinstance(self._decomposition, Tchebicheff_ed):\n inds_cur.append(inds_rem[FVs.argsort()[0]])\n else:\n inds_cur.insert(0, inds_rem[FVs.argsort()[0]])\n else:\n if isinstance(self._decomposition, Tchebicheff_ed):\n inds_cur.append(inds_rem[0])\n else:\n inds_cur.insert(0, inds_rem[0])\n\n self.pop.set(\"X\", self.pop.get(\"X\")[inds_cur])\n self.pop.set(\"F\", self.pop.get(\"F\")[inds_cur])\n\n if self.utility_type == 'descend':\n v_bg = self.utility_ini\n v_fn = self.utility_ini / 10\n v_gp = (v_fn - v_bg) / (len(self.pop) - 1)\n self.utility = np.full(len(self.pop), self.utility_ini)\n for _ in range(len(self.pop)):\n self.utility[_] = v_bg + _ * v_gp\n elif self.utility_type == 'ascend':\n v_bg = self.utility_ini / 10\n v_fn = self.utility_ini\n v_gp = (v_fn - v_bg) / (len(self.pop) - 1)\n self.utility = np.full(len(self.pop), self.utility_ini)\n for _ in range(len(self.pop)):\n self.utility[_] = v_bg + _ * v_gp\n elif self.utility_type == 'uniform':\n self.utility = np.full(len(self.pop), self.utility_ini)\n\n self.a_util = 0.99\n\n def _next(self):\n repair, crossover, mutation = self.mating.repair, self.mating.crossover, self.mating.mutation\n\n # retrieve the current population\n pop = self.pop\n\n # iterate for each member of the population in random order\n if self.type_select == 'random':\n inds = np.random.permutation(len(pop))[:self.n_offspr]\n else:\n print(self.utility)\n inds = np.random.choice([_ for _ in range(self.pop_size)], self.n_offspr,\n replace=False,\n p=self.utility / (np.sum(self.utility)))\n if isinstance(self._decomposition, Tchebicheff_ed):\n tar_ind = 0\n else:\n tar_ind = self.pop_size - 1\n if tar_ind not in inds:\n inds[np.random.choice(self.n_offspr)] = tar_ind\n for i in inds:\n # all neighbors of this individual and corresponding weights\n if np.random.random() < self.prob_neighbor_mating:\n flag_neighbor = True\n N = self.neighbors[i, :]\n parents = N[np.random.permutation(self.n_neighbors)][:crossover.n_parents]\n else:\n flag_neighbor = False\n N = np.array([int(_) for _ in range(self.pop_size)], dtype=np.int64)\n parents = np.random.permutation(self.pop_size)[:crossover.n_parents]\n\n # do recombination and create an offspring\n off = crossover.do(self.problem, pop, parents[None, :])\n off = mutation.do(self.problem, off)\n off = off[np.random.randint(0, len(off))]\n\n # repair first in case it is necessary\n if repair:\n off = self.repair.do(self.problem, off, algorithm=self)\n\n # evaluate the offspring\n self.evaluator.eval(self.problem, off)\n\n # update the ideal point\n self.ideal_point = np.min(np.vstack([self.ideal_point, off.F]), axis=0)\n\n # calculate the decomposed values for each neighbor\n FV = self._decomposition.do(pop[N].get(\"F\"), weights=self.ref_dirs[N, :],\n ideal_point=self.ideal_point, nadir_point=self.nadir_point)\n off_FV = self._decomposition.do(off.F[None, :], weights=self.ref_dirs[N, :],\n ideal_point=self.ideal_point, nadir_point=self.nadir_point)\n\n # get the absolute index in F where offspring is better than the current F (decomposed space)\n FV_diff = off_FV - FV\n inds_neg = FV_diff < 0\n I = FV_diff[inds_neg].argsort()[:self.n_max_rep]\n # I = np.where(off_FV < FV)[0]\n # print(inds_neg)\n # print(I)\n I = N[inds_neg][I]\n if self.type_select != 'random' and len(I) > 0:\n tmp = (pop[I].get(\"F\")[:, 0] - off.get(\"F\")[0]) / (self.nadir_point[0] - self.ideal_point[0] + 1e-5)\n inds_pos = tmp > 0\n uti = np.sum(tmp[inds_pos])\n tmp_n = np.sum(inds_pos)\n if tmp_n > 0:\n uti /= tmp_n\n self.utility[i] = uti + self.a_util * self.utility[i]\n pop[I] = off\n\n self.nadir_point = np.max(np.vstack([self.nadir_point, off.F]), axis=0)\n\n# parse_doc_string(MOEAD.__init__)\n" ]
[ [ "torch.nn.CrossEntropyLoss", "torch.nn.functional.softmax", "torch.nn.functional.mse_loss", "numpy.mean", "torch.nn.DataParallel" ], [ "numpy.random.random", "numpy.random.choice", "numpy.reshape", "numpy.isnan", "scipy.spatial.distance.cdist", "numpy.full", "numpy.random.permutation", "numpy.sum", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "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": [] } ]
crsqq/OpenNE
[ "0cecb2b5076b878d2f07ed1130682aeab6ce37f1" ]
[ "wrapper.py" ]
[ "from OpenNE.src.libnrl import graph\nfrom OpenNE.src.libnrl import grarep\nfrom OpenNE.src.libnrl import line\nfrom OpenNE.src.libnrl import node2vec\nfrom OpenNE.src.libnrl.gcn import gcnAPI\nfrom itertools import product\nimport networkx as nx\nimport numpy as np\nimport tensorflow as tf\n\ndef nx_to_openne_graph(nxgraph, stringify_nodes=True):\n dg = nx.to_directed(nxgraph).copy()\n if stringify_nodes:\n nx.relabel_nodes(dg, {n:str(n) for n in dg.nodes}, copy=False)\n nx.set_edge_attributes(dg, 1.0, 'weight')\n g = graph.Graph()\n g.G = dg\n g.encode_node()\n return g\n\n\nclass OpenNEEmbeddingBase:\n def __init__(self, thisgraph, parameters):\n self.graph = nx_to_openne_graph(thisgraph)\n self.embeddings = None\n self.parameters = parameters\n def run(self):\n raise NotImplementedError('')\n def update_parameters(self, new_parameters):\n self.parameters = new_parameters\n self.embeddings = None\n def get_embeddings(self):\n if not self.embeddings:\n self.run()\n return self.embeddings\n def get_vectors(self):\n return self.get_embeddings().vectors\n\n @staticmethod\n def valid_parameter_combinations(parameterSpace):\n \"\"\"\n returns all possible combinations, if some are not valid / useful,\n this method needs to be overwritten\n \"\"\"\n all_combinations = product(*parameterSpace.values())\n return [{k:v for k,v in zip(parameterSpace.keys(), combn)} for combn in all_combinations]\n\nclass Node2VecEmbedding(OpenNEEmbeddingBase):\n \"\"\"\n {'dim': 2, 'num_paths': 80, 'p': 1, 'path_length': 10, 'q': 1}\n \"\"\"\n def run(self):\n self.embeddings = node2vec.Node2vec(self.graph, retrainable=True, **self.parameters)\n\n def retrain(self, new_graph, num_paths=80, epochs=5):\n g = nx_to_openne_graph(new_graph)\n self.embeddings.retrain(g, num_paths=num_paths, epochs=epochs)\n\nclass GraRepEmbedding(OpenNEEmbeddingBase):\n def run(self):\n self.embeddings = grarep.GraRep(self.graph, **self.parameters)\n\n @staticmethod\n def valid_parameter_combinations(parameterSpace):\n \"\"\"\n returns all possible combinations, if some are not valid / useful,\n this method needs to be overwritten\n \"\"\"\n all_combinations = product(*parameterSpace.values())\n all_combinations = [{k:v for k,v in zip(parameterSpace.keys(), combn)} for combn in all_combinations]\n return [x for x in all_combinations if x[\"dim\"] % x[\"Kstep\"] == 0]\n\nclass LINEEmbedding(OpenNEEmbeddingBase):\n def run(self):\n tf.reset_default_graph()\n self.embeddings = line.LINE(self.graph, **self.parameters)\n\n\n\nfrom scipy.sparse.linalg.eigen.arpack import eigsh as largest_eigsh\n\nclass SpectralClusteringEmbedding(OpenNEEmbeddingBase):\n def __init__(self, thisgraph, parameters):\n self.graph = thisgraph\n self.embeddings = None\n self.parameters = parameters\n\n nx.relabel_nodes(self.graph, {n:str(n) for n in self.graph.nodes}, copy=False)\n def run(self):\n L = nx.normalized_laplacian_matrix(self.graph)\n evalues, evectors = a,b = largest_eigsh(L, k=self.parameters['dim'])\n self.embeddings = {str(n):v for n,v in zip(self.graph.nodes, evectors)}\n def get_vectors(self):\n return self.get_embeddings()\n\n\ndef _RandNE(graph, dim, q, beta):\n d = dim\n A = nx.to_scipy_sparse_matrix(graph)\n\n R = np.random.normal(loc=0, scale=1/d, size=(A.shape[0], d))\n\n U0, _ = np.linalg.qr(R)\n\n Ulist = [U0]\n for i in range(q):\n Ulist.append(A.dot(Ulist[-1]))\n\n Ulist = np.array(Ulist)\n\n betas = (beta**np.arange(0, q+1))\n\n U = np.array([scalar*m for scalar,m in zip(betas, Ulist)]).sum(axis=0)\n return U\n\nclass RandNEEmbedding(OpenNEEmbeddingBase):\n def __init__(self, thisgraph, parameters):\n self.graph = thisgraph\n self.embeddings = None\n self.parameters = parameters\n def run(self):\n U = _RandNE(self.graph, **self.parameters)\n self.embeddings = {str(n):v for n,v in zip(self.graph.nodes, U)}\n def get_vectors(self):\n return self.get_embeddings()\n" ]
[ [ "numpy.arange", "scipy.sparse.linalg.eigen.arpack.eigsh", "numpy.random.normal", "tensorflow.reset_default_graph", "numpy.linalg.qr", "numpy.array" ] ]
[ { "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": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
thibnoel/solopython
[ "0977c6de8bcee2b8ecabaa46f6953e7a05334af1" ]
[ "minimal_controler.py" ]
[ "# coding: utf8\nfrom coll_avoidance_modules.solo_coll_wrapper_c import *\nfrom coll_avoidance_modules.collisions_controller import *\n\nfrom PA_utils_mpc import PyBulletSimulator\nimport numpy as np\nimport argparse\n# from solo12 import Solo12\n# from pynput import keyboard\n\nfrom PA_logger import Logger\n# from utils.qualisysClient import QualisysClient\n\nimport os\nimport sys\nsys.path.insert(0, './mpctsid')\n\nDT = 0.002\n\nkey_pressed = False\n\n\ndef on_press(key):\n \"\"\"Wait for a specific key press on the keyboard\n\n Args:\n key (keyboard.Key): the key we want to wait for\n \"\"\"\n global key_pressed\n try:\n if key == keyboard.Key.enter:\n key_pressed = True\n # Stop listener\n return False\n except AttributeError:\n print('Unknown key {0} pressed'.format(key))\n\n\ndef put_on_the_floor(device, q_init):\n \"\"\"Make the robot go to the default initial position and wait for the user\n to press the Enter key to start the main control loop\n\n Args:\n device (robot wrapper): a wrapper to communicate with the robot\n q_init (array): the default position of the robot\n \"\"\"\n global key_pressed\n key_pressed = False\n Kp_pos = 3.\n Kd_pos = 0.01\n imax = 3.0\n pos = np.zeros(device.nb_motors)\n for motor in range(device.nb_motors):\n pos[motor] = q_init[device.motorToUrdf[motor]] * \\\n device.gearRatioSigned[motor]\n listener = keyboard.Listener(on_press=on_press)\n listener.start()\n print(\"Put the robot on the floor and press Enter\")\n while not key_pressed:\n device.UpdateMeasurment()\n for motor in range(device.nb_motors):\n ref = Kp_pos*(pos[motor] - device.hardware.GetMotor(motor).GetPosition() -\n Kd_pos*device.hardware.GetMotor(motor).GetVelocity())\n ref = min(imax, max(-imax, ref))\n device.hardware.GetMotor(motor).SetCurrentReference(ref)\n device.SendCommand(WaitEndOfCycle=True)\n\n print(\"Start the motion.\")\n\n\ndef mcapi_playback(name_interface, clib_path):\n \"\"\"Main function that calibrates the robot, get it into a default waiting position then launch\n the main control loop once the user has pressed the Enter key\n\n Args:\n name_interface (string): name of the interface that is used to communicate with the robot\n \"\"\"\n\n #########################################\n # PARAMETERS OF THE MPC-TSID CONTROLLER #\n #########################################\n \n envID = 0 # Identifier of the environment to choose in which one the simulation will happen\n velID = 0 # Identifier of the reference velocity profile to choose which one will be sent to the robot\n\n dt_tsid = 0.0020 # Time step of TSID\n dt_mpc = 0.02 # Time step of the MPC\n # dt is dt_tsid, defined in the TSID controller script\n k_mpc = int(dt_mpc / dt_tsid)\n t = 0.0 # Time\n n_periods = 1 # Number of periods in the prediction horizon\n T_gait = 0.64 # Duration of one gait period\n N_SIMULATION = 20000 # number of simulated TSID time steps\n\t\n # If True the ground is flat, otherwise it has bumps\n use_flat_plane = True\n\n # Enable or disable PyBullet GUI\n enable_pyb_GUI = True\n\t\n # Default position after calibration\n #q_init = np.array([0.0, 0.8, -1.6, 0, 0.8, -1.6,\n # 0, -0.8, 1.6, 0, -0.8, 1.6])\n\t\n q_init = [0,0,0,0,0,0,0,0]\n\t#############################################\n # PARAMETERS OF THE COLL. AVOID. CONTROLLER #\n #############################################\n\t### Set collision avoidance parameters\n collision_threshold = 0.1\n collision_kp = 10.\n collision_kv = 0.01\n k_friction = 0.1\n\t# Load the specified compiled C library\n cCollFun = CDLL(clib_path)\n\n emergency_dist_thresh = collision_threshold/5\n emergency_tau_thresh = 3\n\n emergencyFlag = False\n\n ####\n\n # Create device object\n # device = Solo12(name_interface, dt=DT)\n device = PyBulletSimulator()\n\n # qc = QualisysClient(ip=\"140.93.16.160\", body_id=0) # QualisysClient\n # logger = Logger(device, qualisys=qc) # Logger object\n nb_motors = device.nb_motors\n\n # Calibrate encoders\n #device.Init(calibrateEncoders=True, q_init=q_init)\n device.Init(calibrateEncoders=True, q_init=q_init, envID=envID,\n use_flat_plane=use_flat_plane, enable_pyb_GUI=enable_pyb_GUI, dt=dt_tsid)\n\n # Wait for Enter input before starting the control loop\n # put_on_the_floor(device, q_init)\n\n # CONTROL LOOP ***************************************************\n t = 0.0\n t_max = (N_SIMULATION-2) * dt_tsid\n while ((not device.hardware.IsTimeout()) and (t < t_max)):\n\n device.UpdateMeasurment() # Retrieve data from IMU and Motion capture\n\n # Desired torques\n tau_q = np.zeros(12)\n\n\t\t#tau_q = np.zeros(len(nb_motors))\n\t\t#Check if the controller switched to emergency mode\n if(emergencyFlag):\n # Compute emergency behavior\n # Ex :\n tau_q = computeEmergencyTorque(device.v_mes, collision_kv)\n else:\n\t\t\t# Compute collisions distances and jacobians from the C lib. \n c_results = getLegsCollisionsResults(device.q_mes, cCollFun, nb_motors, 20)\n c_dist_legs = getLegsDistances(c_results, nb_motors, 20)\n c_Jlegs = getLegsJacobians(c_results, nb_motors, 20)\n\t\t\t# Compute collision avoidance torque\n tau_q = computeRepulsiveTorque(device.q_mes, device.v_mes, c_dist_legs, c_Jlegs, dist_thresh=collision_threshold, kp=collision_kp, kv=collision_kv)\n \n\t\t# Set a virtual friction torque to avoid divergence\n tau_q += -k_friction*device.v_mes\n # Set desired torques for the actuators\n device.SetDesiredJointTorque(tau_q)\n\n # Call logger\n # logger.sample(device, qualisys=qc)\n\n # Send command to the robot\n device.SendCommand(WaitEndOfCycle=True)\n if ((device.cpt % 1000) == 0):\n device.Print()\n\n t += DT\n\n # ****************************************************************\n\n # Whatever happened we send 0 torques to the motors.\n device.SetDesiredJointTorque([0]*nb_motors)\n device.SendCommand(WaitEndOfCycle=True)\n\n if device.hardware.IsTimeout():\n print(\"Masterboard timeout detected.\")\n print(\"Either the masterboard has been shut down or there has been a connection issue with the cable/wifi.\")\n # Shut down the interface between the computer and the master board\n device.hardware.Stop()\n\n # Save the logs of the Logger object\n # logger.saveAll()\n\n\ndef main():\n \"\"\"Main function\n \"\"\"\n\n parser = argparse.ArgumentParser(\n description='Playback trajectory to show the extent of solo12 workspace.')\n parser.add_argument('-i',\n '--interface',\n required=True,\n help='Name of the interface (use ifconfig in a terminal), for instance \"enp1s0\"')\n\n parser.add_argument('-C',\n '--clib',\n required=True,\n help='Path to the compiled C-generated library used for distance and jacobian evaluations, for instance \"libcoll_legs8.so\"')\n\n #example_script(parser.parse_args().interface, parser.parse_args().clib)\n\n mcapi_playback(parser.parse_args().interface, parser.parse_args().clib)\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ratt-ru/dask-ms
[ "becd3572f86a0ad78b55540f25fce6e129976a29" ]
[ "daskms/tests/test_ordering.py" ]
[ "# -*- coding: utf-8 -*-\n\nimport dask\nimport dask.array as da\nfrom numpy.testing import assert_array_equal\nimport pyrap.tables as pt\nimport pytest\n\nfrom daskms.table_proxy import TableProxy\nfrom daskms.ordering import (ordering_taql,\n row_ordering,\n group_ordering_taql,\n group_row_ordering)\nfrom daskms.utils import group_cols_str, index_cols_str, assert_liveness\n\n\ndef table_proxy(ms):\n return TableProxy(pt.table, ms, ack=False,\n lockoptions='user', readonly=True)\n\n\[email protected](\"group_cols\", [\n [\"FIELD_ID\", \"SCAN_NUMBER\"]],\n ids=group_cols_str)\[email protected](\"index_cols\", [\n [\"TIME\", \"ANTENNA1\", \"ANTENNA2\"]],\n ids=index_cols_str)\ndef test_ordering_query_taql_where_strings(ms, group_cols, index_cols):\n taql = group_ordering_taql(table_proxy(ms), group_cols, index_cols,\n taql_where=\"ANTENNA1 != ANTENNA2\")\n assert taql._args[0].replace(\"\\t\", \" \"*4) == (\n \"SELECT\\n\"\n \" FIELD_ID,\\n\"\n \" SCAN_NUMBER,\\n\"\n \" GAGGR(TIME) as GROUP_TIME,\\n\"\n \" GAGGR(ANTENNA1) as GROUP_ANTENNA1,\\n\"\n \" GAGGR(ANTENNA2) as GROUP_ANTENNA2,\\n\"\n \" GROWID() AS __tablerow__,\\n\"\n \" GCOUNT() as __tablerows__,\\n\"\n \" GROWID()[0] as __firstrow__\\n\"\n \"FROM\\n\"\n \" $1\\n\"\n \"WHERE\\n\"\n \" ANTENNA1 != ANTENNA2\\n\"\n \"GROUPBY\\n\"\n \" FIELD_ID,\\n\"\n \" SCAN_NUMBER\")\n\n taql = group_ordering_taql(table_proxy(ms), group_cols, index_cols)\n assert taql._args[0].replace(\"\\t\", \" \"*4) == (\n \"SELECT\\n\"\n \" FIELD_ID,\\n\"\n \" SCAN_NUMBER,\\n\"\n \" GAGGR(TIME) as GROUP_TIME,\\n\"\n \" GAGGR(ANTENNA1) as GROUP_ANTENNA1,\\n\"\n \" GAGGR(ANTENNA2) as GROUP_ANTENNA2,\\n\"\n \" GROWID() AS __tablerow__,\\n\"\n \" GCOUNT() as __tablerows__,\\n\"\n \" GROWID()[0] as __firstrow__\\n\"\n \"FROM\\n\"\n \" $1\\n\"\n \"GROUPBY\\n\"\n \" FIELD_ID,\\n\"\n \" SCAN_NUMBER\")\n\n taql = group_ordering_taql(table_proxy(ms), group_cols, [])\n assert taql._args[0].replace(\"\\t\", \" \"*4) == (\n \"SELECT\\n\"\n \" FIELD_ID,\\n\"\n \" SCAN_NUMBER,\\n\"\n \" GROWID() AS __tablerow__,\\n\"\n \" GCOUNT() as __tablerows__,\\n\"\n \" GROWID()[0] as __firstrow__\\n\"\n \"FROM\\n\"\n \" $1\\n\"\n \"GROUPBY\\n\"\n \" FIELD_ID,\\n\"\n \" SCAN_NUMBER\")\n\n taql = ordering_taql(table_proxy(ms), index_cols,\n taql_where=\"ANTENNA1 != ANTENNA2\")\n assert taql._args[0].replace(\"\\t\", \" \"*4) == (\n \"SELECT\\n\"\n \" ROWID() as __tablerow__\\n\"\n \"FROM\\n\"\n \" $1\\n\"\n \"WHERE\\n\"\n \" ANTENNA1 != ANTENNA2\\n\"\n \"ORDERBY\\n\"\n \" TIME,\\n\"\n \" ANTENNA1,\\n\"\n \" ANTENNA2\")\n\n taql = ordering_taql(table_proxy(ms), index_cols)\n assert taql._args[0].replace(\"\\t\", \" \"*4) == (\n \"SELECT\\n\"\n \" ROWID() as __tablerow__\\n\"\n \"FROM\\n\"\n \" $1\\n\"\n \"ORDERBY\\n\"\n \" TIME,\\n\"\n \" ANTENNA1,\\n\"\n \" ANTENNA2\")\n\n taql = ordering_taql(table_proxy(ms), [])\n assert taql._args[0].replace(\"\\t\", \" \"*4) == (\n \"SELECT\\n\"\n \" ROWID() as __tablerow__\\n\"\n \"FROM\\n\"\n \" $1\\n\")\n\n\[email protected](\"group_cols\", [\n [\"FIELD_ID\", \"SCAN_NUMBER\"]],\n ids=group_cols_str)\[email protected](\"index_cols\", [\n [\"TIME\", \"ANTENNA1\", \"ANTENNA2\"]],\n ids=index_cols_str)\ndef test_ordering_multiple_groups(ms, group_cols, index_cols):\n group_taql = group_ordering_taql(table_proxy(ms), group_cols, index_cols)\n assert_liveness(2, 1)\n orders = group_row_ordering(group_taql, group_cols,\n index_cols, [{'row': 2}])\n assert_liveness(2, 1)\n first_rows = group_taql.getcol(\"__firstrow__\").result()\n assert_liveness(2, 1)\n\n assert len(first_rows) == len(orders) == 6\n\n assert_array_equal(first_rows, [0, 1, 3, 4, 7, 8])\n\n rowid_arrays = tuple(o[0] for o in orders)\n rowids = dask.compute(rowid_arrays)[0]\n\n assert_array_equal(rowids[0], [2, 0])\n assert_array_equal(rowids[1], [1])\n assert_array_equal(rowids[2], [5, 3])\n assert_array_equal(rowids[3], [6, 4])\n assert_array_equal(rowids[4], [9, 7])\n assert_array_equal(rowids[5], [8])\n\n del first_rows, orders, rowid_arrays, group_taql\n assert_liveness(0, 0)\n\n\[email protected](\"index_cols\", [\n [\"TIME\", \"ANTENNA1\", \"ANTENNA2\"]],\n ids=index_cols_str)\[email protected](\"chunks\", [\n {'row': 2},\n {'row': (2, 3, 4, 1)},\n {'row': (5, 3, 2)}],\n ids=lambda c: f'chunks={c}')\ndef test_row_ordering_no_group(ms, index_cols, chunks):\n order_taql = ordering_taql(table_proxy(ms), index_cols)\n assert_liveness(2, 1)\n orders = row_ordering(order_taql, index_cols, chunks)\n assert_liveness(2, 1)\n\n # Normalise chunks to match that of the output array\n expected_chunks = da.core.normalize_chunks(chunks['row'], (10,))\n\n assert orders[0].chunks == expected_chunks\n\n rowids = dask.compute(orders[0])[0]\n assert_array_equal(rowids, [9, 8, 7, 6, 5, 4, 3, 2, 1, 0])\n\n del orders, order_taql\n assert_liveness(0, 0)\n\n\n# Grouping on DATA_DESC_ID gives us two groups\n# one with 7 rows and the other with 3\[email protected](\"group_cols\", [\n [\"DATA_DESC_ID\"]],\n ids=group_cols_str)\[email protected](\"index_cols\", [\n [\"TIME\", \"ANTENNA1\", \"ANTENNA2\"]],\n ids=index_cols_str)\[email protected](\"chunks\", [\n [{'row': 2}, {'row': 2}],\n [{'row': (3, 4)}, {'row': 3}],\n [{'row': (2, 3, 2)}, {'row': (2, 1)}],\n [{'row': 2}]],\n ids=lambda c: f'chunks={c}')\ndef test_row_ordering_multiple_groups(ms, group_cols,\n index_cols, chunks):\n group_taql = group_ordering_taql(table_proxy(ms), group_cols, index_cols)\n assert_liveness(2, 1)\n orders = group_row_ordering(group_taql, group_cols, index_cols, chunks)\n assert_liveness(2, 1)\n first_rows = group_taql.getcol(\"__firstrow__\").result()\n assert_liveness(2, 1)\n\n # We get two groups out\n assert len(orders) == len(first_rows) == 2\n assert_array_equal(first_rows, [0, 7])\n\n rowid_arrays = tuple(o[0] for o in orders)\n rowids = dask.compute(rowid_arrays)[0]\n\n # Check the two resulting groups\n\n # Normalise chunks to match that of the output array\n row_chunks = chunks[0]['row']\n expected_chunks = da.core.normalize_chunks(row_chunks, (7,))\n assert_array_equal(rowids[0], [6, 5, 4, 3, 2, 1, 0])\n assert rowid_arrays[0].chunks == expected_chunks\n\n # If chunks only supplied for the first group, re-use it's chunking\n row_chunks = chunks[0]['row'] if len(chunks) == 1 else chunks[1]['row']\n expected_chunks = da.core.normalize_chunks(row_chunks, (3,))\n assert_array_equal(rowids[1], [9, 8, 7])\n assert rowid_arrays[1].chunks == expected_chunks\n\n del first_rows, orders, rowid_arrays, group_taql\n assert_liveness(0, 0)\n" ]
[ [ "numpy.testing.assert_array_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
TB5zhh/ViewpointBottleneck
[ "db0fe4b61ae42eceff21296844200d636e6e5e83" ]
[ "lib/distributed_utils.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport os\nimport pickle\nimport socket\nimport struct\nimport subprocess\nimport warnings\n\nimport torch\nimport torch.distributed as dist\n\n\n\ndef is_master(args):\n return args.distributed_rank == 0\n\n\ndef infer_init_method(args):\n if args.distributed_init_method is not None:\n return\n\n # support torch.distributed.launch\n if all(key in os.environ for key in [\n 'MASTER_ADDR', 'MASTER_PORT', 'WORLD_SIZE', 'RANK'\n ]):\n args.distributed_init_method = 'env://'\n args.distributed_world_size = int(os.environ['WORLD_SIZE'])\n args.distributed_rank = int(os.environ['RANK'])\n\n # we can determine the init method automatically for Slurm\n elif args.distributed_port > 0:\n node_list = os.environ.get('SLURM_STEP_NODELIST')\n if node_list is None:\n node_list = os.environ.get('SLURM_JOB_NODELIST')\n if node_list is not None:\n try:\n hostnames = subprocess.check_output(['scontrol', 'show', 'hostnames', node_list])\n args.distributed_init_method = 'tcp://{host}:{port}'.format(\n host=hostnames.split()[0].decode('utf-8'),\n port=args.distributed_port,\n )\n nnodes = int(os.environ.get('SLURM_NNODES'))\n ntasks_per_node = os.environ.get('SLURM_NTASKS_PER_NODE')\n if ntasks_per_node is not None:\n ntasks_per_node = int(ntasks_per_node)\n else:\n ntasks = int(os.environ.get('SLURM_NTASKS'))\n nnodes = int(os.environ.get('SLURM_NNODES'))\n assert ntasks % nnodes == 0\n ntasks_per_node = int(ntasks / nnodes)\n if ntasks_per_node == 1:\n assert args.distributed_world_size % nnodes == 0\n gpus_per_node = args.distributed_world_size // nnodes\n node_id = int(os.environ.get('SLURM_NODEID'))\n args.distributed_rank = node_id * gpus_per_node\n else:\n assert ntasks_per_node == args.distributed_world_size // nnodes\n args.distributed_no_spawn = True\n args.distributed_rank = int(os.environ.get('SLURM_PROCID'))\n args.device_id = int(os.environ.get('SLURM_LOCALID'))\n except subprocess.CalledProcessError as e: # scontrol failed\n raise e\n except FileNotFoundError: # Slurm is not installed\n pass\n\n\ndef distributed_init(args):\n if args.distributed_world_size == 1:\n raise ValueError('Cannot initialize distributed with distributed_world_size=1')\n\n if torch.distributed.is_initialized():\n warnings.warn('Distributed is already initialized, cannot initialize twice!')\n else:\n print('| distributed init (rank {}): {}'.format(\n args.distributed_rank, args.distributed_init_method), flush=True)\n dist.init_process_group(\n backend=args.distributed_backend,\n init_method=args.distributed_init_method,\n world_size=args.distributed_world_size,\n rank=args.distributed_rank,\n )\n print('| initialized host {} as rank {}'.format(\n socket.gethostname(), args.distributed_rank), flush=True)\n\n # perform a dummy all-reduce to initialize the NCCL communicator\n if torch.cuda.is_available():\n dist.all_reduce(torch.zeros(1).cuda())\n else:\n dist.all_reduce(torch.zeros(1))\n\n suppress_output(is_master(args))\n\n args.distributed_rank = torch.distributed.get_rank()\n return args.distributed_rank\n\n\ndef suppress_output(is_master):\n \"\"\"Suppress printing on the current device. Force printing with `force=True`.\"\"\"\n import builtins as __builtin__\n builtin_print = __builtin__.print\n\n def print(*args, **kwargs):\n force = kwargs.pop('force', False)\n if is_master or force:\n builtin_print(*args, **kwargs)\n\n __builtin__.print = print\n\n\ndef get_rank():\n return dist.get_rank()\n\n\ndef get_world_size():\n try:\n return dist.get_world_size()\n except AssertionError:\n return 1\n\ndef get_default_group():\n return dist.group.WORLD\n\n\ndef all_reduce(tensor, op='sum', group=None):\n if group is None:\n group = get_default_group()\n output = dist.all_reduce(tensor, group=group)\n if op == 'mean':\n return output / get_world_size()\n return output\n\ndef all_gather_list(data, group=None, max_size=16384):\n \"\"\"Gathers arbitrary data from all nodes into a list.\n\n Similar to :func:`~torch.distributed.all_gather` but for arbitrary Python\n data. Note that *data* must be picklable.\n\n Args:\n data (Any): data from the local worker to be gathered on other workers\n group (optional): group of the collective\n max_size (int, optional): maximum size of the data to be gathered\n across workers\n \"\"\"\n rank = get_rank()\n world_size = get_world_size()\n\n buffer_size = max_size * world_size\n if not hasattr(all_gather_list, '_buffer') or \\\n all_gather_list._buffer.numel() < buffer_size:\n all_gather_list._buffer = torch.cuda.ByteTensor(buffer_size)\n all_gather_list._cpu_buffer = torch.ByteTensor(max_size).pin_memory()\n buffer = all_gather_list._buffer\n buffer.zero_()\n cpu_buffer = all_gather_list._cpu_buffer\n\n enc = pickle.dumps(data)\n enc_size = len(enc)\n header_size = 4 # size of header that contains the length of the encoded data\n size = header_size + enc_size\n if size > max_size:\n raise ValueError('encoded data size ({}) exceeds max_size ({})'.format(size, max_size))\n\n header = struct.pack(\">I\", enc_size)\n cpu_buffer[:size] = torch.ByteTensor(list(header + enc))\n start = rank * max_size\n buffer[start:start + size].copy_(cpu_buffer[:size])\n\n all_reduce(buffer, group=group)\n\n try:\n result = []\n for i in range(world_size):\n out_buffer = buffer[i * max_size:(i + 1) * max_size]\n enc_size, = struct.unpack(\">I\", bytes(out_buffer[:header_size].tolist()))\n if enc_size > 0:\n result.append(pickle.loads(bytes(out_buffer[header_size:header_size + enc_size].tolist())))\n return result\n except pickle.UnpicklingError:\n raise Exception(\n 'Unable to unpickle data from other workers. all_gather_list requires all '\n 'workers to enter the function together, so this error usually indicates '\n 'that the workers have fallen out of sync somehow. Workers can fall out of '\n 'sync if one of them runs out of memory, or if there are other conditions '\n 'in your training script that can cause one worker to finish an epoch '\n 'while other workers are still iterating over their portions of the data.'\n )\n" ]
[ [ "torch.ByteTensor", "torch.distributed.init_process_group", "torch.zeros", "torch.cuda.ByteTensor", "torch.distributed.is_initialized", "torch.cuda.is_available", "torch.distributed.get_rank", "torch.distributed.get_world_size", "torch.distributed.all_reduce" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ntgiwsvp/qiskit-terra
[ "206b8bcc930817d88f8244f7b984880aecde959d" ]
[ "qiskit/circuit/gate.py" ]
[ "# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"Unitary gate.\"\"\"\n\nfrom warnings import warn\nfrom typing import List, Optional, Union, Tuple\nimport numpy as np\nfrom scipy.linalg import schur\n\nfrom qiskit.circuit.parameter import ParameterExpression\nfrom qiskit.circuit.exceptions import CircuitError\nfrom .instruction import Instruction\n\n\nclass Gate(Instruction):\n \"\"\"Unitary gate.\"\"\"\n\n def __init__(self, name: str, num_qubits: int, params: List,\n label: Optional[str] = None) -> None:\n \"\"\"Create a new gate.\n\n Args:\n name: The Qobj name of the gate.\n num_qubits: The number of qubits the gate acts on.\n params: A list of parameters.\n label: An optional label for the gate.\n \"\"\"\n self._label = label\n self.definition = None\n super().__init__(name, num_qubits, 0, params)\n\n # Set higher priority than Numpy array and matrix classes\n __array_priority__ = 20\n\n def to_matrix(self) -> np.ndarray:\n \"\"\"Return a Numpy.array for the gate unitary matrix.\n\n Returns:\n np.ndarray: if the Gate subclass has a matrix defintion.\n\n Raises:\n CircuitError: If a Gate subclass does not implement this method an\n exception will be raised when this base class method is called.\n \"\"\"\n if hasattr(self, '__array__'):\n # pylint: disable=no-member\n return self.__array__(dtype=complex)\n raise CircuitError(\"to_matrix not defined for this {}\".format(type(self)))\n\n def power(self, exponent: float):\n \"\"\"Creates a unitary gate as `gate^exponent`.\n\n Args:\n exponent (float): Gate^exponent\n\n Returns:\n qiskit.extensions.UnitaryGate: To which `to_matrix` is self.to_matrix^exponent.\n\n Raises:\n CircuitError: If Gate is not unitary\n \"\"\"\n from qiskit.quantum_info.operators import Operator # pylint: disable=cyclic-import\n from qiskit.extensions.unitary import UnitaryGate # pylint: disable=cyclic-import\n # Should be diagonalized because it's a unitary.\n decomposition, unitary = schur(Operator(self).data, output='complex')\n # Raise the diagonal entries to the specified power\n decomposition_power = list()\n\n decomposition_diagonal = decomposition.diagonal()\n # assert off-diagonal are 0\n if not np.allclose(np.diag(decomposition_diagonal), decomposition):\n raise CircuitError('The matrix is not diagonal')\n\n for element in decomposition_diagonal:\n decomposition_power.append(pow(element, exponent))\n # Then reconstruct the resulting gate.\n unitary_power = unitary @ np.diag(decomposition_power) @ unitary.conj().T\n return UnitaryGate(unitary_power, label='%s^%s' % (self.name, exponent))\n\n def _return_repeat(self, exponent: float) -> 'Gate':\n return Gate(name=\"%s*%s\" % (self.name, exponent), num_qubits=self.num_qubits,\n params=self.params)\n\n def assemble(self) -> 'Instruction':\n \"\"\"Assemble a QasmQobjInstruction\"\"\"\n instruction = super().assemble()\n if self.label:\n instruction.label = self.label\n return instruction\n\n @property\n def label(self) -> str:\n \"\"\"Return gate label\"\"\"\n return self._label\n\n @label.setter\n def label(self, name: str):\n \"\"\"Set gate label to name\n\n Args:\n name (str or None): label to assign unitary\n\n Raises:\n TypeError: name is not string or None.\n \"\"\"\n if isinstance(name, (str, type(None))):\n self._label = name\n else:\n raise TypeError('label expects a string or None')\n\n def control(self, num_ctrl_qubits: Optional[int] = 1, label: Optional[str] = None,\n ctrl_state: Optional[Union[int, str]] = None):\n \"\"\"Return controlled version of gate. See :class:`.ControlledGate` for usage.\n\n Args:\n num_ctrl_qubits: number of controls to add to gate (default=1)\n label: optional gate label\n ctrl_state: The control state in decimal or as a bitstring\n (e.g. '111'). If None, use 2**num_ctrl_qubits-1.\n\n Returns:\n qiskit.circuit.ControlledGate: Controlled version of gate. This default algorithm\n uses num_ctrl_qubits-1 ancillae qubits so returns a gate of size\n num_qubits + 2*num_ctrl_qubits - 1.\n\n Raises:\n QiskitError: unrecognized mode or invalid ctrl_state\n \"\"\"\n # pylint: disable=cyclic-import\n from .add_control import add_control\n return add_control(self, num_ctrl_qubits, label, ctrl_state)\n\n @staticmethod\n def _broadcast_single_argument(qarg: List) -> List:\n \"\"\"Expands a single argument.\n\n For example: [q[0], q[1]] -> [q[0]], [q[1]]\n \"\"\"\n # [q[0], q[1]] -> [q[0]]\n # -> [q[1]]\n for arg0 in qarg:\n yield [arg0], []\n\n @staticmethod\n def _broadcast_2_arguments(qarg0: List, qarg1: List) -> List:\n if len(qarg0) == len(qarg1):\n # [[q[0], q[1]], [r[0], r[1]]] -> [q[0], r[0]]\n # -> [q[1], r[1]]\n for arg0, arg1 in zip(qarg0, qarg1):\n yield [arg0, arg1], []\n elif len(qarg0) == 1:\n # [[q[0]], [r[0], r[1]]] -> [q[0], r[0]]\n # -> [q[0], r[1]]\n for arg1 in qarg1:\n yield [qarg0[0], arg1], []\n elif len(qarg1) == 1:\n # [[q[0], q[1]], [r[0]]] -> [q[0], r[0]]\n # -> [q[1], r[0]]\n for arg0 in qarg0:\n yield [arg0, qarg1[0]], []\n else:\n raise CircuitError('Not sure how to combine these two-qubit arguments:\\n %s\\n %s' %\n (qarg0, qarg1))\n\n @staticmethod\n def _broadcast_3_or_more_args(qargs: List) -> List:\n if all(len(qarg) == len(qargs[0]) for qarg in qargs):\n for arg in zip(*qargs):\n yield list(arg), []\n else:\n raise CircuitError(\n 'Not sure how to combine these qubit arguments:\\n %s\\n' % qargs)\n\n def broadcast_arguments(self, qargs: List, cargs: List) -> Tuple[List, List]:\n \"\"\"Validation and handling of the arguments and its relationship.\n\n For example, ``cx([q[0],q[1]], q[2])`` means ``cx(q[0], q[2]); cx(q[1], q[2])``. This\n method yields the arguments in the right grouping. In the given example::\n\n in: [[q[0],q[1]], q[2]],[]\n outs: [q[0], q[2]], []\n [q[1], q[2]], []\n\n The general broadcasting rules are:\n\n * If len(qargs) == 1::\n\n [q[0], q[1]] -> [q[0]],[q[1]]\n\n * If len(qargs) == 2::\n\n [[q[0], q[1]], [r[0], r[1]]] -> [q[0], r[0]], [q[1], r[1]]\n [[q[0]], [r[0], r[1]]] -> [q[0], r[0]], [q[0], r[1]]\n [[q[0], q[1]], [r[0]]] -> [q[0], r[0]], [q[1], r[0]]\n\n * If len(qargs) >= 3::\n\n [q[0], q[1]], [r[0], r[1]], ...] -> [q[0], r[0], ...], [q[1], r[1], ...]\n\n Args:\n qargs: List of quantum bit arguments.\n cargs: List of classical bit arguments.\n\n Returns:\n A tuple with single arguments.\n\n Raises:\n CircuitError: If the input is not valid. For example, the number of\n arguments does not match the gate expectation.\n \"\"\"\n if len(qargs) != self.num_qubits or cargs:\n raise CircuitError(\n 'The amount of qubit/clbit arguments does not match the gate expectation.')\n\n if any([not qarg for qarg in qargs]):\n raise CircuitError('One or more of the arguments are empty')\n\n if len(qargs) == 1:\n return Gate._broadcast_single_argument(qargs[0])\n elif len(qargs) == 2:\n return Gate._broadcast_2_arguments(qargs[0], qargs[1])\n elif len(qargs) >= 3:\n return Gate._broadcast_3_or_more_args(qargs)\n else:\n raise CircuitError('This gate cannot handle %i arguments' % len(qargs))\n\n def validate_parameter(self, parameter):\n \"\"\"Gate parameters should be int, float, or ParameterExpression\"\"\"\n if isinstance(parameter, ParameterExpression):\n if len(parameter.parameters) > 0:\n return parameter # expression has free parameters, we cannot validate it\n if not parameter._symbol_expr.is_real:\n raise CircuitError(\"Bound parameter expression is complex in gate {}\".format(\n self.name))\n return parameter # per default assume parameters must be real when bound\n if isinstance(parameter, (int, float)):\n return parameter\n elif isinstance(parameter, (np.integer, np.floating)):\n return parameter.item()\n elif isinstance(parameter, np.ndarray):\n warn(\"Gate param type %s is being deprecated as of 0.16.0, and will be removed \"\n \"no earlier than 3 months after that release date. \"\n \"Considering creating your own Gate subclass with the method validate_parameter \"\n \" to allow this param type.\" % type(parameter), DeprecationWarning, 3)\n return parameter\n else:\n raise CircuitError(\"Invalid param type {0} for gate {1}.\".format(type(parameter),\n self.name))\n" ]
[ [ "numpy.diag" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dynasty-com/NeMo
[ "1ac828df423fbcec1b34c650b3a20266bb133dde", "1ac828df423fbcec1b34c650b3a20266bb133dde", "1ac828df423fbcec1b34c650b3a20266bb133dde" ]
[ "nemo/collections/asr/models/label_models.py", "nemo/collections/asr/data/audio_to_text.py", "nemo/collections/nlp/models/language_modeling/bert_lm_model.py" ]
[ "# 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\nimport copy\nimport json\nimport os\nimport pickle as pkl\nfrom typing import Dict, List, Optional, Union\n\nimport onnx\nimport torch\nfrom omegaconf import DictConfig\nfrom omegaconf.omegaconf import open_dict\nfrom pytorch_lightning import Trainer\n\nfrom nemo.collections.asr.data.audio_to_label import AudioToSpeechLabelDataSet\nfrom nemo.collections.asr.losses.angularloss import AngularSoftmaxLoss\nfrom nemo.collections.asr.parts.features import WaveformFeaturizer\nfrom nemo.collections.asr.parts.perturb import process_augmentations\nfrom nemo.collections.common.losses import CrossEntropyLoss as CELoss\nfrom nemo.collections.common.metrics import TopKClassificationAccuracy\nfrom nemo.core.classes import ModelPT\nfrom nemo.core.classes.common import PretrainedModelInfo, typecheck\nfrom nemo.core.classes.exportable import Exportable\nfrom nemo.core.neural_types import *\nfrom nemo.utils import logging\nfrom nemo.utils.export_utils import attach_onnx_to_onnx\n\n__all__ = ['EncDecSpeakerLabelModel', 'ExtractSpeakerEmbeddingsModel']\n\n\nclass EncDecSpeakerLabelModel(ModelPT, Exportable):\n \"\"\"Encoder decoder class for speaker label models.\n Model class creates training, validation methods for setting up data\n performing model forward pass.\n Expects config dict for\n * preprocessor\n * Jasper/Quartznet Encoder\n * Speaker Decoder\n \"\"\"\n\n @classmethod\n def list_available_models(cls) -> List[PretrainedModelInfo]:\n \"\"\"\n This method returns a list of pre-trained model which can be instantiated directly from NVIDIA's NGC cloud.\n\n Returns:\n List of available pre-trained models.\n \"\"\"\n result = []\n model = PretrainedModelInfo(\n pretrained_model_name=\"SpeakerNet_recognition\",\n location=\"https://api.ngc.nvidia.com/v2/models/nvidia/nemospeechmodels/versions/1.0.0a5/files/SpeakerNet_recognition.nemo\",\n description=\"SpeakerNet_recognition model trained end-to-end for speaker recognition purposes with cross_entropy loss. It was trained on voxceleb 1, voxceleb 2 dev datasets and augmented with musan music and noise. Speaker Recognition model achieves 2.65% EER on voxceleb-O cleaned trial file\",\n )\n result.append(model)\n\n model = PretrainedModelInfo(\n pretrained_model_name=\"SpeakerNet_verification\",\n location=\"https://api.ngc.nvidia.com/v2/models/nvidia/nemospeechmodels/versions/1.0.0a5/files/SpeakerNet_verification.nemo\",\n description=\"SpeakerNet_verification model trained end-to-end for speaker verification purposes with arcface angular softmax loss. It was trained on voxceleb 1, voxceleb 2 dev datasets and augmented with musan music and noise. Speaker Verification model achieves 2.12% EER on voxceleb-O cleaned trial file\",\n )\n result.append(model)\n\n return result\n\n def __init__(self, cfg: DictConfig, trainer: Trainer = None):\n super().__init__(cfg=cfg, trainer=trainer)\n self.preprocessor = EncDecSpeakerLabelModel.from_config_dict(cfg.preprocessor)\n self.encoder = EncDecSpeakerLabelModel.from_config_dict(cfg.encoder)\n self.decoder = EncDecSpeakerLabelModel.from_config_dict(cfg.decoder)\n if 'angular' in cfg.decoder and cfg.decoder['angular']:\n logging.info(\"Training with Angular Softmax Loss\")\n scale = cfg.loss.scale\n margin = cfg.loss.margin\n self.loss = AngularSoftmaxLoss(scale=scale, margin=margin)\n else:\n logging.info(\"Training with Softmax-CrossEntropy loss\")\n self.loss = CELoss()\n\n self._accuracy = TopKClassificationAccuracy(top_k=[1], dist_sync_on_step=True)\n\n def __setup_dataloader_from_config(self, config: Optional[Dict]):\n if 'augmentor' in config:\n augmentor = process_augmentations(config['augmentor'])\n else:\n augmentor = None\n\n featurizer = WaveformFeaturizer(\n sample_rate=config['sample_rate'], int_values=config.get('int_values', False), augmentor=augmentor\n )\n self.dataset = AudioToSpeechLabelDataSet(\n manifest_filepath=config['manifest_filepath'],\n labels=config['labels'],\n featurizer=featurizer,\n max_duration=config.get('max_duration', None),\n min_duration=config.get('min_duration', None),\n trim=config.get('trim_silence', True),\n load_audio=config.get('load_audio', True),\n time_length=config.get('time_length', 8),\n )\n\n return torch.utils.data.DataLoader(\n dataset=self.dataset,\n batch_size=config['batch_size'],\n collate_fn=self.dataset.fixed_seq_collate_fn,\n drop_last=config.get('drop_last', False),\n shuffle=config['shuffle'],\n num_workers=config.get('num_workers', 2),\n pin_memory=config.get('pin_memory', False),\n )\n\n def setup_training_data(self, train_data_layer_config: Optional[Union[DictConfig, Dict]]):\n if 'shuffle' not in train_data_layer_config:\n train_data_layer_config['shuffle'] = True\n self._train_dl = self.__setup_dataloader_from_config(config=train_data_layer_config)\n\n def setup_validation_data(self, val_data_layer_config: Optional[Union[DictConfig, Dict]]):\n if 'shuffle' not in val_data_layer_config:\n val_data_layer_config['shuffle'] = False\n val_data_layer_config['labels'] = self.dataset.labels\n self._validation_dl = self.__setup_dataloader_from_config(config=val_data_layer_config)\n\n def setup_test_data(self, test_data_layer_params: Optional[Union[DictConfig, Dict]]):\n if 'shuffle' not in test_data_layer_params:\n test_data_layer_params['shuffle'] = False\n if hasattr(self, 'dataset'):\n test_data_layer_params['labels'] = self.dataset.labels\n self.embedding_dir = test_data_layer_params.get('embedding_dir', './')\n self.test_manifest = test_data_layer_params.get('manifest_filepath', None)\n self._test_dl = self.__setup_dataloader_from_config(config=test_data_layer_params)\n\n @property\n def input_types(self) -> Optional[Dict[str, NeuralType]]:\n if hasattr(self.preprocessor, '_sample_rate'):\n audio_eltype = AudioSignal(freq=self.preprocessor._sample_rate)\n else:\n audio_eltype = AudioSignal()\n return {\n \"input_signal\": NeuralType(('B', 'T'), audio_eltype),\n \"input_signal_length\": NeuralType(tuple('B'), LengthsType()),\n }\n\n @property\n def output_types(self) -> Optional[Dict[str, NeuralType]]:\n return {\n \"logits\": NeuralType(('B', 'D'), LogitsType()),\n \"embs\": NeuralType(('B', 'D'), AcousticEncodedRepresentation()),\n }\n\n @typecheck()\n def forward(self, input_signal, input_signal_length):\n processed_signal, processed_signal_len = self.preprocessor(\n input_signal=input_signal, length=input_signal_length,\n )\n\n encoded, _ = self.encoder(audio_signal=processed_signal, length=processed_signal_len)\n logits, embs = self.decoder(encoder_output=encoded)\n return logits, embs\n\n # PTL-specific methods\n def training_step(self, batch, batch_idx):\n audio_signal, audio_signal_len, labels, _ = batch\n logits, _ = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len)\n loss = self.loss(logits=logits, labels=labels)\n\n self.log('loss', loss)\n self.log('learning_rate', self._optimizer.param_groups[0]['lr'])\n\n self._accuracy(logits=logits, labels=labels)\n top_k = self._accuracy.compute()\n for i, top_i in enumerate(top_k):\n self.log(f'training_batch_accuracy_top@{i}', top_i)\n\n return {'loss': loss}\n\n def validation_step(self, batch, batch_idx, dataloader_idx: int = 0):\n audio_signal, audio_signal_len, labels, _ = batch\n logits, _ = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len)\n loss_value = self.loss(logits=logits, labels=labels)\n acc_top_k = self._accuracy(logits=logits, labels=labels)\n correct_counts, total_counts = self._accuracy.correct_counts_k, self._accuracy.total_counts_k\n\n return {\n 'val_loss': loss_value,\n 'val_correct_counts': correct_counts,\n 'val_total_counts': total_counts,\n 'val_acc_top_k': acc_top_k,\n }\n\n def multi_validation_epoch_end(self, outputs, dataloader_idx: int = 0):\n val_loss_mean = torch.stack([x['val_loss'] for x in outputs]).mean()\n correct_counts = torch.stack([x['val_correct_counts'] for x in outputs]).sum(axis=0)\n total_counts = torch.stack([x['val_total_counts'] for x in outputs]).sum(axis=0)\n\n self._accuracy.correct_counts_k = correct_counts\n self._accuracy.total_counts_k = total_counts\n topk_scores = self._accuracy.compute()\n\n logging.info(\"val_loss: {:.3f}\".format(val_loss_mean))\n self.log('val_loss', val_loss_mean)\n for top_k, score in zip(self._accuracy.top_k, topk_scores):\n self.log('val_epoch_accuracy_top@{}'.format(top_k), score)\n\n return {\n 'val_loss': val_loss_mean,\n 'val_acc_top_k': topk_scores,\n }\n\n def test_step(self, batch, batch_idx, dataloader_idx: int = 0):\n audio_signal, audio_signal_len, labels, _ = batch\n logits, _ = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len)\n loss_value = self.loss(logits=logits, labels=labels)\n acc_top_k = self._accuracy(logits=logits, labels=labels)\n correct_counts, total_counts = self._accuracy.correct_counts_k, self._accuracy.total_counts_k\n\n return {\n 'test_loss': loss_value,\n 'test_correct_counts': correct_counts,\n 'test_total_counts': total_counts,\n 'test_acc_top_k': acc_top_k,\n }\n\n def multi_test_epoch_end(self, outputs, dataloader_idx: int = 0):\n test_loss_mean = torch.stack([x['test_loss'] for x in outputs]).mean()\n correct_counts = torch.stack([x['test_correct_counts'] for x in outputs]).sum(axis=0)\n total_counts = torch.stack([x['test_total_counts'] for x in outputs]).sum(axis=0)\n\n self._accuracy.correct_counts_k = correct_counts\n self._accuracy.total_counts_k = total_counts\n topk_scores = self._accuracy.compute()\n\n logging.info(\"test_loss: {:.3f}\".format(test_loss_mean))\n self.log('test_loss', test_loss_mean)\n for top_k, score in zip(self._accuracy.top_k, topk_scores):\n self.log('test_epoch_accuracy_top@{}'.format(top_k), score)\n\n return {\n 'test_loss': test_loss_mean,\n 'test_acc_top_k': topk_scores,\n }\n\n def setup_finetune_model(self, model_config: DictConfig):\n \"\"\"\n setup_finetune_model method sets up training data, validation data and test data with new\n provided config, this checks for the previous labels set up during training from scratch, if None,\n it sets up labels for provided finetune data from manifest files\n\n Args:\n model_config: cfg which has train_ds, optional validation_ds, optional test_ds and\n mandatory encoder and decoder model params\n make sure you set num_classes correctly for finetune data\n\n Returns: None\n\n \"\"\"\n if hasattr(self, 'dataset'):\n scratch_labels = self.dataset.labels\n else:\n scratch_labels = None\n\n logging.info(\"Setting up data loaders with manifests provided from model_config\")\n\n if 'train_ds' in model_config and model_config.train_ds is not None:\n self.setup_training_data(model_config.train_ds)\n else:\n raise KeyError(\"train_ds is not found in model_config but you need it for fine tuning\")\n\n if self.dataset.labels is None or len(self.dataset.labels) == 0:\n raise ValueError(f'New labels must be non-empty list of labels. But I got: {self.dataset.labels}')\n\n if 'validation_ds' in model_config and model_config.validation_ds is not None:\n self.setup_multiple_validation_data(model_config.validation_ds)\n\n if 'test_ds' in model_config and model_config.test_ds is not None:\n self.setup_multiple_test_data(model_config.test_ds)\n\n if scratch_labels == self.dataset.labels: # checking for new finetune dataset labels\n logging.warning(\n \"Trained dataset labels are same as finetune dataset labels -- continuing change of decoder parameters\"\n )\n elif scratch_labels is None:\n logging.warning(\n \"Either you provided a dummy manifest file during training from scratch or you restored from a pretrained nemo file\"\n )\n\n decoder_config = model_config.decoder\n new_decoder_config = copy.deepcopy(decoder_config)\n if new_decoder_config['num_classes'] != len(self.dataset.labels):\n raise ValueError(\n \"number of classes provided {} is not same as number of different labels in finetuning data: {}\".format(\n new_decoder_config['num_classes'], len(self.dataset.labels)\n )\n )\n\n del self.decoder\n self.decoder = EncDecSpeakerLabelModel.from_config_dict(new_decoder_config)\n\n with open_dict(self._cfg.decoder):\n self._cfg.decoder = new_decoder_config\n\n logging.info(f\"Changed decoder output to # {self.decoder._num_classes} classes.\")\n\n def export(\n self,\n output: str,\n input_example=None,\n output_example=None,\n verbose=False,\n export_params=True,\n do_constant_folding=True,\n keep_initializers_as_inputs=False,\n onnx_opset_version: int = 12,\n try_script: bool = False,\n set_eval: bool = True,\n check_trace: bool = True,\n use_dynamic_axes: bool = True,\n ):\n if input_example is not None or output_example is not None:\n logging.warning(\n \"Passed input and output examples will be ignored and recomputed since\"\n \" EncDecSpeakerModel consists of two separate models (encoder and decoder) with different\"\n \" inputs and outputs.\"\n )\n\n encoder_onnx = self.encoder.export(\n os.path.join(os.path.dirname(output), 'encoder_' + os.path.basename(output)),\n None, # computed by input_example()\n None,\n verbose,\n export_params,\n do_constant_folding,\n keep_initializers_as_inputs,\n onnx_opset_version,\n try_script,\n set_eval,\n check_trace,\n use_dynamic_axes,\n )\n\n decoder_onnx = self.decoder.export(\n os.path.join(os.path.dirname(output), 'decoder_' + os.path.basename(output)),\n None, # computed by input_example()\n None,\n verbose,\n export_params,\n do_constant_folding,\n keep_initializers_as_inputs,\n onnx_opset_version,\n try_script,\n set_eval,\n check_trace,\n use_dynamic_axes,\n )\n\n output_model = attach_onnx_to_onnx(encoder_onnx, decoder_onnx, \"SL\")\n onnx.save(output_model, output)\n\n\nclass ExtractSpeakerEmbeddingsModel(EncDecSpeakerLabelModel):\n \"\"\"\n This Model class facilitates extraction of speaker embeddings from a pretrained model.\n Respective embedding file is saved in self.embedding dir passed through cfg\n \"\"\"\n\n def __init__(self, cfg: DictConfig, trainer: Trainer = None):\n super().__init__(cfg=cfg, trainer=trainer)\n\n def test_step(self, batch, batch_ix):\n audio_signal, audio_signal_len, labels, slices = batch\n _, embs = self.forward(input_signal=audio_signal, input_signal_length=audio_signal_len)\n return {'embs': embs, 'labels': labels, 'slices': slices}\n\n def test_epoch_end(self, outputs):\n embs = torch.cat([x['embs'] for x in outputs])\n slices = torch.cat([x['slices'] for x in outputs])\n emb_shape = embs.shape[-1]\n embs = embs.view(-1, emb_shape).cpu().numpy()\n out_embeddings = {}\n start_idx = 0\n with open(self.test_manifest, 'r') as manifest:\n for idx, line in enumerate(manifest.readlines()):\n line = line.strip()\n dic = json.loads(line)\n structure = dic['audio_filepath'].split('/')[-3:]\n uniq_name = '@'.join(structure)\n if uniq_name in out_embeddings:\n raise KeyError(\"Embeddings for label {} already present in emb dictionary\".format(uniq_name))\n num_slices = slices[idx]\n end_idx = start_idx + num_slices\n out_embeddings[uniq_name] = embs[start_idx:end_idx].mean(axis=0)\n start_idx = end_idx\n\n embedding_dir = os.path.join(self.embedding_dir, 'embeddings')\n if not os.path.exists(embedding_dir):\n os.mkdir(embedding_dir)\n\n prefix = self.test_manifest.split('/')[-1].split('.')[-2]\n\n name = os.path.join(embedding_dir, prefix)\n pkl.dump(out_embeddings, open(name + '_embeddings.pkl', 'wb'))\n logging.info(\"Saved embedding files to {}\".format(embedding_dir))\n\n return {}\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.\nimport io\nimport os\nfrom typing import Callable, Dict, List, Optional, Union\n\nimport braceexpand\nimport torch\nimport webdataset as wd\nfrom torch.nn import functional as F\n\nfrom nemo.collections.asr.data import vocabs\nfrom nemo.collections.asr.parts import collections, parsers\nfrom nemo.collections.asr.parts.features import WaveformFeaturizer\nfrom nemo.core.classes import Dataset, IterableDataset\nfrom nemo.core.neural_types import *\nfrom nemo.utils import logging\nfrom nemo.utils.decorators import experimental\n\n__all__ = [\n 'AudioToCharDataset',\n 'AudioToCharWithDursDataset',\n 'AudioToBPEDataset',\n 'AudioLabelDataset',\n 'TarredAudioToCharDataset',\n 'TarredAudioToBPEDataset',\n]\n\n\ndef _speech_collate_fn(batch, pad_id):\n \"\"\"collate batch of audio sig, audio len, tokens, tokens len\n Args:\n batch (Optional[FloatTensor], Optional[LongTensor], LongTensor,\n LongTensor): A tuple of tuples of signal, signal lengths,\n encoded tokens, and encoded tokens length. This collate func\n assumes the signals are 1d torch tensors (i.e. mono audio).\n \"\"\"\n _, audio_lengths, _, tokens_lengths = zip(*batch)\n max_audio_len = 0\n has_audio = audio_lengths[0] is not None\n if has_audio:\n max_audio_len = max(audio_lengths).item()\n max_tokens_len = max(tokens_lengths).item()\n\n audio_signal, tokens = [], []\n for sig, sig_len, tokens_i, tokens_i_len in batch:\n if has_audio:\n sig_len = sig_len.item()\n if sig_len < max_audio_len:\n pad = (0, max_audio_len - sig_len)\n sig = torch.nn.functional.pad(sig, pad)\n audio_signal.append(sig)\n tokens_i_len = tokens_i_len.item()\n if tokens_i_len < max_tokens_len:\n pad = (0, max_tokens_len - tokens_i_len)\n tokens_i = torch.nn.functional.pad(tokens_i, pad, value=pad_id)\n tokens.append(tokens_i)\n\n if has_audio:\n audio_signal = torch.stack(audio_signal)\n audio_lengths = torch.stack(audio_lengths)\n else:\n audio_signal, audio_lengths = None, None\n tokens = torch.stack(tokens)\n tokens_lengths = torch.stack(tokens_lengths)\n\n return audio_signal, audio_lengths, tokens, tokens_lengths\n\n\nclass _AudioTextDataset(Dataset):\n \"\"\"\n Dataset that loads tensors via a json file containing paths to audio files, transcripts, and durations (in seconds).\n Each new line is a different sample. Example below:\n {\"audio_filepath\": \"/path/to/audio.wav\", \"text_filepath\": \"/path/to/audio.txt\", \"duration\": 23.147}\n ...\n {\"audio_filepath\": \"/path/to/audio.wav\", \"text\": \"the transcription\", \"offset\": 301.75, \"duration\": 0.82, \"utt\":\n \"utterance_id\", \"ctm_utt\": \"en_4156\", \"side\": \"A\"}\n Args:\n manifest_filepath: Path to manifest json as described above. Can be comma-separated paths.\n labels: String containing all the possible characters to map to\n sample_rate (int): Sample rate to resample loaded audio to\n int_values (bool): If true, load samples as 32-bit integers. Defauts to False.\n augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor object used to augment loaded\n audio\n max_duration: If audio exceeds this length, do not include in dataset\n min_duration: If audio is less than this length, do not include in dataset\n max_utts: Limit number of utterances\n blank_index: blank character index, default = -1\n unk_index: unk_character index, default = -1\n normalize: whether to normalize transcript text (default): True\n bos_id: Id of beginning of sequence symbol to append if not None\n eos_id: Id of end of sequence symbol to append if not None\n load_audio: Boolean flag indicate whether do or not load audio\n add_misc: True if add additional info dict.\n \"\"\"\n\n @property\n def output_types(self) -> Optional[Dict[str, NeuralType]]:\n \"\"\"Returns definitions of module output ports.\n \"\"\"\n return {\n 'audio_signal': NeuralType(\n ('B', 'T'),\n AudioSignal(freq=self._sample_rate) # TODO: self._sample_rate is not defined anywhere\n if self is not None and hasattr(self, '_sample_rate')\n else AudioSignal(),\n ),\n 'a_sig_length': NeuralType(tuple('B'), LengthsType()),\n 'transcripts': NeuralType(('B', 'T'), LabelsType()),\n 'transcript_length': NeuralType(tuple('B'), LengthsType()),\n }\n\n def __init__(\n self,\n manifest_filepath: str,\n parser: Union[str, Callable],\n sample_rate: int,\n int_values: bool = False,\n augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None,\n max_duration: Optional[int] = None,\n min_duration: Optional[int] = None,\n max_utts: int = 0,\n trim: bool = False,\n bos_id: Optional[int] = None,\n eos_id: Optional[int] = None,\n pad_id: int = 0,\n load_audio: bool = True,\n add_misc: bool = False,\n ):\n self.parser = parser\n\n self.collection = collections.ASRAudioText(\n manifests_files=manifest_filepath.split(','),\n parser=parser,\n min_duration=min_duration,\n max_duration=max_duration,\n max_number=max_utts,\n )\n\n self.featurizer = WaveformFeaturizer(sample_rate=sample_rate, int_values=int_values, augmentor=augmentor)\n self.trim = trim\n self.eos_id = eos_id\n self.bos_id = bos_id\n self.pad_id = pad_id\n self.load_audio = load_audio\n self._add_misc = add_misc\n\n def __getitem__(self, index):\n sample = self.collection[index]\n if self.load_audio:\n offset = sample.offset\n\n if offset is None:\n offset = 0\n\n features = self.featurizer.process(\n sample.audio_file, offset=offset, duration=sample.duration, trim=self.trim, orig_sr=sample.orig_sr\n )\n f, fl = features, torch.tensor(features.shape[0]).long()\n else:\n f, fl = None, None\n\n t, tl = sample.text_tokens, len(sample.text_tokens)\n if self.bos_id is not None:\n t = [self.bos_id] + t\n tl += 1\n if self.eos_id is not None:\n t = t + [self.eos_id]\n tl += 1\n\n output = f, fl, torch.tensor(t).long(), torch.tensor(tl).long()\n\n if self._add_misc:\n misc = dict()\n misc['id'] = sample.id\n misc['text_raw'] = sample.text_raw\n misc['speaker'] = sample.speaker\n output = (output, misc)\n\n return output\n\n def __len__(self):\n return len(self.collection)\n\n def _collate_fn(self, batch):\n return _speech_collate_fn(batch, pad_id=self.pad_id)\n\n\n@experimental\nclass AudioToCharDataset(_AudioTextDataset):\n \"\"\"\n Dataset that loads tensors via a json file containing paths to audio\n files, transcripts, and durations (in seconds). Each new line is a\n different sample. Example below:\n {\"audio_filepath\": \"/path/to/audio.wav\", \"text_filepath\":\n \"/path/to/audio.txt\", \"duration\": 23.147}\n ...\n {\"audio_filepath\": \"/path/to/audio.wav\", \"text\": \"the\n transcription\", \"offset\": 301.75, \"duration\": 0.82, \"utt\":\n \"utterance_id\", \"ctm_utt\": \"en_4156\", \"side\": \"A\"}\n Args:\n manifest_filepath: Path to manifest json as described above. Can\n be comma-separated paths.\n labels: String containing all the possible characters to map to\n sample_rate (int): Sample rate to resample loaded audio to\n int_values (bool): If true, load samples as 32-bit integers. Defauts to False.\n augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor\n object used to augment loaded audio\n max_duration: If audio exceeds this length, do not include in dataset\n min_duration: If audio is less than this length, do not include\n in dataset\n max_utts: Limit number of utterances\n blank_index: blank character index, default = -1\n unk_index: unk_character index, default = -1\n normalize: whether to normalize transcript text (default): True\n bos_id: Id of beginning of sequence symbol to append if not None\n eos_id: Id of end of sequence symbol to append if not None\n load_audio: Boolean flag indicate whether do or not load audio\n add_misc: True if add additional info dict.\n \"\"\"\n\n @property\n def output_types(self) -> Optional[Dict[str, NeuralType]]:\n \"\"\"Returns definitions of module output ports.\n \"\"\"\n return {\n 'audio_signal': NeuralType(\n ('B', 'T'),\n AudioSignal(freq=self._sample_rate)\n if self is not None and hasattr(self, '_sample_rate')\n else AudioSignal(),\n ),\n 'a_sig_length': NeuralType(tuple('B'), LengthsType()),\n 'transcripts': NeuralType(('B', 'T'), LabelsType()),\n 'transcript_length': NeuralType(tuple('B'), LengthsType()),\n }\n\n def __init__(\n self,\n manifest_filepath: str,\n labels: Union[str, List[str]],\n sample_rate: int,\n int_values: bool = False,\n augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None,\n max_duration: Optional[float] = None,\n min_duration: Optional[float] = None,\n max_utts: int = 0,\n blank_index: int = -1,\n unk_index: int = -1,\n normalize: bool = True,\n trim: bool = False,\n bos_id: Optional[int] = None,\n eos_id: Optional[int] = None,\n pad_id: int = 0,\n load_audio: bool = True,\n parser: Union[str, Callable] = 'en',\n add_misc: bool = False,\n ):\n self.labels = labels\n\n parser = parsers.make_parser(\n labels=labels, name=parser, unk_id=unk_index, blank_id=blank_index, do_normalize=normalize\n )\n\n super().__init__(\n manifest_filepath=manifest_filepath,\n parser=parser,\n sample_rate=sample_rate,\n int_values=int_values,\n augmentor=augmentor,\n max_duration=max_duration,\n min_duration=min_duration,\n max_utts=max_utts,\n trim=trim,\n bos_id=bos_id,\n eos_id=eos_id,\n pad_id=pad_id,\n load_audio=load_audio,\n add_misc=add_misc,\n )\n\n\nclass AudioToCharWithDursDataset(AudioToCharDataset):\n \"\"\"\n Dataset that loads tensors via a json file containing paths to audio\n files, transcripts, and durations (in seconds). Each new line is a\n different sample. Example below:\n {\"audio_filepath\": \"/path/to/audio.wav\", \"text_filepath\":\n \"/path/to/audio.txt\", \"duration\": 23.147}\n ...\n {\"audio_filepath\": \"/path/to/audio.wav\", \"text\": \"the\n transcription\", \"offset\": 301.75, \"duration\": 0.82, \"utt\":\n \"utterance_id\", \"ctm_utt\": \"en_4156\", \"side\": \"A\"}\n\n Additionally, user provides path to precomputed durations, which is a pickled python dict with 'tags' and 'durs'\n keys, both of which are list of examples values. Tag is a unique example identifier, which is a wav filename\n without suffix. Durations are an additional tuple of two tensors: graphemes durations and blanks durations.\n Example below:\n {'tags': ['LJ050-0234', 'LJ019-0373'],\n 'durs': [(graphemes_durs0, blanks_durs0), (graphemes_durs1, blanks_durs1)]}\n\n Args:\n **kwargs: Passed to AudioToCharDataset constructor.\n durs_path (str): String path to pickled list of '[(tag, durs)]' durations location.\n rep (bool): True if repeat text graphemes according to durs.\n vocab: Vocabulary config (parser + set of graphemes to use). Constructor propagates these to\n `self.make_vocab` function call to build a complete vocabulary.\n \"\"\"\n\n @property\n def output_types(self) -> Optional[Dict[str, NeuralType]]:\n \"\"\"Returns definitions of module output ports.\"\"\"\n return {\n 'audio': NeuralType(\n ('B', 'T'),\n AudioSignal(freq=self._sample_rate)\n if self is not None and hasattr(self, '_sample_rate')\n else AudioSignal(),\n ),\n 'audio_len': NeuralType(('B',), LengthsType()),\n 'text': NeuralType(('B', 'T'), LabelsType()),\n 'text_len': NeuralType(('B',), LengthsType()),\n 'durs': NeuralType(('B', 'T'), LengthsType()),\n }\n\n @staticmethod\n def make_vocab(notation='chars', punct=True, spaces=False, stresses=False):\n \"\"\"Constructs vocabulary from given parameters.\n\n Args:\n notation (str): Either 'chars' or 'phonemes' as general notation.\n punct (bool): True if reserve grapheme for basic punctuation.\n spaces (bool): True if prepend spaces to every punctuation symbol.\n stresses (bool): True if use phonemes codes with stresses (0-2).\n\n Returns:\n (vocabs.Base) Vocabulary\n \"\"\"\n if notation == 'chars':\n vocab = vocabs.Chars(punct=punct, spaces=spaces)\n elif notation == 'phonemes':\n vocab = vocabs.Phonemes(punct=punct, stresses=stresses, spaces=spaces)\n else:\n raise ValueError(\"Unsupported vocab type.\")\n return vocab\n\n def __init__(self, **kwargs):\n durs_path = kwargs.pop('durs_path')\n rep = kwargs.pop('rep', False)\n self.vocab = self.make_vocab(**kwargs.pop('vocab', {}))\n kwargs.setdefault('labels', [])\n\n super().__init__(**kwargs)\n\n pth = torch.load(durs_path)\n tag2d = dict(zip(pth['tags'], pth['durs']))\n durs = []\n for i, e in enumerate(self.collection):\n tag = os.path.splitext(os.path.basename(e.audio_file))[0]\n durs.append(tag2d[tag])\n self.durs = durs\n self.rep = rep\n\n def __getitem__(self, item):\n sample = self.collection[item]\n audio, audio_len, _, _ = super().__getitem__(item) # noqa\n text = self.vocab.encode(sample.text_raw)\n text, text_len = torch.tensor(text).long(), torch.tensor(len(text)).long()\n blanks_durs, graphemes_durs = self.durs[item]\n\n return (\n audio,\n audio_len,\n text,\n text_len,\n blanks_durs,\n graphemes_durs,\n )\n\n @staticmethod\n def _merge(tensors, dim=0, value=0, dtype=None):\n \"\"\"Merges list of tensors into one.\"\"\"\n tensors = [tensor if isinstance(tensor, torch.Tensor) else torch.tensor(tensor) for tensor in tensors]\n dim = dim if dim != -1 else len(tensors[0].shape) - 1\n dtype = tensors[0].dtype if dtype is None else dtype\n max_len = max(tensor.shape[dim] for tensor in tensors)\n new_tensors = []\n for tensor in tensors:\n pad = (2 * len(tensor.shape)) * [0]\n pad[-2 * dim - 1] = max_len - tensor.shape[dim]\n new_tensors.append(F.pad(tensor, pad=pad, value=value))\n return torch.stack(new_tensors).to(dtype=dtype)\n\n @staticmethod\n def _interleave(x, y):\n \"\"\"Interleave two tensors.\"\"\"\n xy = torch.stack([x[:-1], y], dim=1).view(-1)\n xy = F.pad(xy, pad=[0, 1], value=x[-1])\n return xy\n\n def _collate_fn(self, batch):\n batch = list(zip(*batch))\n\n asr_batch = _speech_collate_fn(list(zip(*batch[:4])), pad_id=self.vocab.pad)\n audio, audio_len, text, text_len = asr_batch\n\n text = [\n self._interleave(\n x=torch.empty(len(t) + 1, dtype=torch.long, device=t.device,).fill_(self.vocab.blank), y=t,\n )\n for t in text\n ]\n text = self._merge(text, value=self.vocab.pad, dtype=torch.long)\n text_len = text_len * 2 + 1\n\n blanks_durs, graphemes_durs = batch[4:]\n durs = [self._interleave(b, c) for b, c in zip(blanks_durs, graphemes_durs)]\n durs = self._merge(durs, dtype=torch.long).to(text.device)\n\n if self.rep:\n text = self._merge(\n tensors=[torch.repeat_interleave(text1, durs1) for text1, durs1 in zip(text, durs)], dtype=torch.long,\n )\n text_len = durs.sum(-1)\n\n return (\n audio,\n audio_len,\n text,\n text_len,\n durs,\n )\n\n\n@experimental\nclass AudioToBPEDataset(_AudioTextDataset):\n @property\n def output_types(self) -> Optional[Dict[str, NeuralType]]:\n \"\"\"Returns definitions of module output ports.\n \"\"\"\n return {\n 'audio_signal': NeuralType(\n ('B', 'T'),\n AudioSignal(freq=self._sample_rate)\n if self is not None and hasattr(self, '_sample_rate')\n else AudioSignal(),\n ),\n 'a_sig_length': NeuralType(tuple('B'), LengthsType()),\n 'transcripts': NeuralType(('B', 'T'), LabelsType()),\n 'transcript_length': NeuralType(tuple('B'), LengthsType()),\n }\n\n def __init__(\n self,\n manifest_filepath: str,\n tokenizer: 'nemo.collections.common.tokenizers.TokenizerSpec',\n sample_rate: int,\n int_values: bool = False,\n augmentor: 'nemo.collections.asr.parts.perturb.AudioAugmentor' = None,\n max_duration: Optional[int] = None,\n min_duration: Optional[int] = None,\n max_utts: int = 0,\n trim: bool = False,\n load_audio: bool = True,\n add_misc: bool = False,\n use_start_end_token: bool = True,\n ):\n if use_start_end_token and hasattr(tokenizer, 'bos_token'):\n bos_id = tokenizer.bos_id\n else:\n bos_id = None\n\n if use_start_end_token and hasattr(tokenizer, 'eos_token'):\n eos_id = tokenizer.eos_id\n else:\n eos_id = None\n\n if hasattr(tokenizer, 'pad_token'):\n pad_id = tokenizer.pad_id\n else:\n pad_id = 0\n\n class TokenizerWrapper:\n def __init__(self, tokenizer):\n self._tokenizer = tokenizer\n\n def __call__(self, text):\n t = self._tokenizer.text_to_ids(text)\n return t\n\n super().__init__(\n manifest_filepath=manifest_filepath,\n parser=TokenizerWrapper(tokenizer),\n sample_rate=sample_rate,\n int_values=int_values,\n augmentor=augmentor,\n max_duration=max_duration,\n min_duration=min_duration,\n max_utts=max_utts,\n bos_id=bos_id,\n eos_id=eos_id,\n pad_id=pad_id,\n trim=trim,\n load_audio=load_audio,\n add_misc=add_misc,\n )\n\n\n# Ported from https://github.com/NVIDIA/OpenSeq2Seq/blob/master/open_seq2seq/data/speech2text/speech_commands.py\n@experimental\nclass AudioLabelDataset(Dataset):\n \"\"\"\n Dataset that loads tensors via a json file containing paths to audio\n files, command class, and durations (in seconds). Each new line is a\n different sample. Example below:\n {\"audio_filepath\": \"/path/to/audio.wav\", \"label\":\n \"label\", \"duration\": 23.147}\n ...\n {\"audio_filepath\": \"/path/to/audio.wav\", \"label\": \"label\",\n \"offset\": 301.75, \"duration\": 0.82}\n Args:\n manifest_filepath: Path to manifest json as described above. Can\n be comma-separated paths.\n labels (Optional[list]): String containing all the possible labels to map to\n if None then automatically picks from ASRSpeechLabel collection.\n featurizer: Initialized featurizer class that converts paths of\n audio to feature tensors\n max_duration: If audio exceeds this length, do not include in dataset\n min_duration: If audio is less than this length, do not include\n in dataset\n trim: Boolean flag whether to trim the audio\n load_audio: Boolean flag indicate whether do or not load audio\n \"\"\"\n\n def __init__(\n self,\n manifest_filepath,\n featurizer,\n labels=None,\n max_duration=None,\n min_duration=None,\n trim=False,\n load_audio=True,\n ):\n self.collection = collections.ASRSpeechLabel(\n manifests_files=manifest_filepath.split(','), min_duration=min_duration, max_duration=max_duration\n )\n\n self.featurizer = featurizer\n self.trim = trim\n self.load_audio = load_audio\n\n self.labels = labels if labels else self.collection.uniq_labels\n self.num_commands = len(self.labels)\n\n self.label2id, self.id2label = {}, {}\n for label_id, label in enumerate(self.labels):\n self.label2id[label] = label_id\n self.id2label[label_id] = label\n\n def __getitem__(self, index):\n sample = self.collection[index]\n if self.load_audio:\n offset = sample.offset\n\n if offset is None:\n offset = 0\n\n features = self.featurizer.process(\n sample.audio_file, offset=offset, duration=sample.duration, trim=self.trim\n )\n f, fl = features, torch.tensor(features.shape[0]).long()\n else:\n f, fl = None, None\n\n t = self.label2id[sample.label]\n tl = 1 # For compatibility with collate_fn used later\n\n return f, fl, torch.tensor(t).long(), torch.tensor(tl).long()\n\n def __len__(self):\n return len(self.collection)\n\n def _collate_fn(self, batch):\n \"\"\"collate batch of audio sig, audio len, tokens (single token), tokens len (1)\n Args:\n batch (Optional[FloatTensor], Optional[LongTensor], LongTensor,\n LongTensor): A tuple of tuples of signal, signal lengths,\n encoded tokens, and encoded tokens length. This collate func\n assumes the signals are 1d torch tensors (i.e. mono audio).\n \"\"\"\n return _speech_collate_fn(batch, pad_id=0)\n\n\n@experimental\nclass _TarredAudioToTextDataset(IterableDataset):\n \"\"\"\n A similar Dataset to the AudioToCharDataset/AudioToBPEDataset, but which loads tarred audio files.\n\n Accepts a single comma-separated JSON manifest file (in the same style as for the AudioToCharDataset/AudioToBPEDataset),\n as well as the path(s) to the tarball(s) containing the wav files. Each line of the manifest should\n contain the information for one audio file, including at least the transcript and name of the audio\n file within the tarball.\n\n Valid formats for the audio_tar_filepaths argument include:\n (1) a single string that can be brace-expanded, e.g. 'path/to/audio.tar' or 'path/to/audio_{1..100}.tar.gz', or\n (2) a list of file paths that will not be brace-expanded, e.g. ['audio_1.tar', 'audio_2.tar', ...].\n\n Note: For brace expansion in (1), there may be cases where `{x..y}` syntax cannot be used due to shell interference.\n This occurs most commonly inside SLURM scripts. Therefore we provide a few equivalent replacements.\n Supported opening braces - { <=> (, [, < and the special tag _OP_.\n Supported closing braces - } <=> ), ], > and the special tag _CL_.\n For SLURM based tasks, we suggest the use of the special tags for ease of use.\n\n See the WebDataset documentation for more information about accepted data and input formats.\n\n If using multiple processes the number of shards should be divisible by the number of workers to ensure an\n even split among workers. If it is not divisible, logging will give a warning but training will proceed.\n In addition, if using mutiprocessing, each shard MUST HAVE THE SAME NUMBER OF ENTRIES after filtering\n is applied. We currently do not check for this, but your program may hang if the shards are uneven!\n\n Notice that a few arguments are different from the AudioToCharDataset; for example, shuffle (bool) has been\n replaced by shuffle_n (int).\n\n Additionally, please note that the len() of this DataLayer is assumed to be the length of the manifest\n after filtering. An incorrect manifest length may lead to some DataLoader issues down the line.\n\n Args:\n audio_tar_filepaths: Either a list of audio tarball filepaths, or a\n string (can be brace-expandable).\n manifest_filepath (str): Path to the manifest.\n parser (callable): A callable which is used to pre-process the text output.\n sample_rate (int): Sample rate to resample loaded audio to\n int_values (bool): If true, load samples as 32-bit integers. Defauts to False.\n augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor\n object used to augment loaded audio\n shuffle_n (int): How many samples to look ahead and load to be shuffled.\n See WebDataset documentation for more details.\n Defaults to 0.\n min_duration (float): Dataset parameter.\n All training files which have a duration less than min_duration\n are dropped. Note: Duration is read from the manifest JSON.\n Defaults to 0.1.\n max_duration (float): Dataset parameter.\n All training files which have a duration more than max_duration\n are dropped. Note: Duration is read from the manifest JSON.\n Defaults to None.\n max_utts (int): Limit number of utterances. 0 means no maximum.\n blank_index (int): Blank character index, defaults to -1.\n unk_index (int): Unknown character index, defaults to -1.\n normalize (bool): Dataset parameter.\n Whether to use automatic text cleaning.\n It is highly recommended to manually clean text for best results.\n Defaults to True.\n trim (bool): Whether to use trim silence from beginning and end\n of audio signal using librosa.effects.trim().\n Defaults to False.\n bos_id (id): Dataset parameter.\n Beginning of string symbol id used for seq2seq models.\n Defaults to None.\n eos_id (id): Dataset parameter.\n End of string symbol id used for seq2seq models.\n Defaults to None.\n pad_id (id): Token used to pad when collating samples in batches.\n If this is None, pads using 0s.\n Defaults to None.\n global_rank (int): Worker rank, used for partitioning shards. Defaults to 0.\n world_size (int): Total number of processes, used for partitioning shards. Defaults to 0.\n \"\"\"\n\n def __init__(\n self,\n audio_tar_filepaths: Union[str, List[str]],\n manifest_filepath: str,\n parser: Callable,\n sample_rate: int,\n int_values: bool = False,\n augmentor: Optional['nemo.collections.asr.parts.perturb.AudioAugmentor'] = None,\n shuffle_n: int = 0,\n min_duration: Optional[float] = None,\n max_duration: Optional[float] = None,\n max_utts: int = 0,\n trim: bool = False,\n bos_id: Optional[int] = None,\n eos_id: Optional[int] = None,\n add_misc: bool = False,\n pad_id: int = 0,\n global_rank: int = 0,\n world_size: int = 0,\n ):\n self.collection = collections.ASRAudioText(\n manifests_files=manifest_filepath.split(','),\n parser=parser,\n min_duration=min_duration,\n max_duration=max_duration,\n max_number=max_utts,\n index_by_file_id=True, # Must set this so the manifest lines can be indexed by file ID\n )\n\n self.featurizer = WaveformFeaturizer(sample_rate=sample_rate, int_values=int_values, augmentor=augmentor)\n self.trim = trim\n self.eos_id = eos_id\n self.bos_id = bos_id\n self.pad_id = pad_id\n self._add_misc = add_misc\n\n if isinstance(audio_tar_filepaths, str):\n # Replace '(' and '[' with '{'\n brace_keys_open = ['(', '[', '<', '_OP_']\n for bkey in brace_keys_open:\n if bkey in audio_tar_filepaths:\n audio_tar_filepaths = audio_tar_filepaths.replace(bkey, \"{\")\n\n # Replace ')' and ']' with '}'\n brace_keys_close = [')', ']', '>', '_CL_']\n for bkey in brace_keys_close:\n if bkey in audio_tar_filepaths:\n audio_tar_filepaths = audio_tar_filepaths.replace(bkey, \"}\")\n\n # Check for distributed and partition shards accordingly\n if world_size > 1:\n if isinstance(audio_tar_filepaths, str):\n # Brace expand\n audio_tar_filepaths = list(braceexpand.braceexpand(audio_tar_filepaths))\n\n if len(audio_tar_filepaths) % world_size != 0:\n logging.warning(\n f\"Number of shards in tarred dataset ({len(audio_tar_filepaths)}) is not divisible \"\n f\"by number of distributed workers ({world_size}).\"\n )\n\n begin_idx = (len(audio_tar_filepaths) // world_size) * global_rank\n end_idx = begin_idx + (len(audio_tar_filepaths) // world_size)\n audio_tar_filepaths = audio_tar_filepaths[begin_idx:end_idx]\n logging.info(\n \"Partitioning tarred dataset: process (%d) taking shards [%d, %d)\", global_rank, begin_idx, end_idx\n )\n\n # Put together WebDataset\n self._dataset = (\n wd.Dataset(audio_tar_filepaths)\n .shuffle(shuffle_n)\n .rename(audio='wav', key='__key__')\n .to_tuple('audio', 'key')\n .pipe(self._filter)\n .map(f=self._build_sample)\n )\n\n def _filter(self, iterator):\n \"\"\"This function is used to remove samples that have been filtered out by ASRAudioText already.\n Otherwise, we would get a KeyError as _build_sample attempts to find the manifest entry for a sample\n that was filtered out (e.g. for duration).\n Note that if using multi-GPU training, filtering may lead to an imbalance in samples in each shard,\n which may make your code hang as one process will finish before the other.\n \"\"\"\n\n class TarredAudioFilter:\n def __init__(self, collection):\n self.iterator = iterator\n self.collection = collection\n\n def __iter__(self):\n return self\n\n def __next__(self):\n while True:\n audio_bytes, audio_filename = next(self.iterator)\n file_id, _ = os.path.splitext(os.path.basename(audio_filename))\n if file_id in self.collection.mapping:\n return audio_bytes, audio_filename\n\n return TarredAudioFilter(self.collection)\n\n def _collate_fn(self, batch):\n return _speech_collate_fn(batch, self.pad_id)\n\n def _build_sample(self, tup):\n \"\"\"Builds the training sample by combining the data from the WebDataset with the manifest info.\n \"\"\"\n audio_bytes, audio_filename = tup\n\n # Grab manifest entry from self.collection\n file_id, _ = os.path.splitext(os.path.basename(audio_filename))\n manifest_idx = self.collection.mapping[file_id]\n manifest_entry = self.collection[manifest_idx]\n\n offset = manifest_entry.offset\n if offset is None:\n offset = 0\n\n # Convert audio bytes to IO stream for processing (for SoundFile to read)\n audio_filestream = io.BytesIO(audio_bytes)\n features = self.featurizer.process(\n audio_filestream,\n offset=offset,\n duration=manifest_entry.duration,\n trim=self.trim,\n orig_sr=manifest_entry.orig_sr,\n )\n audio_filestream.close()\n\n # Audio features\n f, fl = features, torch.tensor(features.shape[0]).long()\n\n # Text features\n t, tl = manifest_entry.text_tokens, len(manifest_entry.text_tokens)\n if self.bos_id is not None:\n t = [self.bos_id] + t\n tl += 1\n if self.eos_id is not None:\n t = t + [self.eos_id]\n tl += 1\n\n return f, fl, torch.tensor(t).long(), torch.tensor(tl).long()\n\n def __iter__(self):\n return self._dataset.__iter__()\n\n def __len__(self):\n return len(self.collection)\n\n\n@experimental\nclass TarredAudioToCharDataset(_TarredAudioToTextDataset):\n \"\"\"\n A similar Dataset to the AudioToCharDataset, but which loads tarred audio files.\n\n Accepts a single comma-separated JSON manifest file (in the same style as for the AudioToCharDataset),\n as well as the path(s) to the tarball(s) containing the wav files. Each line of the manifest should\n contain the information for one audio file, including at least the transcript and name of the audio\n file within the tarball.\n\n Valid formats for the audio_tar_filepaths argument include:\n (1) a single string that can be brace-expanded, e.g. 'path/to/audio.tar' or 'path/to/audio_{1..100}.tar.gz', or\n (2) a list of file paths that will not be brace-expanded, e.g. ['audio_1.tar', 'audio_2.tar', ...].\n\n See the WebDataset documentation for more information about accepted data and input formats.\n\n If using multiple processes the number of shards should be divisible by the number of workers to ensure an\n even split among workers. If it is not divisible, logging will give a warning but training will proceed.\n In addition, if using mutiprocessing, each shard MUST HAVE THE SAME NUMBER OF ENTRIES after filtering\n is applied. We currently do not check for this, but your program may hang if the shards are uneven!\n\n Notice that a few arguments are different from the AudioToCharDataset; for example, shuffle (bool) has been\n replaced by shuffle_n (int).\n\n Additionally, please note that the len() of this DataLayer is assumed to be the length of the manifest\n after filtering. An incorrect manifest length may lead to some DataLoader issues down the line.\n\n Args:\n audio_tar_filepaths: Either a list of audio tarball filepaths, or a\n string (can be brace-expandable).\n manifest_filepath (str): Path to the manifest.\n labels (list): List of characters that can be output by the ASR model.\n For Jasper, this is the 28 character set {a-z '}. The CTC blank\n symbol is automatically added later for models using ctc.\n sample_rate (int): Sample rate to resample loaded audio to\n int_values (bool): If true, load samples as 32-bit integers. Defauts to False.\n augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor\n object used to augment loaded audio\n shuffle_n (int): How many samples to look ahead and load to be shuffled.\n See WebDataset documentation for more details.\n Defaults to 0.\n min_duration (float): Dataset parameter.\n All training files which have a duration less than min_duration\n are dropped. Note: Duration is read from the manifest JSON.\n Defaults to 0.1.\n max_duration (float): Dataset parameter.\n All training files which have a duration more than max_duration\n are dropped. Note: Duration is read from the manifest JSON.\n Defaults to None.\n max_utts (int): Limit number of utterances. 0 means no maximum.\n blank_index (int): Blank character index, defaults to -1.\n unk_index (int): Unknown character index, defaults to -1.\n normalize (bool): Dataset parameter.\n Whether to use automatic text cleaning.\n It is highly recommended to manually clean text for best results.\n Defaults to True.\n trim (bool): Whether to use trim silence from beginning and end\n of audio signal using librosa.effects.trim().\n Defaults to False.\n bos_id (id): Dataset parameter.\n Beginning of string symbol id used for seq2seq models.\n Defaults to None.\n eos_id (id): Dataset parameter.\n End of string symbol id used for seq2seq models.\n Defaults to None.\n pad_id (id): Token used to pad when collating samples in batches.\n If this is None, pads using 0s.\n Defaults to None.\n global_rank (int): Worker rank, used for partitioning shards. Defaults to 0.\n world_size (int): Total number of processes, used for partitioning shards. Defaults to 0.\n \"\"\"\n\n def __init__(\n self,\n audio_tar_filepaths: Union[str, List[str]],\n manifest_filepath: str,\n labels: List[str],\n sample_rate: int,\n int_values: bool = False,\n augmentor: Optional['nemo.collections.asr.parts.perturb.AudioAugmentor'] = None,\n shuffle_n: int = 0,\n min_duration: Optional[float] = None,\n max_duration: Optional[float] = None,\n max_utts: int = 0,\n blank_index: int = -1,\n unk_index: int = -1,\n normalize: bool = True,\n trim: bool = False,\n bos_id: Optional[int] = None,\n eos_id: Optional[int] = None,\n parser: Optional[str] = 'en',\n add_misc: bool = False,\n pad_id: int = 0,\n global_rank: int = 0,\n world_size: int = 0,\n ):\n self.labels = labels\n\n parser = parsers.make_parser(\n labels=labels, name=parser, unk_id=unk_index, blank_id=blank_index, do_normalize=normalize\n )\n\n super().__init__(\n audio_tar_filepaths=audio_tar_filepaths,\n manifest_filepath=manifest_filepath,\n parser=parser,\n sample_rate=sample_rate,\n int_values=int_values,\n augmentor=augmentor,\n shuffle_n=shuffle_n,\n min_duration=min_duration,\n max_duration=max_duration,\n max_utts=max_utts,\n trim=trim,\n bos_id=bos_id,\n eos_id=eos_id,\n add_misc=add_misc,\n pad_id=pad_id,\n global_rank=global_rank,\n world_size=world_size,\n )\n\n\n@experimental\nclass TarredAudioToBPEDataset(_TarredAudioToTextDataset):\n \"\"\"\n A similar Dataset to the AudioToBPEDataset, but which loads tarred audio files.\n\n Accepts a single comma-separated JSON manifest file (in the same style as for the AudioToBPEDataset),\n as well as the path(s) to the tarball(s) containing the wav files. Each line of the manifest should\n contain the information for one audio file, including at least the transcript and name of the audio\n file within the tarball.\n\n Valid formats for the audio_tar_filepaths argument include:\n (1) a single string that can be brace-expanded, e.g. 'path/to/audio.tar' or 'path/to/audio_{1..100}.tar.gz', or\n (2) a list of file paths that will not be brace-expanded, e.g. ['audio_1.tar', 'audio_2.tar', ...].\n\n See the WebDataset documentation for more information about accepted data and input formats.\n\n If using multiple processes the number of shards should be divisible by the number of workers to ensure an\n even split among workers. If it is not divisible, logging will give a warning but training will proceed.\n In addition, if using mutiprocessing, each shard MUST HAVE THE SAME NUMBER OF ENTRIES after filtering\n is applied. We currently do not check for this, but your program may hang if the shards are uneven!\n\n Notice that a few arguments are different from the AudioToBPEDataset; for example, shuffle (bool) has been\n replaced by shuffle_n (int).\n\n Additionally, please note that the len() of this DataLayer is assumed to be the length of the manifest\n after filtering. An incorrect manifest length may lead to some DataLoader issues down the line.\n\n Args:\n audio_tar_filepaths: Either a list of audio tarball filepaths, or a\n string (can be brace-expandable).\n manifest_filepath (str): Path to the manifest.\n tokenizer (TokenizerSpec): Either a Word Piece Encoding tokenizer (BERT),\n or a Sentence Piece Encoding tokenizer (BPE). The CTC blank\n symbol is automatically added later for models using ctc.\n sample_rate (int): Sample rate to resample loaded audio to\n int_values (bool): If true, load samples as 32-bit integers. Defauts to False.\n augmentor (nemo.collections.asr.parts.perturb.AudioAugmentor): An AudioAugmentor\n object used to augment loaded audio\n shuffle_n (int): How many samples to look ahead and load to be shuffled.\n See WebDataset documentation for more details.\n Defaults to 0.\n min_duration (float): Dataset parameter.\n All training files which have a duration less than min_duration\n are dropped. Note: Duration is read from the manifest JSON.\n Defaults to 0.1.\n max_duration (float): Dataset parameter.\n All training files which have a duration more than max_duration\n are dropped. Note: Duration is read from the manifest JSON.\n Defaults to None.\n max_utts (int): Limit number of utterances. 0 means no maximum.\n trim (bool): Whether to use trim silence from beginning and end\n of audio signal using librosa.effects.trim().\n Defaults to False.\n pad_id (id): Token used to pad when collating samples in batches.\n If this is None, pads using 0s.\n Defaults to None.\n global_rank (int): Worker rank, used for partitioning shards. Defaults to 0.\n world_size (int): Total number of processes, used for partitioning shards. Defaults to 0.\n \"\"\"\n\n def __init__(\n self,\n audio_tar_filepaths: Union[str, List[str]],\n manifest_filepath: str,\n tokenizer: 'nemo.collections.common.tokenizers.TokenizerSpec',\n sample_rate: int,\n int_values: bool = False,\n augmentor: Optional['nemo.collections.asr.parts.perturb.AudioAugmentor'] = None,\n shuffle_n: int = 0,\n min_duration: Optional[float] = None,\n max_duration: Optional[float] = None,\n max_utts: int = 0,\n trim: bool = False,\n add_misc: bool = False,\n global_rank: int = 0,\n world_size: int = 0,\n use_start_end_token: bool = True,\n ):\n if use_start_end_token and hasattr(tokenizer, 'bos_token'):\n bos_id = tokenizer.bos_id\n else:\n bos_id = None\n\n if use_start_end_token and hasattr(tokenizer, 'eos_token'):\n eos_id = tokenizer.eos_id\n else:\n eos_id = None\n\n if hasattr(tokenizer, 'pad_token'):\n pad_id = tokenizer.pad_id\n else:\n pad_id = 0\n\n class TokenizerWrapper:\n def __init__(self, tokenizer):\n self._tokenizer = tokenizer\n\n def __call__(self, text):\n t = self._tokenizer.text_to_ids(text)\n return t\n\n super().__init__(\n audio_tar_filepaths=audio_tar_filepaths,\n manifest_filepath=manifest_filepath,\n parser=TokenizerWrapper(tokenizer),\n sample_rate=sample_rate,\n int_values=int_values,\n augmentor=augmentor,\n shuffle_n=shuffle_n,\n min_duration=min_duration,\n max_duration=max_duration,\n max_utts=max_utts,\n trim=trim,\n bos_id=bos_id,\n eos_id=eos_id,\n add_misc=add_misc,\n pad_id=pad_id,\n global_rank=global_rank,\n world_size=world_size,\n )\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\nimport os\nfrom typing import Dict, Optional\n\nimport torch\nfrom omegaconf import DictConfig, OmegaConf\nfrom pytorch_lightning import Trainer\nfrom torch.utils.data import DataLoader\n\nfrom nemo.collections.common.losses import AggregatorLoss, CrossEntropyLoss, SmoothedCrossEntropyLoss\nfrom nemo.collections.nlp.data.language_modeling.lm_bert_dataset import (\n BertPretrainingDataset,\n BertPretrainingPreprocessedDataloader,\n)\nfrom nemo.collections.nlp.metrics.perplexity import Perplexity\nfrom nemo.collections.nlp.modules.common import BertPretrainingTokenClassifier, SequenceClassifier\nfrom nemo.collections.nlp.modules.common.lm_utils import get_lm_model\nfrom nemo.collections.nlp.modules.common.tokenizer_utils import get_tokenizer\nfrom nemo.core.classes import typecheck\nfrom nemo.core.classes.modelPT import ModelPT\nfrom nemo.core.neural_types import NeuralType\nfrom nemo.utils import logging\n\n__all__ = [\"BERTLMModel\"]\n\n\nclass BERTLMModel(ModelPT):\n \"\"\"\n BERT language model pretraining.\n \"\"\"\n\n @property\n def input_types(self) -> Optional[Dict[str, NeuralType]]:\n return self.bert_model.input_types\n\n @property\n def output_types(self) -> Optional[Dict[str, NeuralType]]:\n output_types_dict = {\"mlm_log_probs\": self.mlm_classifier.output_types[\"log_probs\"]}\n if not self.only_mlm_loss:\n output_types_dict[\"nsp_logits\"] = self.nsp_classifier.output_types[\"logits\"]\n return output_types_dict\n\n def __init__(self, cfg: DictConfig, trainer: Trainer = None):\n\n if cfg.tokenizer is not None:\n self._setup_tokenizer(cfg.tokenizer)\n else:\n self.tokenizer = None\n\n super().__init__(cfg=cfg, trainer=trainer)\n\n self.bert_model = get_lm_model(\n pretrained_model_name=cfg.language_model.pretrained_model_name,\n config_file=cfg.language_model.config_file,\n config_dict=OmegaConf.to_container(cfg.language_model.config) if cfg.language_model.config else None,\n checkpoint_file=cfg.language_model.lm_checkpoint,\n )\n\n self.hidden_size = self.bert_model.config.hidden_size\n self.vocab_size = self.bert_model.config.vocab_size\n self.only_mlm_loss = cfg.only_mlm_loss\n\n self.mlm_classifier = BertPretrainingTokenClassifier(\n hidden_size=self.hidden_size,\n num_classes=self.vocab_size,\n num_layers=cfg.num_tok_classification_layers,\n activation=\"gelu\",\n log_softmax=True,\n use_transformer_init=True,\n )\n\n self.mlm_loss = SmoothedCrossEntropyLoss()\n\n if not self.only_mlm_loss:\n self.nsp_classifier = SequenceClassifier(\n hidden_size=self.hidden_size,\n num_classes=2,\n num_layers=cfg.num_seq_classification_layers,\n log_softmax=False,\n activation=\"tanh\",\n use_transformer_init=True,\n )\n\n self.nsp_loss = CrossEntropyLoss()\n self.agg_loss = AggregatorLoss(num_inputs=2)\n\n # # tie weights of MLM softmax layer and embedding layer of the encoder\n if (\n self.mlm_classifier.mlp.last_linear_layer.weight.shape\n != self.bert_model.embeddings.word_embeddings.weight.shape\n ):\n raise ValueError(\"Final classification layer does not match embedding layer.\")\n self.mlm_classifier.mlp.last_linear_layer.weight = self.bert_model.embeddings.word_embeddings.weight\n # create extra bias\n\n # setup to track metrics\n self.perplexity_metric = Perplexity(dist_sync_on_step=True)\n\n self.setup_optimization(cfg.optim)\n\n @typecheck()\n def forward(self, input_ids, token_type_ids, attention_mask):\n \"\"\"\n No special modification required for Lightning, define it as you normally would\n in the `nn.Module` in vanilla PyTorch.\n \"\"\"\n hidden_states = self.bert_model(\n input_ids=input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask,\n )\n mlm_log_probs = self.mlm_classifier(hidden_states=hidden_states)\n if self.only_mlm_loss:\n return (mlm_log_probs,)\n\n nsp_logits = self.nsp_classifier(hidden_states=hidden_states)\n return mlm_log_probs, nsp_logits\n\n def training_step(self, batch, batch_idx):\n \"\"\"\n Lightning calls this inside the training loop with the data from the training dataloader\n passed in as `batch`.\n \"\"\"\n # forward pass\n input_ids, input_type_ids, input_mask, output_ids, output_mask, labels = batch\n logits = self.forward(input_ids=input_ids, token_type_ids=input_type_ids, attention_mask=input_mask,)\n mlm_loss = self.mlm_loss(log_probs=logits[0], labels=output_ids, output_mask=output_mask)\n\n if self.only_mlm_loss:\n loss = mlm_loss\n else:\n nsp_loss = self.nsp_loss(logits=logits[1], labels=labels)\n\n loss = self.agg_loss(loss_1=mlm_loss, loss_2=nsp_loss)\n\n tensorboard_logs = {\"train_loss\": loss}\n return {\"loss\": loss, \"log\": tensorboard_logs}\n\n def validation_step(self, batch, batch_idx):\n \"\"\"\n Lightning calls this inside the validation loop with the data from the validation dataloader\n passed in as `batch`.\n \"\"\"\n input_ids, input_type_ids, input_mask, output_ids, output_mask, labels = batch\n logits = self.forward(input_ids=input_ids, token_type_ids=input_type_ids, attention_mask=input_mask,)\n\n mlm_loss = self.mlm_loss(log_probs=logits[0], labels=output_ids, output_mask=output_mask)\n\n if self.only_mlm_loss:\n loss = mlm_loss\n else:\n nsp_loss = self.nsp_loss(logits=logits[1], labels=labels)\n\n loss = self.agg_loss(loss_1=mlm_loss, loss_2=nsp_loss)\n perplexity = self.perplexity_metric(mlm_loss)\n tensorboard_logs = {\"val_loss\": loss, \"perplexity\": perplexity}\n return {\"val_loss\": loss, \"log\": tensorboard_logs}\n\n def validation_epoch_end(self, outputs):\n \"\"\"Called at the end of validation to aggregate outputs.\n\n Args:\n outputs (list): The individual outputs of each validation step.\n\n Returns:\n dict: Validation loss and tensorboard logs.\n \"\"\"\n if outputs:\n avg_loss = torch.stack([x[\"val_loss\"] for x in outputs]).mean()\n perplexity = torch.stack([x[\"log\"][\"perplexity\"] for x in outputs]).mean()\n tensorboard_logs = {\"val_loss\": avg_loss, \"perplexity\": perplexity}\n logging.info(f\"evaluation perplexity {perplexity.item()}\")\n return {\"val_loss\": avg_loss, \"log\": tensorboard_logs}\n\n def setup_training_data(self, train_data_config: Optional[DictConfig]):\n self._train_dl = (\n self._setup_preprocessed_dataloader(train_data_config)\n if self.tokenizer is None\n else self._setup_dataloader(train_data_config)\n )\n\n def setup_validation_data(self, val_data_config: Optional[DictConfig]):\n self._validation_dl = (\n self._setup_preprocessed_dataloader(val_data_config)\n if self.tokenizer is None\n else self._setup_dataloader(val_data_config)\n )\n\n def setup_test_data(self, test_data_config: Optional[DictConfig]):\n pass\n\n def _setup_preprocessed_dataloader(self, cfg: Optional[DictConfig]):\n dataset = cfg.data_file\n max_predictions_per_seq = cfg.max_predictions_per_seq\n batch_size = cfg.batch_size\n\n if os.path.isdir(dataset):\n files = [os.path.join(dataset, f) for f in os.listdir(dataset) if os.path.isfile(os.path.join(dataset, f))]\n else:\n files = [dataset]\n files.sort()\n dl = BertPretrainingPreprocessedDataloader(\n data_files=files, max_predictions_per_seq=max_predictions_per_seq, batch_size=batch_size,\n )\n return dl\n\n def _setup_tokenizer(self, cfg: DictConfig):\n tokenizer = get_tokenizer(\n tokenizer_name=cfg.tokenizer_name,\n tokenizer_model=cfg.tokenizer_model,\n special_tokens=OmegaConf.to_container(cfg.special_tokens) if cfg.special_tokens else None,\n vocab_file=cfg.vocab_file,\n )\n self.tokenizer = tokenizer\n\n def _setup_dataloader(self, cfg: DictConfig):\n dataset = BertPretrainingDataset(\n tokenizer=self.tokenizer,\n data_file=cfg.data_file,\n max_seq_length=cfg.max_seq_length,\n mask_prob=cfg.mask_prob,\n short_seq_prob=cfg.short_seq_prob,\n )\n dl = torch.utils.data.DataLoader(\n dataset=dataset,\n batch_size=cfg.batch_size,\n collate_fn=dataset.collate_fn,\n drop_last=cfg.get(\"drop_last\", False),\n shuffle=cfg.shuffle,\n num_workers=cfg.get(\"num_workers\", 0),\n )\n return dl\n\n @classmethod\n def list_available_models(cls) -> Optional[Dict[str, str]]:\n pass\n" ]
[ [ "torch.stack", "torch.cat" ], [ "torch.load", "torch.tensor", "torch.repeat_interleave", "torch.stack", "torch.nn.functional.pad" ], [ "torch.stack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
GBATZOLIS/CAFLOW
[ "ea33f84c424bd8e46999be59cd5d52bd8f0a3a77" ]
[ "caflow/models/modules/mri_to_pet/UnconditionalFlow.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 19 22:02:53 2021\n\n@author: gbatz97\n\"\"\"\n\nimport torch.nn as nn\nimport torch\nfrom caflow.models.modules.blocks.FlowBlock import FlowBlock \nfrom caflow.models.modules.blocks.Dequantisation import Dequantisation, VariationalDequantization\n\nclass UnconditionalFlow(nn.Module):\n def __init__(self, channels, dim, resolution, scales, scale_depth, quants, vardeq_depth, coupling_type, nn_settings):\n super(UnconditionalFlow, self).__init__()\n \n self.channels = channels\n self.dim = dim\n self.resolution = resolution\n self.scales = scales\n \n self.scale_blocks = nn.ModuleList()\n\n if vardeq_depth is None:\n self.scale_blocks.append(Dequantisation(dim=dim, quants=quants))\n else:\n self.scale_blocks.append(VariationalDequantization(channels=channels, depth=vardeq_depth, dim=dim, \\\n resolution=self.calculate_resolution(dim, 0),\\\n quants=quants, coupling_type=coupling_type, nn_settings=nn_settings))\n\n for scale in range(self.scales):\n scale_channels = self.calculate_scale_channels(dim, scale)\n resolution = self.calculate_resolution(dim, scale)\n self.scale_blocks.append(FlowBlock(channels = scale_channels, dim = dim,\n resolution=resolution, depth = scale_depth,\n coupling_type=coupling_type, nn_settings=nn_settings))\n\n # Create prior distribution for final latent space\n self.prior = torch.distributions.normal.Normal(loc=0.0, scale=1.0)\n \n def calculate_resolution(self, dim, scale):\n if isinstance(self.resolution, int):\n resolution = tuple([self.resolution//2**scale for _ in range(self.dim)])\n else:\n resolution = tuple([x//2**scale for x in self.resolution])\n return resolution\n\n def calculate_scale_channels(self, dim, scale):\n if scale==0:\n return 2 ** (dim * scale) * self.channels\n else:\n return 2 ** ((dim-1) * scale) * self.channels\n \n \n def forward(self, y=None, z=[], logprior=0., logdet=0., reverse=False):\n if reverse:\n #assert z is not None\n y_dec, logdet = self.decode(z, logdet=logdet)\n return y_dec, logdet\n else:\n #assert y is not None\n z_enc, logprior, logdet = self.encode(y, logprior=logprior, logdet=logdet)\n return z_enc, logprior, logdet\n \n def encode(self, y, logprior, logdet):\n #y is the HR image/scan that we want to encode in the latent space\n #z_enc: list of the encoded latent tensors in ascending scale order\n #order: from scale 1 (dim=orig_dim/2) --- to --- scale n (dim=orig_dim/2^n)\n\n h_pass = y\n z_enc = []\n \n h_pass, logdet = self.scale_blocks[0](h_pass, logdet, False) #dequantisation\n for i in range(1, self.scales+1):\n if i==self.scales:\n h_split, logdet = self.scale_blocks[i](h_pass, logdet, False)\n else:\n h, logdet = self.scale_blocks[i](h_pass, logdet, False)\n h_split, h_pass = h.chunk(2, dim=1)\n \n logprior+=self.prior.log_prob(h_split).sum(dim = [i+1 for i in range(self.dim+1)])\n z_enc.append(h_split)\n\n return z_enc, logprior, logdet\n\n\n def decode(self, z:list, logdet):\n #z is a list of the latent tensors of the different scales.\n #The tensors of different scales have been put in an ascending order\n #z = [h_split(1st scale)-size:D/2, ..., h_split(nth scale)-size:D/2^n]\n \n h_pass=None\n for i in range(self.scales):\n h_split = z[self.scales-1-i]\n if h_pass==None:\n concat_pass = h_split\n else:\n concat_pass = torch.cat([h_split, h_pass], dim=1)\n h_pass, logdet = self.scale_blocks[self.scales-i](concat_pass, logdet, True)\n \n h_pass, logdet = self.scale_blocks[0](h_pass, logdet, True) #quantisation\n \n return h_pass, logdet\n\n\n\"\"\"\n#instantiate the unconditional flow\nrflow = UnconditionalFlow(channels=1, dim=3, scales=4, scale_depth=3, network = GatedConvNet)\n\ny = torch.randn((2, 1, 64, 64, 64), dtype=torch.float32)\nprint('y shape: ', y.size())\n\nprint('Encoding y with the forward pass...We get z_enc (same dimensionality)')\nz_enc, logprior, logdet = rflow(y=y)\n\nprint('z_enc elements:')\nfor i, elem in enumerate(z_enc):\n print(i, elem.size())\n \nprint('logprior size: ', logprior.size())\nprint('logdet size: ', logdet.size())\n\nprint('Decoding y_dec from its z_enc enconding... We pass z_enc through the backward pass.')\ny_dec, logdet = rflow(z=z_enc, reverse=True)\nprint('y_dec size:', y_dec.size())\n\nr = torch.abs(y-y_dec)\nprint('sum(|y-y_dec|)',torch.sum(r))\nprint('mean(|y-y_dec|):',torch.mean(r))\n\"\"\"\n \n\n" ]
[ [ "torch.distributions.normal.Normal", "torch.nn.ModuleList", "torch.cat" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tech-srl/c3po
[ "a673a0514ee8c800efa12574ef8da3fcb8ef73b7", "a673a0514ee8c800efa12574ef8da3fcb8ef73b7" ]
[ "LaserTagger/Models/TransformerCRF_V2.py", "LaserTagger/Models/SequenceEncoder.py" ]
[ "from torch import nn\nfrom Models.CRF import CRF\nfrom Models.Transformer import Transformer\nfrom Models.TransformerCtx import TransformerCtx\nfrom Models.SequenceEncoder import SequenceEncoder\nfrom Models.Attention import Attention\nimport torch\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\n\n\nclass Transformer_CRF(nn.Module):\n def __init__(self, vocab_size, ctx_vocab_size, nb_labels, emb_dim, hidden_dim, bos_idx, eos_idx, pad_idx, num_lstm_layers, dropout, device):\n super().__init__()\n self.transformer = Transformer(\n vocab_size, in_dim=emb_dim, nb_labels=nb_labels, dropout=dropout\n )\n self.crf = CRF(\n nb_labels,\n device,\n bos_idx,\n eos_idx,\n pad_tag_id=pad_idx,\n batch_first=True,\n )\n self.ctx_encoder = TransformerCtx(ctx_vocab_size, device=device, in_dim=emb_dim)\n self.ctx_combiner = Attention(emb_dim)\n self.query = nn.Parameter(torch.Tensor(1, emb_dim))\n torch.nn.init.xavier_uniform_(self.query.data)\n self.emb_dim = emb_dim\n self.ctx_linear = nn.Linear(2 * emb_dim, emb_dim)\n\n def combine_ctx(self, x, before_ctx, after_ctx):\n # (batch, h_dim)\n before_ctx_encoded = self.before_ctx_encoder(before_ctx)\n after_ctx_encoded = self.after_ctx_encoder(after_ctx)\n\n # (batch, 2 * h_dim)\n ctx_cat = torch.cat((before_ctx_encoded, after_ctx_encoded), dim=1)\n # (batch, h_dim)\n encoded_ctx = torch.tanh(self.ctx_linear(ctx_cat))\n\n seq_len = x.shape[1]\n\n # (batch, seq_len, h_dim)\n encoded_ctx_repeated = encoded_ctx.unsqueeze(dim=0).repeat(seq_len, 1, 1)\n return encoded_ctx_repeated\n\n def forward_ctx(self, x, before_ctx, after_ctx):\n batch_size = x.shape[0]\n # (batch_size, 1, emb_dim)\n query = self.query.expand(batch_size, self.emb_dim).unsqueeze(dim=1)\n packed_query = pack_padded_sequence(query, batch_size * [1], batch_first=True, enforce_sorted=False)\n # Packed sequence (before_ctx_length, batch_size, emb_dim)\n encoded_before_ctx = self.ctx_encoder(before_ctx)\n # (batch_size, 1, emb_dim)\n encoded_before_ctx, _ = self.ctx_combiner(packed_query, encoded_before_ctx)\n # Packed sequence (after_ctx_length, batch_size, emb_dim)\n encoded_after_ctx = self.ctx_encoder(after_ctx)\n # (batch_size, 1 ,emb_dim)\n encoded_after_ctx, _ = self.ctx_combiner(packed_query, encoded_after_ctx)\n # (batch_size ,emb_dim)\n combined_ctx = self.ctx_linear(torch.cat([encoded_before_ctx, encoded_after_ctx], dim=2).squeeze())\n # (1, batch_size ,emb_dim)\n combined_ctx = combined_ctx.unsqueeze(dim=0)\n seq_len = x.shape[1]\n # (seq_len, batch_size, emb_dim)\n combined_ctx = combined_ctx.repeat(seq_len, 1, 1)\n return combined_ctx\n\n def forward(self, x, before_ctx, after_ctx, mask=None):\n # (seq_len, batch_size, emb_dim)\n combined_ctx = self.forward_ctx(x, before_ctx, after_ctx)\n # (batch_size, src_length, num_labels)\n emissions = self.transformer(x, combined_ctx, mask)\n score, path = self.crf.decode(emissions, mask=mask)\n return score, path\n\n def loss(self, x, before_ctx, after_ctx, y, mask=None):\n # (seq_len, batch_size, emb_dim)\n combined_ctx = self.forward_ctx(x, before_ctx, after_ctx)\n # (batch_size, src_length, num_labels)\n emissions = self.transformer(x, combined_ctx, mask)\n nll = self.crf(emissions, y, mask=mask)\n return nll\n", "import torch.nn as nn\nfrom Models.Embedding import Embedding\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\nimport torch\n\n\nclass SequenceEncoder(nn.Module):\n def __init__(self, vocab_size, in_dim, h_dim, num_layers, dropout, padding_idx):\n super(SequenceEncoder, self).__init__()\n self.emb = Embedding(vocab_size, in_dim, padding_idx)\n self.rnn = nn.LSTM(input_size=in_dim,\n hidden_size=h_dim,\n num_layers=num_layers,\n dropout=dropout,\n bidirectional=True)\n self.linear = nn.Linear(2 * h_dim, h_dim)\n self.dropout = nn.Dropout(p=dropout)\n self.num_layers = num_layers\n self.num_direction = 2\n self.h_dim = h_dim\n\n def forward(self, src):\n \"\"\"\n :param src: of shape (src_length, batch)\n :return: out: PackedSequence of shape (batch, h_dim)\n \"\"\"\n src, src_lengths = pad_packed_sequence(src)\n src_length, batch_size = src.size()\n # (src_length, batch, in_dim)\n src_in = self.emb(src)\n\n src_packed = pack_padded_sequence(src_in, src_lengths, enforce_sorted=False)\n # out: (path_length, batch, num_directions * h_dim)\n # (h_n, c_n): (num_layers * num_directions, batch, h_dim)\n out, (h_n, c_n) = self.rnn(src_packed)\n # (num_layers, num_directions, batch, h_dim)\n h_n = h_n.view(self.num_layers, self.num_direction, batch_size, self.h_dim)\n # (batch, h_dim)\n h_forward = h_n[-1, 0]\n h_backward = h_n[-1, 1]\n # (batch, 2* h_dim)\n out_cat = torch.cat((h_forward, h_backward), dim=1)\n # (batch, h_dim)\n out_linear = self.linear(out_cat)\n output = torch.tanh(out_linear)\n output = self.dropout(output)\n return output\n\n" ]
[ [ "torch.Tensor", "torch.cat", "torch.nn.utils.rnn.pack_padded_sequence", "torch.nn.Linear", "torch.nn.init.xavier_uniform_" ], [ "torch.nn.Dropout", "torch.nn.LSTM", "torch.cat", "torch.nn.utils.rnn.pack_padded_sequence", "torch.tanh", "torch.nn.Linear", "torch.nn.utils.rnn.pad_packed_sequence" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kevinintel/neural-compressor
[ "b57645566aeff8d3c18dc49d2739a583c072f940", "b57645566aeff8d3c18dc49d2739a583c072f940", "b57645566aeff8d3c18dc49d2739a583c072f940", "b57645566aeff8d3c18dc49d2739a583c072f940", "b57645566aeff8d3c18dc49d2739a583c072f940", "b57645566aeff8d3c18dc49d2739a583c072f940", "b57645566aeff8d3c18dc49d2739a583c072f940" ]
[ "examples/pytorch/eager/image_recognition/cifar100/main.py", "examples/pytorch/fx/object_detection/ssd_resnet34/ptq/python/main.py", "test/test_tensorflow_set_tensor.py", "examples/engine/nlp/mrpc/bert_base_sparse/utils.py", "neural_compressor/adaptor/engine_utils/util.py", "test/test_tensorflow_graph_cse_optimization.py", "test/test_onnxrt_augment.py" ]
[ "import os\nimport time\nimport shutil\nimport argparse\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.models.vgg as vgg\nimport torchvision.datasets as datasets\nimport torchvision.transforms as transforms\n\nfrom plain_cnn_cifar import ConvNetMaker, plane_cifar100_book\n\n# used for logging to TensorBoard\nfrom tensorboard_logger import configure, log_value\n\nparser = argparse.ArgumentParser(description='PyTorch CNN or VGG Training')\nparser.add_argument('--dataset', default='cifar100', type=str,\n help='dataset cifar100')\nparser.add_argument('--epochs', default=200, type=int,\n help='number of total epochs to run')\nparser.add_argument('--start-epoch', default=0, type=int,\n help='manual epoch number (useful on restarts)')\nparser.add_argument('-b', '--batch-size', default=128, type=int,\n help='mini-batch size (default: 128)')\nparser.add_argument('--lr', '--learning-rate', default=0.02, type=float,\n help='initial learning rate')\nparser.add_argument('--momentum', default=0.9, type=float, help='momentum')\nparser.add_argument('--nesterov', default=True, type=bool, help='nesterov momentum')\nparser.add_argument('--weight-decay', '--wd', default=5e-4, type=float,\n help='weight decay (default: 5e-4)')\nparser.add_argument('--print-freq', '-p', default=10, type=int,\n help='print frequency (default: 10)')\nparser.add_argument('--droprate', default=0, type=float,\n help='dropout probability (default: 0.0)')\nparser.add_argument('--no-augment', dest='augment', action='store_false',\n help='whether to use standard augmentation (default: True)')\nparser.add_argument('--resume', default='', type=str,\n help='path to latest checkpoint (default: none)')\nparser.add_argument('--name', default='CNN-2', type=str,\n help='name of experiment')\nparser.add_argument('--student_type', default='CNN-2', type=str,\n help='type of student model (CNN-2 [default] or VGG-8)')\nparser.add_argument('--teacher_type', default='CNN-10', type=str,\n help='type of teacher model (CNN-10 [default] or VGG-13)')\nparser.add_argument('--teacher_model', default='runs/CNN-10/model_best.pth.tar', type=str,\n help='path of teacher model')\nparser.add_argument('--tensorboard',\n help='Log progress to TensorBoard', action='store_true')\n\nparser.add_argument(\"--seed\", type=int, default=5143, help=\"A seed for reproducible training.\")\nparser.add_argument(\"--config\", default='distillation.yaml', help=\"pruning config\")\nparser.add_argument(\"--temperature\", default=1, type=float,\n help='temperature parameter of distillation')\nparser.add_argument(\"--loss_types\", default=['CE', 'KL'], type=str, nargs='+',\n help='loss types of distillation, should be a list of length 2, '\n 'first for student targets loss, second for teacher student loss.')\nparser.add_argument(\"--loss_weights\", default=[0.5, 0.5], type=float, nargs='+',\n help='loss weights of distillation, should be a list of length 2, '\n 'and sum to 1.0, first for student targets loss weight, '\n 'second for teacher student loss weight.')\nparser.set_defaults(augment=True)\n\ndef set_seed(seed):\n import random\n import numpy as np\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n\ndef main():\n global args, best_prec1\n args, _ = parser.parse_known_args()\n best_prec1 = 0\n if args.seed is not None:\n set_seed(args.seed)\n if args.tensorboard: configure(\"runs/%s\"%(args.name))\n\n # Data loading code\n normalize = transforms.Normalize(mean=[0.5071, 0.4866, 0.4409], std=[0.2675, 0.2565, 0.2761])\n\n if args.augment:\n transform_train = transforms.Compose([\n \ttransforms.ToTensor(),\n \ttransforms.Lambda(lambda x: F.pad(x.unsqueeze(0),\n \t\t\t\t\t\t(4,4,4,4),mode='reflect').squeeze()),\n transforms.ToPILImage(),\n transforms.RandomCrop(32),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ])\n else:\n transform_train = transforms.Compose([\n transforms.ToTensor(),\n normalize,\n ])\n transform_test = transforms.Compose([\n transforms.ToTensor(),\n normalize\n ])\n\n # create teacher and student model\n if args.teacher_type == 'CNN-10':\n teacher_model = ConvNetMaker(plane_cifar100_book['10'])\n elif args.teacher_type == 'VGG-13':\n teacher_model = vgg.vgg13(num_classes=100)\n else:\n raise NotImplementedError('Unsupported teacher model type')\n teacher_model.load_state_dict(torch.load(args.teacher_model)['state_dict'])\n \n if args.student_type == 'CNN-2':\n student_model = ConvNetMaker(plane_cifar100_book['2'])\n elif args.student_type == 'VGG-8':\n student_model = vgg.VGG(vgg.make_layers([64, 'M', 128, 'M', 256, 'M', 512, 'M', 512, 'M']), num_classes=100)\n else:\n raise NotImplementedError('Unsupported student model type')\n\n # get the number of model parameters\n print('Number of teacher model parameters: {}'.format(\n sum([p.data.nelement() for p in teacher_model.parameters()])))\n print('Number of student model parameters: {}'.format(\n sum([p.data.nelement() for p in student_model.parameters()])))\n\n kwargs = {'num_workers': 0, 'pin_memory': True}\n assert(args.dataset == 'cifar100')\n train_dataset = datasets.__dict__[args.dataset.upper()]('../data', \n train=True, download=True,\n transform=transform_train)\n # get logits of teacher model\n if args.loss_weights[1] > 0:\n from tqdm import tqdm\n def get_logits(teacher_model, train_dataset):\n print(\"***** Getting logits of teacher model *****\")\n print(f\" Num examples = {len(train_dataset) }\")\n logits_file = os.path.join(os.path.dirname(args.teacher_model), 'teacher_logits.npy')\n if not os.path.exists(logits_file):\n teacher_model.eval()\n train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=args.batch_size, **kwargs)\n train_dataloader = tqdm(train_dataloader, desc=\"Evaluating\")\n teacher_logits = []\n for step, (input, target) in enumerate(train_dataloader):\n outputs = teacher_model(input)\n teacher_logits += [x for x in outputs.numpy()]\n np.save(logits_file, np.array(teacher_logits))\n else:\n teacher_logits = np.load(logits_file)\n train_dataset.targets = [{'labels':l, 'teacher_logits':tl} \\\n for l, tl in zip(train_dataset.targets, teacher_logits)]\n return train_dataset\n with torch.no_grad():\n train_dataset = get_logits(teacher_model, train_dataset)\n train_loader = torch.utils.data.DataLoader(train_dataset,\n batch_size=args.batch_size, shuffle=True, **kwargs)\n val_loader = torch.utils.data.DataLoader(\n datasets.__dict__[args.dataset.upper()]('../data', train=False, transform=transform_test),\n batch_size=args.batch_size, shuffle=True, **kwargs)\n\n # optionally resume from a checkpoint\n if args.resume:\n if os.path.isfile(args.resume):\n print(\"=> loading checkpoint '{}'\".format(args.resume))\n checkpoint = torch.load(args.resume)\n args.start_epoch = checkpoint['epoch']\n best_prec1 = checkpoint['best_prec1']\n student_model.load_state_dict(checkpoint['state_dict'])\n print(\"=> loaded checkpoint '{}' (epoch {})\"\n .format(args.resume, checkpoint['epoch']))\n else:\n print(\"=> no checkpoint found at '{}'\".format(args.resume))\n\n # define optimizer\n optimizer = torch.optim.SGD(student_model.parameters(), args.lr,\n momentum=args.momentum, nesterov = args.nesterov,\n weight_decay=args.weight_decay)\n\n # cosine learning rate\n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, len(train_loader)*args.epochs)\n\n def train_func(model):\n return train(train_loader, model, scheduler, distiller, best_prec1)\n\n def eval_func(model):\n return validate(val_loader, model, distiller)\n\n from neural_compressor.experimental import Distillation, common\n from neural_compressor.experimental.common.criterion import PyTorchKnowledgeDistillationLoss\n \n distiller = Distillation(args.config)\n distiller.teacher_model = common.Model(teacher_model)\n distiller.student_model = common.Model(student_model)\n distiller.train_func = train_func\n distiller.eval_func = eval_func\n distiller.optimizer = optimizer\n distiller.criterion = PyTorchKnowledgeDistillationLoss(\n temperature=args.temperature,\n loss_types=args.loss_types,\n loss_weights=args.loss_weights)\n model = distiller()\n \n directory = \"runs/%s/\"%(args.name)\n os.makedirs(directory, exist_ok=True)\n model.save(directory)\n # change to framework model for further use\n model = model.model\n\ndef train(train_loader, model, scheduler, distiller, best_prec1):\n distiller.pre_epoch_begin()\n for epoch in range(args.start_epoch, args.epochs):\n \"\"\"Train for one epoch on the training set\"\"\"\n batch_time = AverageMeter()\n losses = AverageMeter()\n top1 = AverageMeter()\n\n # switch to train mode\n model.train()\n\n end = time.time()\n for i, (input, target) in enumerate(train_loader):\n teacher_logits = None\n if isinstance(target, dict):\n teacher_logits = target['teacher_logits']\n target = target['labels']\n\n # compute output\n output = model(input)\n \n distiller.on_post_forward(input, teacher_logits)\n loss = distiller.criterion(output, target)\n\n # measure accuracy and record loss\n prec1 = accuracy(output.data, target, topk=(1,))[0]\n losses.update(loss.data.item(), input.size(0))\n top1.update(prec1.item(), input.size(0))\n\n # compute gradient and do SGD step\n distiller.optimizer.zero_grad()\n loss.backward()\n distiller.optimizer.step()\n scheduler.step()\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if i % args.print_freq == 0:\n print('Epoch: [{0}][{1}/{2}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\n 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\\t'\n 'LR {scheduler._last_lr[0]:.6f}'.format(\n epoch, i, len(train_loader), batch_time=batch_time,\n loss=losses, top1=top1, scheduler=scheduler))\n\n distiller.on_epoch_end()\n # remember best prec@1 and save checkpoint\n is_best = distiller.best_score > best_prec1\n best_prec1 = max(distiller.best_score, best_prec1)\n save_checkpoint({\n 'epoch': distiller._epoch_runned + 1,\n 'state_dict': model.state_dict(),\n 'best_prec1': best_prec1,\n }, is_best)\n # log to TensorBoard\n if args.tensorboard:\n log_value('train_loss', losses.avg, epoch)\n log_value('train_acc', top1.avg, epoch)\n log_value('learning_rate', scheduler._last_lr[0], epoch)\n \n\ndef validate(val_loader, model, distiller):\n \"\"\"Perform validation on the validation set\"\"\"\n batch_time = AverageMeter()\n top1 = AverageMeter()\n\n # switch to evaluate mode\n model.eval()\n\n end = time.time()\n for i, (input, target) in enumerate(val_loader):\n # compute output\n with torch.no_grad():\n output = model(input)\n\n # measure accuracy\n prec1 = accuracy(output.data, target, topk=(1,))[0]\n top1.update(prec1.item(), input.size(0))\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if i % args.print_freq == 0:\n print('Test: [{0}/{1}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})'.format(\n i, len(val_loader), batch_time=batch_time,\n top1=top1))\n\n print(' * Prec@1 {top1.avg:.3f}'.format(top1=top1))\n # log to TensorBoard\n if args.tensorboard:\n log_value('val_acc', top1.avg, distiller._epoch_runned)\n return top1.avg\n\ndef save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):\n \"\"\"Saves checkpoint to disk\"\"\"\n directory = \"runs/%s/\"%(args.name)\n if not os.path.exists(directory):\n os.makedirs(directory)\n filename = directory + filename\n torch.save(state, filename)\n if is_best:\n shutil.copyfile(filename, 'runs/%s/'%(args.name) + 'model_best.pth.tar')\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\ndef accuracy(output, target, topk=(1,)):\n \"\"\"Computes the precision@k for the specified values of k\"\"\"\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0)\n res.append(correct_k.mul_(100.0 / batch_size))\n return res\n\nif __name__ == '__main__':\n main()", "\"\"\"\nmlperf inference benchmarking tool\n\"\"\"\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport argparse\nimport array\nimport collections\nimport json\nimport logging\nimport os\nimport sys\nimport threading\nimport time\nfrom queue import Queue\n\nimport mlperf_loadgen as lg\nimport numpy as np\n\nimport dataset\nimport imagenet\nimport coco\nimport re\n\nlogging.basicConfig(level=logging.INFO)\nlog = logging.getLogger(\"main\")\n\nNANO_SEC = 1e9\nMILLI_SEC = 1000\n\n# pylint: disable=missing-docstring\n\n# the datasets we support\nSUPPORTED_DATASETS = {\n \"imagenet\":\n (imagenet.Imagenet, dataset.pre_process_vgg, dataset.PostProcessCommon(offset=-1),\n {\"image_size\": [224, 224, 3]}),\n \"imagenet_mobilenet\":\n (imagenet.Imagenet, dataset.pre_process_mobilenet, dataset.PostProcessArgMax(offset=-1),\n {\"image_size\": [224, 224, 3]}),\n \"imagenet_pytorch\":\n (imagenet.Imagenet, dataset.pre_process_imagenet_pytorch, dataset.PostProcessArgMax(offset=0),\n {\"image_size\": [224, 224, 3]}),\n \"coco-300\":\n (coco.Coco, dataset.pre_process_coco_mobilenet, coco.PostProcessCoco(),\n {\"image_size\": [300, 300, 3]}),\n \"coco-300-pt\":\n (coco.Coco, dataset.pre_process_coco_pt_mobilenet, coco.PostProcessCocoPt(False,0.3),\n {\"image_size\": [300, 300, 3]}), \n \"coco-1200\":\n (coco.Coco, dataset.pre_process_coco_resnet34, coco.PostProcessCoco(),\n {\"image_size\": [1200, 1200, 3]}),\n \"coco-1200-onnx\":\n (coco.Coco, dataset.pre_process_coco_resnet34, coco.PostProcessCocoOnnx(),\n {\"image_size\": [1200, 1200, 3]}),\n \"coco-1200-pt\":\n (coco.Coco, dataset.pre_process_coco_resnet34, coco.PostProcessCocoPt(True,0.05),\n {\"image_size\": [1200, 1200, 3],\"use_label_map\": True}),\n \"coco-1200-tf\":\n (coco.Coco, dataset.pre_process_coco_resnet34, coco.PostProcessCocoTf(),\n {\"image_size\": [1200, 1200, 3],\"use_label_map\": False}),\n}\n\n# pre-defined command line options so simplify things. They are used as defaults and can be\n# overwritten from command line\n\nSUPPORTED_PROFILES = {\n \"defaults\": {\n \"dataset\": \"imagenet\",\n \"backend\": \"tensorflow\",\n \"cache\": 0,\n \"max-batchsize\": 32,\n },\n\n # resnet\n \"resnet50-tf\": {\n \"inputs\": \"input_tensor:0\",\n \"outputs\": \"ArgMax:0\",\n \"dataset\": \"imagenet\",\n \"backend\": \"tensorflow\",\n \"model-name\": \"resnet50\",\n },\n \"resnet50-onnxruntime\": {\n \"dataset\": \"imagenet\",\n \"outputs\": \"ArgMax:0\",\n \"backend\": \"onnxruntime\",\n \"model-name\": \"resnet50\",\n },\n\n # mobilenet\n \"mobilenet-tf\": {\n \"inputs\": \"input:0\",\n \"outputs\": \"MobilenetV1/Predictions/Reshape_1:0\",\n \"dataset\": \"imagenet_mobilenet\",\n \"backend\": \"tensorflow\",\n \"model-name\": \"mobilenet\",\n },\n \"mobilenet-onnxruntime\": {\n \"dataset\": \"imagenet_mobilenet\",\n \"outputs\": \"MobilenetV1/Predictions/Reshape_1:0\",\n \"backend\": \"onnxruntime\",\n \"model-name\": \"mobilenet\",\n },\n\n # ssd-mobilenet\n \"ssd-mobilenet-tf\": {\n \"inputs\": \"image_tensor:0\",\n \"outputs\": \"num_detections:0,detection_boxes:0,detection_scores:0,detection_classes:0\",\n \"dataset\": \"coco-300\",\n \"backend\": \"tensorflow\",\n \"model-name\": \"ssd-mobilenet\",\n },\n \"ssd-mobilenet-pytorch\": {\n \"inputs\": \"image\",\n \"outputs\": \"bboxes,labels,scores\",\n \"dataset\": \"coco-300-pt\",\n \"backend\": \"pytorch-native\",\n \"model-name\": \"ssd-mobilenet\",\n },\n \"ssd-mobilenet-onnxruntime\": {\n \"dataset\": \"coco-300\",\n \"outputs\": \"num_detections:0,detection_boxes:0,detection_scores:0,detection_classes:0\",\n \"backend\": \"onnxruntime\",\n \"data-format\": \"NHWC\",\n \"model-name\": \"ssd-mobilenet\",\n },\n\n # ssd-resnet34\n \"ssd-resnet34-tf\": {\n \"inputs\": \"image:0\",\n \"outputs\": \"detection_bboxes:0,detection_classes:0,detection_scores:0\",\n \"dataset\": \"coco-1200-tf\",\n \"backend\": \"tensorflow\",\n \"data-format\": \"NCHW\",\n \"model-name\": \"ssd-resnet34\",\n },\n \"ssd-resnet34-pytorch\": {\n \"inputs\": \"image\",\n \"outputs\": \"bboxes,labels,scores\",\n \"dataset\": \"coco-1200-pt\",\n \"backend\": \"pytorch-native\",\n \"model-name\": \"ssd-resnet34\",\n },\n \"ssd-resnet34-onnxruntime\": {\n \"dataset\": \"coco-1200-onnx\",\n \"inputs\": \"image\",\n \"outputs\": \"bboxes,labels,scores\",\n \"backend\": \"onnxruntime\",\n \"data-format\": \"NCHW\",\n \"max-batchsize\": 1,\n \"model-name\": \"ssd-resnet34\",\n },\n \"ssd-resnet34-onnxruntime-tf\": {\n \"dataset\": \"coco-1200-tf\",\n \"inputs\": \"image:0\",\n \"outputs\": \"detection_bboxes:0,detection_classes:0,detection_scores:0\",\n \"backend\": \"onnxruntime\",\n \"data-format\": \"NHWC\",\n \"model-name\": \"ssd-resnet34\",\n },\n}\n\nSCENARIO_MAP = {\n \"SingleStream\": lg.TestScenario.SingleStream,\n \"MultiStream\": lg.TestScenario.MultiStream,\n \"Server\": lg.TestScenario.Server,\n \"Offline\": lg.TestScenario.Offline,\n}\n\nlast_timeing = []\n\n\ndef get_args():\n \"\"\"Parse commandline.\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--tune', dest='tune', action='store_true', \n help='tune best int8 model on calibration dataset')\n parser.add_argument(\"--dataset\", choices=SUPPORTED_DATASETS.keys(), help=\"dataset\")\n parser.add_argument(\"--dataset-path\", required=True, help=\"path to the dataset\")\n parser.add_argument(\"--dataset-list\", help=\"path to the dataset list\")\n parser.add_argument(\"--data-format\", choices=[\"NCHW\", \"NHWC\"], help=\"data format\")\n parser.add_argument(\"--profile\", choices=SUPPORTED_PROFILES.keys(), help=\"standard profiles\")\n parser.add_argument(\"--scenario\", default=\"SingleStream\",\n help=\"mlperf benchmark scenario, one of \" + str(list(SCENARIO_MAP.keys())))\n parser.add_argument(\"--max-batchsize\", type=int, help=\"max batch size in a single inference\")\n parser.add_argument(\"--model\", required=True, help=\"model file\")\n parser.add_argument(\"--output\", default=\"output\", help=\"test results\")\n parser.add_argument(\"--inputs\", help=\"model inputs\")\n parser.add_argument(\"--outputs\", help=\"model outputs\")\n parser.add_argument(\"--backend\", help=\"runtime to use\")\n parser.add_argument(\"--model-name\", help=\"name of the mlperf model, ie. resnet50\")\n parser.add_argument(\"--threads\", default=os.cpu_count(), type=int, help=\"threads\")\n parser.add_argument(\"--qps\", type=int, help=\"target qps\")\n parser.add_argument(\"--cache\", type=int, default=0, help=\"use cache\")\n parser.add_argument(\"--accuracy\", action=\"store_true\", help=\"enable accuracy pass\")\n parser.add_argument(\"--find-peak-performance\", action=\"store_true\", \\\n help=\"enable finding peak performance pass\")\n parser.add_argument(\"--debug\", action=\"store_true\", help=\"debug, turn traces on\")\n\n # file to use mlperf rules compliant parameters\n parser.add_argument(\"--mlperf_conf\", default=\"mlperf.conf\", \\\n help=\"mlperf rules config\")\n # file for user LoadGen settings such as target QPS\n parser.add_argument(\"--user_conf\", default=\"user.conf\", \\\n help=\"user config for user LoadGen settings such as target QPS\")\n\n # below will override mlperf rules compliant settings - don't use for official submission\n parser.add_argument(\"--time\", type=int, help=\"time to scan in seconds\")\n parser.add_argument(\"--count\", type=int, help=\"dataset items to use\")\n parser.add_argument(\"--max-latency\", type=float, help=\"mlperf max latency in pct tile\")\n parser.add_argument(\"--samples-per-query\", type=int, help=\"mlperf multi-stream sample per query\")\n parser.add_argument('--benchmark', dest='benchmark', action='store_true',\n help='run benchmark')\n parser.add_argument('--int8', dest='int8', action='store_true', help='run benchmark')\n parser.add_argument(\"--tuned_checkpoint\", default='./saved_results', type=str, metavar='PATH',\n help='path to checkpoint tuned by Neural Compressor (default: ./)')\n args = parser.parse_args()\n\n # don't use defaults in argparser. Instead we default to a dict, override that with a profile\n # and take this as default unless command line give\n defaults = SUPPORTED_PROFILES[\"defaults\"]\n\n if args.profile:\n profile = SUPPORTED_PROFILES[args.profile]\n defaults.update(profile)\n for k, v in defaults.items():\n kc = k.replace(\"-\", \"_\")\n if getattr(args, kc) is None:\n setattr(args, kc, v)\n if args.inputs:\n args.inputs = args.inputs.split(\",\")\n if args.outputs:\n args.outputs = args.outputs.split(\",\")\n\n if args.scenario not in SCENARIO_MAP:\n parser.error(\"valid scanarios:\" + str(list(SCENARIO_MAP.keys())))\n return args\n\n\ndef get_backend(backend):\n if backend == \"tensorflow\":\n from backend_tf import BackendTensorflow\n backend = BackendTensorflow()\n elif backend == \"onnxruntime\":\n from backend_onnxruntime import BackendOnnxruntime\n backend = BackendOnnxruntime()\n elif backend == \"null\":\n from backend_null import BackendNull\n backend = BackendNull()\n elif backend == \"pytorch\":\n from backend_pytorch import BackendPytorch\n backend = BackendPytorch()\n elif backend == \"pytorch-native\":\n from backend_pytorch_native import BackendPytorchNative\n backend = BackendPytorchNative() \n elif backend == \"tflite\":\n from backend_tflite import BackendTflite\n backend = BackendTflite()\n else:\n raise ValueError(\"unknown backend: \" + backend)\n return backend\n\n\nclass Item:\n \"\"\"An item that we queue for processing by the thread pool.\"\"\"\n\n def __init__(self, query_id, content_id, img, label=None):\n self.query_id = query_id\n self.content_id = content_id\n self.img = img\n self.label = label\n self.start = time.time()\n\n\nclass RunnerBase:\n def __init__(self, model, ds, threads, post_proc=None, max_batchsize=128):\n self.take_accuracy = False\n self.ds = ds\n self.model = model\n self.post_process = post_proc\n self.threads = threads\n self.take_accuracy = False\n self.max_batchsize = max_batchsize\n self.result_timing = []\n\n def handle_tasks(self, tasks_queue):\n pass\n\n def start_run(self, result_dict, take_accuracy):\n self.result_dict = result_dict\n self.result_timing = []\n self.take_accuracy = take_accuracy\n self.post_process.start()\n\n def run_one_item(self, qitem):\n # run the prediction\n processed_results = []\n try:\n results = self.model.predict({self.model.inputs[0]: qitem.img})\n processed_results = self.post_process(results, qitem.content_id, qitem.label, self.result_dict)\n if self.take_accuracy:\n self.post_process.add_results(processed_results)\n self.result_timing.append(time.time() - qitem.start)\n except Exception as ex: # pylint: disable=broad-except\n src = [self.ds.get_item_loc(i) for i in qitem.content_id]\n log.error(\"thread: failed on contentid=%s, %s\", src, ex)\n # since post_process will not run, fake empty responses\n processed_results = [[]] * len(qitem.query_id)\n finally:\n response_array_refs = []\n response = []\n for idx, query_id in enumerate(qitem.query_id):\n response_array = array.array(\"B\", np.array(processed_results[idx], np.float32).tobytes())\n response_array_refs.append(response_array)\n bi = response_array.buffer_info()\n response.append(lg.QuerySampleResponse(query_id, bi[0], bi[1]))\n lg.QuerySamplesComplete(response)\n\n def enqueue(self, query_samples):\n idx = [q.index for q in query_samples]\n query_id = [q.id for q in query_samples]\n if len(query_samples) < self.max_batchsize:\n data, label = self.ds.get_samples(idx)\n self.run_one_item(Item(query_id, idx, data, label))\n else:\n bs = self.max_batchsize\n for i in range(0, len(idx), bs):\n data, label = self.ds.get_samples(idx[i:i+bs])\n self.run_one_item(Item(query_id[i:i+bs], idx[i:i+bs], data, label))\n\n def finish(self):\n pass\n\n\nclass QueueRunner(RunnerBase):\n def __init__(self, model, ds, threads, post_proc=None, max_batchsize=128):\n super().__init__(model, ds, threads, post_proc, max_batchsize)\n self.tasks = Queue(maxsize=threads * 4)\n self.workers = []\n self.result_dict = {}\n\n for _ in range(self.threads):\n worker = threading.Thread(target=self.handle_tasks, args=(self.tasks,))\n worker.daemon = True\n self.workers.append(worker)\n worker.start()\n\n def handle_tasks(self, tasks_queue):\n \"\"\"Worker thread.\"\"\"\n while True:\n qitem = tasks_queue.get()\n if qitem is None:\n # None in the queue indicates the parent want us to exit\n tasks_queue.task_done()\n break\n self.run_one_item(qitem)\n tasks_queue.task_done()\n\n def enqueue(self, query_samples):\n idx = [q.index for q in query_samples]\n query_id = [q.id for q in query_samples]\n if len(query_samples) < self.max_batchsize:\n data, label = self.ds.get_samples(idx)\n self.tasks.put(Item(query_id, idx, data, label))\n else:\n bs = self.max_batchsize\n for i in range(0, len(idx), bs):\n ie = i + bs\n data, label = self.ds.get_samples(idx[i:ie])\n self.tasks.put(Item(query_id[i:ie], idx[i:ie], data, label))\n\n def finish(self):\n # exit all threads\n for _ in self.workers:\n self.tasks.put(None)\n for worker in self.workers:\n worker.join()\n\n\ndef add_results(final_results, name, result_dict, result_list, took, show_accuracy=False):\n percentiles = [50., 80., 90., 95., 99., 99.9]\n buckets = np.percentile(result_list, percentiles).tolist()\n buckets_str = \",\".join([\"{}:{:.4f}\".format(p, b) for p, b in zip(percentiles, buckets)])\n\n if result_dict[\"total\"] == 0:\n result_dict[\"total\"] = len(result_list)\n\n # this is what we record for each run\n result = {\n \"took\": took,\n \"mean\": np.mean(result_list),\n \"percentiles\": {str(k): v for k, v in zip(percentiles, buckets)},\n \"qps\": len(result_list) / took,\n \"count\": len(result_list),\n \"good_items\": result_dict[\"good\"],\n \"total_items\": result_dict[\"total\"],\n }\n acc_str = \"\"\n if show_accuracy:\n result[\"accuracy\"] = 100. * result_dict[\"good\"] / result_dict[\"total\"]\n acc_str = \", acc={:.3f}%\".format(result[\"accuracy\"])\n if \"mAP\" in result_dict:\n result[\"mAP\"] = 100. * result_dict[\"mAP\"]\n acc_str += \", mAP={:.3f}%\".format(result[\"mAP\"])\n\n # add the result to the result dict\n final_results[name] = result\n\n # to stdout\n print(\"{} qps={:.2f}, mean={:.4f}, time={:.3f}{}, queries={}, tiles={}\".format(\n name, result[\"qps\"], result[\"mean\"], took, acc_str,\n len(result_list), buckets_str))\n return result[\"mAP\"]\n\n\ndef main():\n global last_timeing\n args = get_args()\n\n log.info(args)\n\n # find backend\n backend = get_backend(args.backend)\n\n # override image format if given\n image_format = args.data_format if args.data_format else backend.image_format()\n\n # --count applies to accuracy mode only and can be used to limit the number of images\n # for testing. For perf model we always limit count to 200.\n count_override = False\n count = args.count\n if count:\n count_override = True\n\n # dataset to use\n wanted_dataset, pre_proc, post_proc, kwargs = SUPPORTED_DATASETS[args.dataset]\n ds = wanted_dataset(data_path=args.dataset_path,\n image_list=args.dataset_list,\n name=args.dataset,\n image_format=image_format,\n pre_process=pre_proc,\n use_cache=args.cache,\n count=count, **kwargs)\n # load model to backend\n model = backend.load(args.model, inputs=args.inputs, outputs=args.outputs)\n final_results = {\n \"runtime\": model.name(),\n \"version\": model.version(),\n \"time\": int(time.time()),\n \"cmdline\": str(args),\n }\n\n mlperf_conf = os.path.abspath(args.mlperf_conf)\n if not os.path.exists(mlperf_conf):\n log.error(\"{} not found\".format(mlperf_conf))\n sys.exit(1)\n\n user_conf = os.path.abspath(args.user_conf)\n if not os.path.exists(user_conf):\n log.error(\"{} not found\".format(user_conf))\n sys.exit(1)\n\n if args.output:\n output_dir = os.path.abspath(args.output)\n os.makedirs(output_dir, exist_ok=True)\n os.chdir(output_dir)\n\n #\n # make one pass over the dataset to validate accuracy\n #\n count = ds.get_item_count()\n\n # warmup\n ds.load_query_samples([0])\n for _ in range(5):\n img, _ = ds.get_samples([0])\n _ = backend.predict({backend.inputs[0]: img})\n ds.unload_query_samples(None)\n\n scenario = SCENARIO_MAP[args.scenario]\n runner_map = {\n lg.TestScenario.SingleStream: RunnerBase,\n lg.TestScenario.MultiStream: QueueRunner,\n lg.TestScenario.Server: QueueRunner,\n lg.TestScenario.Offline: QueueRunner\n }\n runner = runner_map[scenario](model, ds, args.threads, post_proc=post_proc, \\\n max_batchsize=args.max_batchsize)\n\n def issue_queries(query_samples):\n runner.enqueue(query_samples)\n\n def flush_queries():\n pass\n\n def process_latencies(latencies_ns):\n # called by loadgen to show us the recorded latencies\n global last_timeing\n last_timeing = [t / NANO_SEC for t in latencies_ns]\n\n log_output_settings = lg.LogOutputSettings()\n log_output_settings.outdir = output_dir\n log_output_settings.copy_summary_to_stdout = False\n log_settings = lg.LogSettings()\n log_settings.enable_trace = args.debug\n log_settings.log_output = log_output_settings\n\n settings = lg.TestSettings()\n settings.FromConfig(mlperf_conf, args.model_name, args.scenario)\n settings.FromConfig(user_conf, args.model_name, args.scenario)\n settings.scenario = scenario\n settings.mode = lg.TestMode.PerformanceOnly\n if args.accuracy:\n settings.mode = lg.TestMode.AccuracyOnly\n if args.benchmark:\n settings.mode = lg.TestMode.PerformanceOnly\n if args.find_peak_performance:\n settings.mode = lg.TestMode.FindPeakPerformance\n\n if args.time:\n # override the time we want to run\n settings.min_duration_ms = args.time * MILLI_SEC\n settings.max_duration_ms = args.time * MILLI_SEC\n\n if args.qps:\n qps = float(args.qps)\n settings.server_target_qps = qps\n settings.offline_expected_qps = qps\n\n if count_override:\n settings.min_query_count = count\n settings.max_query_count = count\n\n if args.samples_per_query:\n settings.multi_stream_samples_per_query = args.samples_per_query\n if args.max_latency:\n settings.server_target_latency_ns = int(args.max_latency * NANO_SEC)\n settings.multi_stream_target_latency_ns = int(args.max_latency * NANO_SEC)\n\n sut = lg.ConstructSUT(issue_queries, flush_queries, process_latencies)\n qsl = lg.ConstructQSL(count, min(count, 500), ds.load_query_samples, ds.unload_query_samples)\n\n log.info(\"starting {}\".format(scenario))\n result_dict = {\"good\": 0, \"total\": 0, \"scenario\": str(scenario)}\n runner.start_run(result_dict, args.accuracy)\n\n raw_model = runner.model.model\n pattern = ['samples_per_query : \\d+', 'Mean latency.*']\n\n def eval_func(model):\n global last_timeing\n runner.model.model = model\n lg.StartTestWithLogSettings(sut, qsl, settings, log_settings)\n if not last_timeing:\n last_timeing = runner.result_timing\n post_proc.finalize(result_dict, ds, output_dir=args.output)\n accu = add_results(final_results, \"{}\".format(scenario),\n result_dict, last_timeing, time.time() - ds.last_loaded, args.accuracy)\n print('Accuracy: %.3f ' % (accu))\n return accu\n\n def benchmark(model):\n global last_timeing\n runner.model.model = model\n lg.StartTestWithLogSettings(sut, qsl, settings, log_settings)\n if not last_timeing:\n last_timeing = runner.result_timing\n file_path = os.path.join(args.output, 'mlperf_log_summary.txt')\n f = open(file_path, 'r', encoding='UTF-8')\n file_content = f.read()\n f.close()\n regex_batch = re.compile(pattern[0])\n regex_late = re.compile(pattern[1])\n samples_per_query = int(regex_batch.findall(file_content)[0].split(': ')[1])\n latency_per_sample = int(regex_late.findall(file_content)[0].split(': ')[1])\n print('Batch size = %d' % samples_per_query)\n print('Latency: %.3f ms' % (latency_per_sample / 10**6))\n print('Throughput: %.3f samples/sec' % (10**9/latency_per_sample))\n\n os.chdir(os.path.join(sys.path[0], \"..\"))\n if args.tune:\n # Quantization with Neural Compressor\n from neural_compressor.experimental import Quantization, common\n quantizer = Quantization(\"./conf.yaml\")\n quantizer.model = common.Model(raw_model)\n quantizer.eval_func = eval_func\n q_model = quantizer()\n q_model.save(args.tuned_checkpoint)\n\n elif args.int8:\n from neural_compressor.utils.pytorch import load\n int8_model = load(os.path.abspath(os.path.expanduser(args.tuned_checkpoint)), raw_model)\n if args.accuracy:\n eval_func(int8_model)\n elif args.benchmark:\n benchmark(int8_model)\n else:\n if args.accuracy:\n eval_func(raw_model)\n elif args.benchmark:\n benchmark(raw_model)\n\n runner.finish()\n lg.DestroyQSL(qsl)\n lg.DestroySUT(sut)\n\n #\n # write final results\n #\n if args.output:\n with open(\"results.json\", \"w\") as f:\n json.dump(final_results, f, sort_keys=True, indent=4)\n\n\nif __name__ == \"__main__\":\n main()\n", "import os\r\nimport unittest\r\nimport yaml\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport shutil\r\nfrom tensorflow.python.framework import graph_util\r\nfrom neural_compressor.adaptor.tensorflow import TensorFlowAdaptor\r\nfrom neural_compressor.adaptor.tf_utils.util import disable_random\r\n\r\ndef build_fake_yaml():\r\n fake_yaml = '''\r\n model:\r\n name: fake_yaml\r\n framework: tensorflow\r\n inputs: input\r\n outputs: op_to_store\r\n device: cpu\r\n evaluation:\r\n accuracy:\r\n metric:\r\n topk: 1\r\n tuning:\r\n accuracy_criterion:\r\n relative: 0.0001\r\n workspace:\r\n path: saved\r\n '''\r\n y = yaml.load(fake_yaml, Loader=yaml.SafeLoader)\r\n with open('fake_yaml.yaml', \"w\", encoding=\"utf-8\") as f:\r\n yaml.dump(y, f)\r\n f.close()\r\nclass TestSetTensor(unittest.TestCase):\r\n @classmethod\r\n def setUpClass(self):\r\n build_fake_yaml()\r\n\r\n @classmethod\r\n def tearDownClass(self):\r\n os.remove('fake_yaml.yaml')\r\n shutil.rmtree('./saved', ignore_errors=True)\r\n \r\n @disable_random()\r\n def test_fp32bias(self):\r\n x = tf.compat.v1.placeholder(tf.float32, [1, 56, 56, 16], name=\"input\")\r\n paddings = tf.constant([[0, 0], [1, 1], [1, 1], [0, 0]])\r\n x_pad = tf.pad(x, paddings, \"CONSTANT\")\r\n conv_weights = tf.compat.v1.get_variable(\"weight\", [3, 3, 16, 16],\r\n initializer=tf.compat.v1.random_normal_initializer())\r\n conv = tf.nn.conv2d(x_pad, conv_weights, strides=[1, 2, 2, 1], padding=\"VALID\")\r\n\r\n conv_bias = tf.compat.v1.get_variable(\"bias\", [16], dtype=tf.float32,\r\n initializer=tf.compat.v1.random_normal_initializer())\r\n\r\n conv_bias = tf.math.add(conv, conv_bias)\r\n relu6 = tf.nn.relu6(conv_bias, name='op_to_store')\r\n\r\n out_name = relu6.name.split(':')[0]\r\n with tf.compat.v1.Session() as sess:\r\n sess.run(tf.compat.v1.global_variables_initializer())\r\n constant_graph = graph_util.convert_variables_to_constants(\r\n sess=sess,\r\n input_graph_def=sess.graph_def,\r\n output_node_names=[out_name])\r\n\r\n from neural_compressor.experimental import Quantization, common\r\n quantizer = Quantization(\"./fake_yaml.yaml\")\r\n dataset = quantizer.dataset('dummy', shape=(100, 56, 56, 16), label=True)\r\n quantizer.calib_dataloader = common.DataLoader(dataset)\r\n quantizer.model = constant_graph\r\n q_model = quantizer()\r\n \r\n framework_specific_info = {'device': 'cpu', 'workspace_path': 'saved',\\\r\n 'random_seed': 1978, 'inputs': ['input'], 'outputs': ['op_to_store'], \\\r\n 'approach': 'post_training_static_quant'}\r\n adaptor = TensorFlowAdaptor(framework_specific_info)\r\n adaptor.set_tensor(q_model, {'bias': np.random.random(16)})\r\n\r\n from tensorflow.core.framework import attr_value_pb2\r\n from tensorflow.python.framework import dtypes\r\n for node in q_model.graph_def.node:\r\n if node.name == 'bias':\r\n self.assertEqual(node.attr['dtype'], attr_value_pb2.AttrValue(\r\n type=dtypes.float32.as_datatype_enum))\r\n\r\n @disable_random()\r\n def test_int32bias(self):\r\n x = tf.compat.v1.placeholder(tf.float32, [1, 56, 56, 16], name=\"input\")\r\n paddings = tf.constant([[0, 0], [1, 1], [1, 1], [0, 0]])\r\n x_pad = tf.pad(x, paddings, \"CONSTANT\")\r\n conv_weights = tf.compat.v1.get_variable(\"weight\", [3, 3, 16, 16],\r\n initializer=tf.compat.v1.random_normal_initializer())\r\n conv = tf.nn.conv2d(x_pad, conv_weights, strides=[1, 2, 2, 1], padding=\"VALID\")\r\n\r\n conv_bias = tf.compat.v1.get_variable(\"bias\", [16], dtype=tf.float32)\r\n\r\n conv_bias = tf.math.add(conv, conv_bias)\r\n relu6 = tf.nn.relu6(conv_bias, name='relu_0')\r\n\r\n conv_weights1 = tf.compat.v1.get_variable(\"weight1\", [3, 3, 16, 16],\r\n initializer=tf.compat.v1.random_normal_initializer())\r\n conv1 = tf.nn.conv2d(relu6, conv_weights1, strides=[1, 2, 2, 1], padding=\"VALID\")\r\n\r\n conv_bias1 = tf.compat.v1.get_variable(\"bias1\", [16], dtype=tf.float32)\r\n\r\n conv_bias1 = tf.math.add(conv1, conv_bias1)\r\n relu6 = tf.nn.relu6(conv_bias1, name='relu_1')\r\n\r\n conv_weights2 = tf.compat.v1.get_variable(\"weight2\", [3, 3, 16, 16],\r\n initializer=tf.compat.v1.random_normal_initializer())\r\n conv2 = tf.nn.conv2d(relu6, conv_weights2, strides=[1, 2, 2, 1], padding=\"VALID\")\r\n\r\n conv_bias2 = tf.compat.v1.get_variable(\"bias2\", [16], dtype=tf.float32)\r\n\r\n conv_bias2 = tf.math.add(conv2, conv_bias2)\r\n relu6 = tf.nn.relu6(conv_bias2, name='op_to_store')\r\n out_name = relu6.name.split(':')[0]\r\n with tf.compat.v1.Session() as sess:\r\n sess.run(tf.compat.v1.global_variables_initializer())\r\n constant_graph = graph_util.convert_variables_to_constants(\r\n sess=sess,\r\n input_graph_def=sess.graph_def,\r\n output_node_names=[out_name])\r\n\r\n for i in constant_graph.node:\r\n if i.op.find('Add') != -1:\r\n i.op = 'Add'\r\n\r\n from neural_compressor.experimental import Quantization, common\r\n quantizer = Quantization(\"./fake_yaml.yaml\")\r\n dataset = quantizer.dataset('dummy', shape=(100, 56, 56, 16), label=True)\r\n quantizer.calib_dataloader = common.DataLoader(dataset)\r\n quantizer.model = constant_graph\r\n q_model = quantizer()\r\n\r\n framework_specific_info = {'device': 'cpu', 'workspace_path': 'saved',\\\r\n 'random_seed': 1978, 'inputs': ['input'], 'outputs': ['op_to_store'], \\\r\n 'approach': 'post_training_static_quant'}\r\n adaptor = TensorFlowAdaptor(framework_specific_info)\r\n adaptor.set_tensor(q_model, {'bias1': np.random.randint(6,size=2, dtype='int32')})\r\n from tensorflow.core.framework import attr_value_pb2\r\n from tensorflow.python.framework import dtypes\r\n for node in q_model.graph_def.node:\r\n if node.name == 'bias2':\r\n self.assertEqual(node.attr['dtype'], attr_value_pb2.AttrValue(\r\n type=dtypes.qint32.as_datatype_enum))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main()\n", "# coding=utf-8\n# Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved.\n# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport csv\nimport tokenization\nimport numpy as np\n\n\n#flags = tf.flags\n#FLAGS = flags.FLAGS\n\nF_max_seq_length = 128\n\n\nclass TF_BERTDataSet():\n \"\"\"\n feature params:\n self.unique_id = unique_id\n self.example_index = example_index\n self.doc_span_index = doc_span_index\n self.tokens = tokens\n self.token_to_orig_map = token_to_orig_map\n self.token_is_max_context = token_is_max_context\n self.input_ids = input_ids #id 6\n self.input_mask = input_mask # id7\n self.segment_ids = segment_ids # id 8\n self.start_position = start_position\n self.end_position = end_position\n self.is_impossible = is_impossible\n\n \"\"\"\n def __init__(self, data_dir, vocab_file, do_lower_case):\n tokenizer = tokenization.FullTokenizer(vocab_file=vocab_file,\n do_lower_case=do_lower_case)\n eval_examples = get_dev_examples(data_dir)\n self.input_ids, self.input_mask, self.segment_ids, self.labels = \\\n convert_examples_to_features(\n examples=eval_examples,\n label_list=[\"0\", \"1\"],\n max_seq_length=F_max_seq_length,\n tokenizer=tokenizer)\n \n def __getitem__(self, idx):\n input_ids_data = self.input_ids[idx]\n input_mask_data = self.input_mask[idx]\n segment_ids_data = self.segment_ids[idx]\n if len(input_ids_data) < F_max_seq_length:\n input_ids_data += [0] * (F_max_seq_length - len(input_ids_data))\n input_mask_data += [0] * (F_max_seq_length - len(input_mask_data))\n segment_ids_data += [0] * (F_max_seq_length - len(segment_ids_data))\n return (np.array(input_ids_data).astype('int32'), \n np.array(segment_ids_data).astype('int32'), \n np.array(input_mask_data).astype('int32')), self.labels[idx]\n\n def __len__(self):\n return len(self.input_ids)\n\n### BERTDataset ###\nclass InputExample(object):\n \"\"\"A single training/test example for simple sequence classification.\"\"\"\n def __init__(self, guid, text_a, text_b=None, label=None):\n \"\"\"Constructs a InputExample.\n\n Args:\n guid: Unique id for the example.\n text_a: string. The untokenized text of the first sequence. For single\n sequence tasks, only this sequence must be specified.\n text_b: (Optional) string. The untokenized text of the second sequence.\n Only must be specified for sequence pair tasks.\n label: (Optional) string. The label of the example. This should be\n specified for train and dev examples, but not for test examples.\n \"\"\"\n self.guid = guid\n self.text_a = text_a\n self.text_b = text_b\n self.label = label\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n def __init__(self,\n input_ids,\n input_mask,\n segment_ids,\n label_id,\n is_real_example=True):\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.label_id = label_id\n self.is_real_example = is_real_example\n\n\ndef _read_tsv(input_file, quotechar=None):\n \"\"\"Reads a tab separated value file.\"\"\"\n with open(input_file, \"r\") as f:\n reader = csv.reader(f, delimiter=\"\\t\", quotechar=quotechar)\n lines = []\n for line in reader:\n lines.append(line)\n return lines\n\n\ndef _create_examples(lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, i)\n text_a = tokenization.convert_to_unicode(line[3])\n text_b = tokenization.convert_to_unicode(line[4])\n if set_type == \"test\":\n label = \"0\"\n else:\n label = tokenization.convert_to_unicode(line[0])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\ndef get_dev_examples(data_dir):\n \"\"\"See base class.\"\"\"\n return _create_examples(_read_tsv(os.path.join(data_dir, \"dev.tsv\")),\n \"dev\")\n\n\ndef _truncate_seq_pair(tokens_a, tokens_b, max_length):\n \"\"\"Truncates a sequence pair in place to the maximum length.\"\"\"\n\n # This is a simple heuristic which will always truncate the longer sequence\n # one token at a time. This makes more sense than truncating an equal percent\n # of tokens from each, since if one sequence is very short then each token\n # that's truncated likely contains more information than a longer sequence.\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_length:\n break\n if len(tokens_a) > len(tokens_b):\n tokens_a.pop()\n else:\n tokens_b.pop()\n\n\ndef convert_single_example(example, label_list, max_seq_length, tokenizer):\n \"\"\"Converts a single `InputExample` into a single `InputFeatures`.\"\"\"\n\n label_map = {}\n for (i, label) in enumerate(label_list):\n label_map[label] = i\n\n tokens_a = tokenizer.tokenize(example.text_a)\n tokens_b = None\n if example.text_b:\n tokens_b = tokenizer.tokenize(example.text_b)\n\n if tokens_b:\n # Modifies `tokens_a` and `tokens_b` in place so that the total\n # length is less than the specified length.\n # Account for [CLS], [SEP], [SEP] with \"- 3\"\n _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\n else:\n # Account for [CLS] and [SEP] with \"- 2\"\n if len(tokens_a) > max_seq_length - 2:\n tokens_a = tokens_a[0:(max_seq_length - 2)]\n\n # The convention in BERT is:\n # (a) For sequence pairs:\n # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n # (b) For single sequences:\n # tokens: [CLS] the dog is hairy . [SEP]\n # type_ids: 0 0 0 0 0 0 0\n #\n # Where \"type_ids\" are used to indicate whether this is the first\n # sequence or the second sequence. The embedding vectors for `type=0` and\n # `type=1` were learned during pre-training and are added to the wordpiece\n # embedding vector (and position vector). This is not *strictly* necessary\n # since the [SEP] token unambiguously separates the sequences, but it makes\n # it easier for the model to learn the concept of sequences.\n #\n # For classification tasks, the first vector (corresponding to [CLS]) is\n # used as the \"sentence vector\". Note that this only makes sense because\n # the entire model is fine-tuned.\n tokens = []\n segment_ids = []\n tokens.append(\"[CLS]\")\n segment_ids.append(0)\n for token in tokens_a:\n tokens.append(token)\n segment_ids.append(0)\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n\n if tokens_b:\n for token in tokens_b:\n tokens.append(token)\n segment_ids.append(1)\n tokens.append(\"[SEP]\")\n segment_ids.append(1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n while len(input_ids) < max_seq_length:\n input_ids.append(0)\n input_mask.append(0)\n segment_ids.append(0)\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n\n label_id = label_map[example.label]\n feature = InputFeatures(input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_id=label_id,\n is_real_example=True)\n return feature\n\n\ndef convert_examples_to_features(examples, label_list, max_seq_length,\n tokenizer):\n \"\"\"Convert a set of `InputExample`s to numpy array.\"\"\"\n input_ids_list = []\n input_mask_list = []\n segment_ids_list = []\n labels = []\n\n for example in examples:\n feature = convert_single_example(example, label_list, max_seq_length,\n tokenizer)\n input_ids_list.append(feature.input_ids)\n input_mask_list.append(feature.input_mask)\n segment_ids_list.append(feature.segment_ids)\n labels.append(feature.label_id)\n\n return np.array(input_ids_list, dtype=\"int32\"), \\\n np.array(input_mask_list, dtype=\"int32\"), \\\n np.array(segment_ids_list, dtype=\"int32\"), \\\n np.array(labels, dtype=\"int32\")\n", "#\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2021 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport numpy as np\n\ndef collate_preds(results):\n batch = results[0]\n if isinstance(batch, list):\n results = zip(*results)\n collate_results = []\n for output in results:\n collate_results.append(np.concatenate(output))\n elif isinstance(batch, dict):\n results = list(batch.values())[:len(list(batch.values()))]\n collate_results = []\n for output in results:\n collate_results.append(np.concatenate(output))\n elif isinstance(batch, np.ndarray):\n collate_results = np.concatenate(results)\n else:\n collate_results = results\n return collate_results\n", "#\n# -*- coding: utf-8 -*-\n#\nimport unittest\nimport tensorflow as tf\nfrom tensorflow.core.framework import graph_pb2\nfrom tensorflow.python.framework import dtypes\n\nfrom neural_compressor.adaptor.tf_utils.quantize_graph.quantize_graph_common import QuantizeGraphHelper\n\nfrom neural_compressor.adaptor.tf_utils.graph_rewriter.generic.graph_cse_optimizer import GraphCseOptimizer\nfrom neural_compressor.adaptor.tf_utils.util import disable_random\n\n\nclass TestGraphCommonSequenceElimated(unittest.TestCase):\n @disable_random()\n def test_graph_cse(self):\n\n input_constant_name = \"input_constant\"\n relu_name = \"relu\"\n float_graph_def = graph_pb2.GraphDef()\n input_constant = QuantizeGraphHelper.create_constant_node(\n input_constant_name,\n value=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],\n dtype=dtypes.float32,\n shape=[1, 2, 6, 1])\n float_graph_def.node.extend([input_constant])\n relu_node = QuantizeGraphHelper.create_node(\"Relu\", relu_name,\n [input_constant_name])\n QuantizeGraphHelper.set_attr_dtype(relu_node, \"T\", dtypes.float32)\n float_graph_def.node.extend([relu_node])\n\n b_constant_name = \"b_constant\"\n mat_mul_name = \"mat_mul\"\n identity_name = \"identity\"\n b_constant = QuantizeGraphHelper.create_constant_node(\n b_constant_name, value=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], dtype=dtypes.float32, shape=[2, 6])\n float_graph_def.node.extend([b_constant])\n\n mat_mul_node = QuantizeGraphHelper.create_node(\"MatMul\", mat_mul_name,\n [relu_name, b_constant_name])\n QuantizeGraphHelper.set_attr_dtype(mat_mul_node, \"T\", dtypes.float32)\n QuantizeGraphHelper.set_attr_bool(mat_mul_node, \"transpose_a\", False)\n QuantizeGraphHelper.set_attr_bool(mat_mul_node, \"transpose_b\", False)\n float_graph_def.node.extend([mat_mul_node])\n\n identity_node = QuantizeGraphHelper.create_node(\"Identity\", identity_name,\n [mat_mul_name])\n float_graph_def.node.extend([identity_node])\n\n bias_add_name = \"bias_add\"\n offset_constant_name = \"offset_constant\"\n\n offset_constant = QuantizeGraphHelper.create_constant_node(\n offset_constant_name,\n value=[1, 2, 3, 4, 5, 6],\n dtype=dtypes.float32,\n shape=[6])\n float_graph_def.node.extend([offset_constant])\n bias_add_node = QuantizeGraphHelper.create_node(\n \"BiasAdd\", bias_add_name, [identity_name, offset_constant_name])\n QuantizeGraphHelper.set_attr_dtype(bias_add_node, \"T\", dtypes.float32)\n float_graph_def.node.extend([bias_add_node])\n\n post_relu_name = \"post_relu\"\n post_relu_node = QuantizeGraphHelper.create_node(\"Relu\", post_relu_name,\n [bias_add_name])\n float_graph_def.node.extend([post_relu_node])\n\n last_identity_node_name = 'last_identity'\n last_identity_node = QuantizeGraphHelper.create_node(\"Identity\", last_identity_node_name,\n [post_relu_name])\n float_graph_def.node.extend([last_identity_node])\n\n left_relu_name = \"final_left_relu\"\n left_relu_node = QuantizeGraphHelper.create_node(\"Relu\", left_relu_name,\n [last_identity_node_name])\n float_graph_def.node.extend([left_relu_node])\n right_relu_name = \"final_right_relu\"\n right_relu_node = QuantizeGraphHelper.create_node(\"Relu\", right_relu_name,\n [last_identity_node_name])\n float_graph_def.node.extend([right_relu_node])\n\n cse_left_node_name = \"cse_left_node\"\n cse_left_node = QuantizeGraphHelper.create_node(\"Identity\", cse_left_node_name,\n [left_relu_name])\n float_graph_def.node.extend([cse_left_node])\n\n cse_right_node_name = \"cse_right_node\"\n cse_right_node = QuantizeGraphHelper.create_node(\"Identity\", cse_right_node_name,\n [right_relu_name])\n float_graph_def.node.extend([cse_right_node])\n\n # post_graph = QuantizeGraphHelper().graph_cse_optimization (\n # float_graph_def)\n post_graph = GraphCseOptimizer(float_graph_def).do_transformation()\n\n right_relu_optimized_flag = True\n for i in post_graph.node:\n if i.name == right_relu_name:\n right_relu_optimized_flag = False\n break\n\n self.assertEqual(right_relu_optimized_flag, True)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "import os\nimport shutil\nimport sys\nimport unittest\nimport numpy as np\nimport onnx\nfrom onnx import helper, TensorProto, numpy_helper\n\n\nsys.path.append('..')\nfrom neural_compressor.experimental.data.datasets.dataset import Dataset\nfrom neural_compressor.adaptor.ox_utils.onnxrt_mid import ONNXRTAugment\nfrom neural_compressor.model.onnx_model import ONNXModel\nfrom neural_compressor.data import DATASETS, DATALOADERS\n\ndef generate_input_initializer(tensor_shape, tensor_dtype, input_name):\n '''\n Helper function to generate initializers for test inputs\n '''\n tensor = np.random.ranf(tensor_shape).astype(tensor_dtype)\n init = numpy_helper.from_array(tensor, input_name)\n return init \n\ndef create_cv_session():\n A = helper.make_tensor_value_info('A', TensorProto.FLOAT, [1, 1, 5, 5])\n B = helper.make_tensor_value_info('B', TensorProto.FLOAT, [1, 1, 3, 3])\n b_value = np.random.randn(1, 1, 3, 3).astype(np.float32)\n B_init = helper.make_tensor('B', TensorProto.FLOAT, [1, 1, 3, 3],\n b_value.reshape(9).tolist())\n D = helper.make_tensor_value_info('D', TensorProto.FLOAT, [1, 1, 5, 5])\n conv_node = onnx.helper.make_node('Conv', ['A', 'B'], ['C'],\n name='conv',\n kernel_shape=[3, 3],\n pads=[1, 1, 1, 1])\n relu_node = onnx.helper.make_node('Relu', ['C'], ['D'], name='relu')\n graph = helper.make_graph([conv_node, relu_node], 'test_graph_1', [A, B], [D], [B_init])\n model = helper.make_model(graph, **{'opset_imports': [helper.make_opsetid('', 13)]})\n\n dataset = TestDataset2()\n dataloader = DATALOADERS['onnxrt_qlinearops'](dataset)\n return model, dataloader\n\ndef create_nlp_session():\n a_value = np.random.randn(100, 4).astype(np.float32)\n A_init = helper.make_tensor('A', TensorProto.FLOAT, [100, 4],\n a_value.reshape(400).tolist())\n b_value = np.random.randint(2, size=(10)).astype(np.int32)\n B_init = helper.make_tensor('B', TensorProto.INT32, [10],\n b_value.reshape(10).tolist())\n A = helper.make_tensor_value_info('A', TensorProto.FLOAT, [1, 100, 4])\n D = helper.make_tensor_value_info('D', TensorProto.FLOAT, [100, 4])\n squeeze = onnx.helper.make_node('Squeeze', ['A'], ['D'], name='squeeze')\n B = helper.make_tensor_value_info('B', TensorProto.INT32, [10])\n C = helper.make_tensor_value_info('C', TensorProto.FLOAT, [10, 4])\n node = onnx.helper.make_node('Gather', ['D', 'B'], ['C'], name='gather')\n graph = helper.make_graph([squeeze, node], 'test_graph_1', [A], [C], [B_init])\n model = helper.make_model(graph, **{'opset_imports': [helper.make_opsetid('', 13)]})\n datasets = DATASETS('onnxrt_qlinearops')\n dataset = datasets['dummy_v2'](input_shape=(100, 4), label_shape=(1,))\n \n dataloader = DATALOADERS['onnxrt_qlinearops'](dataset)\n return model, dataloader \n\nclass TestDataset(Dataset):\n \"\"\"Configuration for Imagenet dataset.\"\"\"\n\n def __init__(self):\n data_list = []\n data_list.append((np.array([[[[0.45,0.60,0.75]],\n [[0.25,0.50,0.75]],\n [[0.90,0.70,0.50]]]]).astype(np.float32), 0))\n data_list.append((np.array([[[[0.62,0.94,0.38]],\n [[0.70,0.13,0.07]],\n [[0.89,0.75,0.84]]]]).astype(np.float32), 0))\n data_list.append((np.array([[[[0.64,0.24,0.97]],\n [[0.82,0.58,0.27]],\n [[0.019,0.34,0.02]]]]).astype(np.float32), 0))\n self.data_list = data_list\n \n def __len__(self):\n return len(self.data_list)\n\n def __getitem__(self, index):\n data = self.data_list[index]\n return data\n\nclass TestDataset2(Dataset):\n \"\"\"Configuration for Imagenet dataset.\"\"\"\n\n def __init__(self):\n data_list = []\n data_list.append(np.random.random([1,5,5]).astype(np.float32))\n data_list.append(np.random.random([1,5,5]).astype(np.float32))\n data_list.append(np.random.random([1,5,5]).astype(np.float32))\n self.data_list = data_list\n\n def __len__(self):\n return len(self.data_list)\n\n def __getitem__(self, index):\n data = self.data_list[index]\n return data, 0\n\nclass TestAugment(unittest.TestCase):\n\n work_space = './onnxrt_calib_test' \n augment_path = \"./onnxrt_calib_test/aug.onnx\"\n \n @classmethod\n def setUpClass(cls):\n os.makedirs(cls.work_space)\n cls.cv_session = create_cv_session()\n cls.nlp_session = create_nlp_session()\n\n @classmethod\n def tearDownClass(cls):\n shutil.rmtree(cls.work_space, ignore_errors=True)\n\n def test_dump_tensor(self):\n model, dataloader = self.cv_session\n augment = ONNXRTAugment(ONNXModel(model), \n dataloader, \n [], \n self.augment_path,\n iterations=[0, 1],\n white_nodes=[\"conv\"])\n map_dumped_tensors = augment.dump_tensor()\n assert \"conv\" in map_dumped_tensors[\"activation\"][0]\n assert \"C\" in map_dumped_tensors[\"activation\"][0][\"conv\"]\n assert \"conv\" in map_dumped_tensors[\"activation\"][1]\n assert \"C\" in map_dumped_tensors[\"activation\"][1][\"conv\"]\n\n model, dataloader = self.cv_session\n augment = ONNXRTAugment(ONNXModel(model),\n dataloader,\n [],\n self.augment_path,\n iterations=[0],\n white_nodes=[\"conv\", \"relu\"])\n map_dumped_tensors = augment.dump_tensor(weight=True)\n assert \"conv\" in map_dumped_tensors[\"activation\"][0]\n assert \"relu\" in map_dumped_tensors[\"activation\"][0]\n assert \"conv\" in map_dumped_tensors[\"weight\"]\n\n model, dataloader = self.nlp_session\n augment = ONNXRTAugment(ONNXModel(model), \n dataloader, \n [], \n self.augment_path,\n iterations=[0],\n white_nodes=[\"gather\"])\n map_dumped_tensors = augment.dump_tensor()\n assert \"gather\" in map_dumped_tensors[\"activation\"][0]\n\n def test_dump_calibration(self):\n model, dataloader = self.cv_session\n augment = ONNXRTAugment(ONNXModel(model),\n dataloader, \n [\"Conv\", \"Relu\"],\n self.augment_path,\n iterations=[0])\n calib_params = augment.dump_calibration()\n assert \"A\" in calib_params and \"B\" in calib_params and \"D\" in calib_params and \"C\" in calib_params\n\n def test_augment_graph(self):\n\n ''' TEST_CONFIG_1'''\n\n # Conv \n # | \n # Clip\n # | \n # MatMul\n \n A = helper.make_tensor_value_info('A', TensorProto.FLOAT, [1, 1, 5, 5])\n B = helper.make_tensor_value_info('B', TensorProto.FLOAT, [1, 1, 3, 3])\n E = helper.make_tensor_value_info('E', TensorProto.FLOAT, [1, 1, 5, 1])\n F = helper.make_tensor_value_info('F', TensorProto.FLOAT, [1, 1, 5, 1])\n conv_node = onnx.helper.make_node('Conv', ['A', 'B'], ['C'], name='Conv', kernel_shape=[3, 3], pads=[1, 1, 1, 1])\n clip_node = onnx.helper.make_node('Clip', ['C'], ['D'], name='Clip')\n matmul_node = onnx.helper.make_node('MatMul', ['D', 'E'], ['F'], name='MatMul')\n graph = helper.make_graph([conv_node, clip_node, matmul_node], 'test_graph_1', [A, B, E], [F])\n model = helper.make_model(graph)\n\n # Augmenting graph\n data_reader = None\n augmented_model_path = os.path.join(self.work_space,'./augmented_test_model_1.onnx')\n augment = ONNXRTAugment(ONNXModel(model), data_reader, ['Conv', 'MatMul'], augmented_model_path)\n augment.augment_nodes = [\"ReduceMin\", \"ReduceMax\"]\n augment.augment_graph()\n augmented_model = augment.augmented_model\n onnx.save(augmented_model, augmented_model_path)\n\n # Checking if each added ReduceMin and ReduceMax node and its output exists\n augmented_model_node_names = [node.name for node in augmented_model.graph.node]\n augmented_model_outputs = [output.name for output in augmented_model.graph.output]\n added_node_names = ['A_ReduceMin', 'A_ReduceMax', 'B_ReduceMin', 'B_ReduceMax', 'C_ReduceMin', \\\n 'C_ReduceMax', 'D_ReduceMin', 'D_ReduceMax', 'F_ReduceMin', 'F_ReduceMax']\n added_outputs = ['A_ReduceMin', 'A_ReduceMax', 'B_ReduceMin', 'B_ReduceMax', 'C_ReduceMin', \\\n 'C_ReduceMax', 'D_ReduceMin', 'D_ReduceMax', 'F_ReduceMin', 'F_ReduceMax']\n # Original 3 nodes + added ReduceMin/Max nodes * 6 (exlude graph input/output)\n self.assertEqual(len(augmented_model_node_names), 15)\n # Original 1 graph output + added outputs * 6\n self.assertEqual(len(augmented_model_outputs), 13)\n for name in added_node_names:\n self.assertTrue(name in augmented_model_node_names)\n for output in added_outputs:\n self.assertTrue(output in augmented_model_outputs)\n\n print('Finished TEST_CONFIG_1')\n\n\n '''TEST_CONFIG_2'''\n\n # Conv\n # | \n # Conv\n\n G = helper.make_tensor_value_info('G', TensorProto.FLOAT, [1, 1, 5, 5])\n H = helper.make_tensor_value_info('H', TensorProto.FLOAT, [1, 1, 3, 3])\n J = helper.make_tensor_value_info('J', TensorProto.FLOAT, [1, 1, 3, 3])\n K = helper.make_tensor_value_info('K', TensorProto.FLOAT, [1, 1, 5, 5])\n conv_node_1 = onnx.helper.make_node('Conv', ['G', 'H'], ['I'], name='Conv', kernel_shape=[3, 3], pads=[1, 1, 1, 1])\n conv_node_2 = onnx.helper.make_node('Conv', ['I', 'J'], ['K'], name='Conv', kernel_shape=[3, 3], pads=[1, 1, 1, 1])\n graph = helper.make_graph([conv_node_1, conv_node_2], 'test_graph_2', [G, H, J], [K])\n model = helper.make_model(graph)\n\n # Augmenting graph\n data_reader = None\n augmented_model_path = os.path.join(self.work_space,'./augmented_test_model_2.onnx')\n augment = ONNXRTAugment(ONNXModel(model), data_reader, ['Conv', 'MatMul'], augmented_model_path)\n augment.augment_nodes = [\"ReduceMin\", \"ReduceMax\"]\n augment.augment_graph()\n augmented_model = augment.augmented_model\n onnx.save(augmented_model, augmented_model_path)\n \n\n augmented_model_node_names = [node.name for node in augmented_model.graph.node]\n augmented_model_outputs = [output.name for output in augmented_model.graph.output]\n added_node_names = ['I_ReduceMin', 'I_ReduceMax', 'J_ReduceMin', 'J_ReduceMax', 'H_ReduceMin', 'H_ReduceMax', \\\n 'G_ReduceMin', 'G_ReduceMax', 'K_ReduceMin', 'K_ReduceMax']\n added_outputs = ['I_ReduceMin', 'I_ReduceMax', 'J_ReduceMin', 'J_ReduceMax', 'H_ReduceMin', 'H_ReduceMax',\\\n 'G_ReduceMin', 'G_ReduceMax', 'K_ReduceMin', 'K_ReduceMax']\n # Original 2 nodes + added ReduceMin/Max nodes * 4\n self.assertEqual(len(augmented_model_node_names), 12)\n # Original 1 graph output + added outputs * 4\n self.assertEqual(len(augmented_model_outputs), 11)\n for name in added_node_names:\n self.assertTrue(name in augmented_model_node_names)\n for output in added_outputs:\n self.assertTrue(output in augmented_model_outputs)\n\n print('Finished TEST_CONFIG_2') \n\n\n '''TEST_CONFIG_3'''\n \n # Relu\n # | \n # Conv \\ \n # | |\n # Clip |\n # | /\n # MatMul\n\n L = helper.make_tensor_value_info('L', TensorProto.FLOAT, [1, 1, 5, 5])\n N = helper.make_tensor_value_info('N', TensorProto.FLOAT, [1, 1, 3, 3])\n Q = helper.make_tensor_value_info('Q', TensorProto.FLOAT, [1, 1, 5, 5])\n relu_node = onnx.helper.make_node('Relu', ['L'], ['M'], name='Relu')\n conv_node = onnx.helper.make_node('Conv', ['M', 'N'], ['O'], name='Conv', kernel_shape=[3, 3], pads=[1, 1, 1, 1])\n clip_node = onnx.helper.make_node('Clip', ['O'], ['P'], name='Clip')\n matmul_node = onnx.helper.make_node('MatMul', ['P','M'], ['Q'], name='MatMul')\n graph = helper.make_graph([relu_node, conv_node, clip_node, matmul_node], 'test_graph_3', [L, N], [Q])\n model = helper.make_model(graph)\n\n # Augmenting graph\n data_reader = None\n augmented_model_path = os.path.join(self.work_space,'./augmented_test_model_3.onnx')\n augment = ONNXRTAugment(ONNXModel(model), data_reader, ['Conv', 'MatMul'], augmented_model_path)\n augment.augment_nodes = [\"ReduceMin\", \"ReduceMax\"]\n augment.augment_graph()\n augmented_model = augment.augmented_model\n onnx.save(augmented_model, augmented_model_path)\n\n augmented_model_node_names = [node.name for node in augmented_model.graph.node]\n augmented_model_outputs = [output.name for output in augmented_model.graph.output]\n added_node_names = ['O_ReduceMin', 'O_ReduceMax', 'Q_ReduceMin', 'Q_ReduceMax', 'N_ReduceMin', \\\n 'N_ReduceMax', 'P_ReduceMin', 'P_ReduceMax', 'M_ReduceMin', 'M_ReduceMax']\n added_outputs = ['O_ReduceMin', 'O_ReduceMax', 'Q_ReduceMin', 'Q_ReduceMax', 'N_ReduceMin', \\\n 'N_ReduceMax', 'P_ReduceMin', 'P_ReduceMax', 'M_ReduceMin', 'M_ReduceMax']\n # Original 4 nodes + added ReduceMin/Max nodes * 8\n self.assertEqual(len(augmented_model_node_names), 14)\n # Original 1 graph output + added outputs * 8\n self.assertEqual(len(augmented_model_outputs), 11)\n for name in added_node_names:\n self.assertTrue(name in augmented_model_node_names)\n for output in added_outputs:\n self.assertTrue(output in augmented_model_outputs)\n \n print('Finished TEST_CONFIG_3')\n\n \n '''TEST_CONFIG_4'''\n\n # Attention\n # | \n # MatMul\n\n Attention_weight = helper.make_tensor_value_info('Attention_weight', TensorProto.FLOAT, [13,7 ])\n Attention_bias = helper.make_tensor_value_info('Attention_bias', TensorProto.FLOAT, [13, 7])\n Attention_mask = helper.make_tensor_value_info('Attention_mask', TensorProto.INT32, [13, 7])\n S = helper.make_tensor_value_info('S', TensorProto.FLOAT, [13, 7])\n T = helper.make_tensor_value_info('T', TensorProto.FLOAT, [13, 7])\n attention_node = onnx.helper.make_node('Attention', ['Attention_weight', 'Attention_bias', 'Attention_mask'], ['R'], name='Attention')\n matmul_node = onnx.helper.make_node('MatMul', ['R', 'S'], ['T'], name='MatMul')\n graph = helper.make_graph([attention_node, matmul_node], 'test_graph_4', [Attention_weight, Attention_bias, Attention_mask, S], [T])\n model = helper.make_model(graph)\n\n # Augmenting graph\n data_reader = None\n augmented_model_path = os.path.join(self.work_space,'./augmented_test_model_4.onnx')\n augment = ONNXRTAugment(ONNXModel(model), data_reader, ['Conv', 'MatMul', 'Attention'], augmented_model_path)\n augment.augment_nodes = [\"ReduceMin\", \"ReduceMax\"]\n augment.augment_graph()\n augmented_model = augment.augmented_model\n onnx.save(augmented_model, augmented_model_path)\n\n augmented_model_node_names = [node.name for node in augmented_model.graph.node]\n augmented_model_outputs = [output.name for output in augmented_model.graph.output]\n added_node_names = ['Attention_bias_ReduceMin', 'Attention_bias_ReduceMax', 'Attention_weight_ReduceMin', \\\n 'Attention_weight_ReduceMax', 'S_ReduceMin', 'S_ReduceMax', 'R_ReduceMin', 'R_ReduceMax', 'T_ReduceMin', 'T_ReduceMax']\n added_outputs = ['Attention_bias_ReduceMin', 'Attention_bias_ReduceMax', 'Attention_weight_ReduceMin', \\\n 'Attention_weight_ReduceMax', 'S_ReduceMin', 'S_ReduceMax', 'R_ReduceMin', 'R_ReduceMax', 'T_ReduceMin', 'T_ReduceMax']\n # Original 2 nodes + added ReduceMin/Max nodes * 5\n self.assertEqual(len(augmented_model_node_names), 12)\n # Original 1 graph output + added outputs * 5\n self.assertEqual(len(augmented_model_outputs), 11)\n for name in added_node_names:\n self.assertTrue(name in augmented_model_node_names)\n for output in added_outputs:\n self.assertTrue(output in augmented_model_outputs)\n\n print('Finished TEST_CONFIG_4')\n\n # QAttention\n # |\n # QuantizeLinear\n \n Attention_weight = helper.make_tensor_value_info('weight_quantized', TensorProto.INT8, [13,7])\n weight_quantized = generate_input_initializer([13, 7], np.int8, 'weight_quantized')\n Attention_bias = helper.make_tensor_value_info('bias', TensorProto.FLOAT, [13, 7])\n bias = generate_input_initializer([13, 7], np.float32, 'bias')\n Input_scale = helper.make_tensor_value_info('input_scale', TensorProto.FLOAT, [1])\n input_scale = generate_input_initializer([1], np.float32, 'input_scale')\n Weight_scale = helper.make_tensor_value_info('weight_scale', TensorProto.FLOAT, [1])\n weight_scale = generate_input_initializer([1], np.float32, 'weight_scale')\n Attention_mask = helper.make_tensor_value_info('mask', TensorProto.INT32, [13, 7])\n mask = generate_input_initializer([13, 7], np.int32, 'mask')\n Input_zo = helper.make_tensor_value_info('input_zero_point', TensorProto.INT8, [1])\n input_zero_point = generate_input_initializer([1], np.int8, 'input_zero_point')\n Weight_zo = helper.make_tensor_value_info('weight_zero_point', TensorProto.INT8, [1])\n weight_zero_point = generate_input_initializer([1], np.int8, 'weight_zero_point')\n Q_scale = helper.make_tensor_value_info('attn_output_scale', TensorProto.FLOAT, [1])\n attn_output_scale = generate_input_initializer([1], np.float32, 'attn_output_scale')\n Q_zo = helper.make_tensor_value_info('attn_output_zero_point', TensorProto.INT8, [1])\n attn_output_zero_point = generate_input_initializer([1], np.int8, 'attn_output_zero_point')\n Output = helper.make_tensor_value_info('output', TensorProto.INT8, [13,7])\n attention_node = onnx.helper.make_node('QAttention', ['weight_quantized', \n 'bias', \n 'input_scale',\n 'weight_scale',\n 'mask',\n 'input_zero_point',\n 'weight_zero_point'], \n ['attn_output'], name='attention_quant')\n qlinear_node = onnx.helper.make_node('QuantizeLinear', \n ['attn_output', 'attn_output_scale', 'attn_output_zero_point'], \n ['attn_output_quantized'], \n name='attn_output_QuantizeLinear')\n graph = helper.make_graph([attention_node, qlinear_node], \n 'test_graph_5', \n [Attention_weight, \n Attention_bias, \n Input_scale,\n Weight_scale,\n Attention_mask,\n Input_zo,\n Weight_zo,\n Q_scale,\n Q_zo], \n [Output])\n graph.initializer.add().CopyFrom(weight_quantized)\n graph.initializer.add().CopyFrom(bias)\n graph.initializer.add().CopyFrom(input_scale)\n graph.initializer.add().CopyFrom(weight_scale)\n graph.initializer.add().CopyFrom(mask)\n graph.initializer.add().CopyFrom(input_zero_point)\n graph.initializer.add().CopyFrom(weight_zero_point)\n graph.initializer.add().CopyFrom(attn_output_scale)\n graph.initializer.add().CopyFrom(attn_output_zero_point) \n model = helper.make_model(graph)\n\n # Augmenting graph\n data_reader = None\n augmented_model_path = os.path.join(self.work_space,'./augmented_test_model_5.onnx')\n augment = ONNXRTAugment(ONNXModel(model), data_reader, [], augmented_model_path, white_nodes=['attention'])\n augment.augment_nodes = ['DequantizeLinear']\n augment.already_quantized = True\n augment.augment_graph(activation_only=True, output_only=True)\n augmented_model = augment.augmented_model\n onnx.save(augmented_model, augmented_model_path)\n\n augmented_model_node_names = [node.name for node in augmented_model.graph.node]\n augmented_model_outputs = [output.name for output in augmented_model.graph.output]\n added_outputs = ['attn_output']\n self.assertEqual(len(augmented_model_node_names), 2)\n self.assertEqual(len(augmented_model_outputs), 2)\n for output in added_outputs:\n self.assertTrue(output in augmented_model_outputs)\n\n print('Finished TEST_CONFIG_5')\n\n # QuantizeLinear\n # |\n # QLinearConv\n # |\n # DequantizeLinear\n A = helper.make_tensor_value_info('A', TensorProto.FLOAT, [1, 1, 5, 5])\n A_scale = helper.make_tensor_value_info('A_scale', TensorProto.FLOAT, [1])\n a_scale = generate_input_initializer([1], np.float32, 'A_scale')\n A_zo = helper.make_tensor_value_info('A_zero_point', TensorProto.INT8, [1])\n a_zero_point = generate_input_initializer([1], np.int8, 'A_zero_point')\n B_scale = helper.make_tensor_value_info('B_scale', TensorProto.FLOAT, [1])\n b_scale = generate_input_initializer([1], np.float32, 'B_scale')\n B_zo = helper.make_tensor_value_info('B_zero_point', TensorProto.INT8, [1])\n b_zero_point = generate_input_initializer([1], np.int8, 'B_zero_point')\n C = helper.make_tensor_value_info('C', TensorProto.INT8, [1, 1, 5, 5])\n c = generate_input_initializer([1, 1, 5, 5], np.int8, 'C')\n C_scale = helper.make_tensor_value_info('C_scale', TensorProto.FLOAT, [1])\n c_scale = generate_input_initializer([1], np.float32, 'C_scale')\n C_zo = helper.make_tensor_value_info('C_zero_point', TensorProto.INT8, [1])\n c_zero_point = generate_input_initializer([1], np.int8, 'C_zero_point')\n E = helper.make_tensor_value_info('E', TensorProto.INT32, [1])\n e = generate_input_initializer([1], np.int32, 'E')\n D_scale = helper.make_tensor_value_info('D_scale', TensorProto.FLOAT, [1])\n d_scale = generate_input_initializer([1], np.float32, 'D_scale')\n D_zo = helper.make_tensor_value_info('D_zero_point', TensorProto.INT8, [1])\n d_zero_point = generate_input_initializer([1], np.int8, 'D_zero_point')\n D = helper.make_tensor_value_info('D', TensorProto.FLOAT, [1, 1, 5, 5])\n quantize_node = onnx.helper.make_node('QuantizeLinear', ['A', 'A_scale', 'A_zero_point'], ['B'], name='A_QuantizeLinear')\n conv_node = onnx.helper.make_node('QLinearConv', ['B', 'B_scale', 'B_zero_point', 'C', 'C_scale', 'C_zero_point', 'D_scale', 'D_zero_point', 'E'], ['D_quantized'], name='conv_quant', kernel_shape=[3, 3], pads=[1, 1, 1, 1])\n dequantize_node = onnx.helper.make_node('DequantizeLinear', ['D_quantized', 'D_scale', 'D_zero_point'], ['D'], name='D_DequantizeLinear')\n graph = helper.make_graph([quantize_node, conv_node, dequantize_node], 'test_graph_5', [A, A_scale, A_zo, C, C_scale, C_zo, E, D_scale, D_zo], [D])\n graph.initializer.add().CopyFrom(a_scale)\n graph.initializer.add().CopyFrom(a_zero_point)\n graph.initializer.add().CopyFrom(b_scale)\n graph.initializer.add().CopyFrom(b_zero_point)\n graph.initializer.add().CopyFrom(c)\n graph.initializer.add().CopyFrom(c_scale)\n graph.initializer.add().CopyFrom(c_zero_point)\n graph.initializer.add().CopyFrom(e)\n graph.initializer.add().CopyFrom(d_scale)\n graph.initializer.add().CopyFrom(d_zero_point)\n model = helper.make_model(graph)\n\n # Augmenting graph\n data_reader = None\n augmented_model_path = os.path.join(self.work_space,'./augmented_test_model_6.onnx')\n augment = ONNXRTAugment(ONNXModel(model), data_reader, [], augmented_model_path, white_nodes=['conv'])\n augment.augment_nodes = [\"DequantizeLinear\"]\n augment.already_quantized = True\n augment.augment_graph(activation_only=True, output_only=True)\n augmented_model = augment.augmented_model\n onnx.save(augmented_model, augmented_model_path)\n\n augmented_model_node_names = [node.name for node in augmented_model.graph.node]\n augmented_model_outputs = [output.name for output in augmented_model.graph.output]\n added_node_names = ['D_quantized_DequantizeLinear']\n added_outputs = ['D_quantized_output']\n self.assertEqual(len(augmented_model_node_names), 4)\n self.assertEqual(len(augmented_model_outputs), 2)\n for name in added_node_names:\n self.assertTrue(name in augmented_model_node_names)\n for output in added_outputs:\n self.assertTrue(output in augmented_model_outputs)\n \n def test_quant_param_calculation(self):\n '''TEST_CONFIG_6'''\n \n # Relu \n # | \\ \n # Conv \\\n # | \\ \n # Relu | \n # | Conv \n # Conv / \n # \\ / \n # |\n # Add\n \n input0 = helper.make_tensor_value_info('input0', TensorProto.FLOAT, [1, 3, 1, 3])\n output = helper.make_tensor_value_info('output', TensorProto.FLOAT, [1, 3, 1, 3])\n \n X1_weight = generate_input_initializer([3, 3, 1, 1], np.float32, 'X1_weight')\n X1_bias = generate_input_initializer([3], np.float32, 'X1_bias')\n X3_weight = generate_input_initializer([3, 3, 1, 1], np.float32, 'X3_weight')\n X3_bias = generate_input_initializer([3],np.float32, 'X3_bias')\n X5_weight = generate_input_initializer([3, 3, 1, 1], np.float32, 'X5_weight')\n X5_bias = generate_input_initializer([3],np.float32,'X5_bias')\n \n relu_node_1 = onnx.helper.make_node('Relu', ['input0'], ['X1'], name='Relu1')\n conv_node_1 = onnx.helper.make_node('Conv', ['X1', 'X1_weight', 'X1_bias'], ['X2'], name='Conv1')\n relu_node_2 = onnx.helper.make_node('Relu', ['X2'], ['X3'], name= 'Relu2')\n conv_node_2 = onnx.helper.make_node('Conv', ['X3', 'X3_weight', 'X3_bias'], ['X4'], name='Conv2')\n conv_node_3 = onnx.helper.make_node('Conv', ['X1', 'X5_weight', 'X5_bias'], ['X5'], name='Conv3')\n add_node = onnx.helper.make_node('Add', ['X4', 'X5'], ['output'], name='Add')\n \n graph = helper.make_graph([relu_node_1, conv_node_1, relu_node_2, conv_node_2, conv_node_3, add_node], 'test_graph_5', [input0], [output])\n graph.initializer.add().CopyFrom(X1_weight)\n graph.initializer.add().CopyFrom(X1_bias)\n graph.initializer.add().CopyFrom(X3_weight)\n graph.initializer.add().CopyFrom(X3_bias)\n graph.initializer.add().CopyFrom(X5_weight)\n graph.initializer.add().CopyFrom(X5_bias)\n model = helper.make_model(graph, **{'opset_imports': [helper.make_opsetid('', 13)]})\n data_reader = TestDataset()\n augmented_model_path = os.path.join(self.work_space,'./augmented_test_model_5.onnx')\n augment = ONNXRTAugment(ONNXModel(model), data_reader,['Conv', 'MatMul'], augmented_model_path)\n\n #test calculation of quantization params\n #TO_DO: check rmin/rmax\n quantization_params_dict = augment.dump_calibration()\n node_output_names, output_dicts_list = augment.get_intermediate_outputs()\n dict_for_quantization = augment._map_calibration(node_output_names, output_dicts_list)\n #check the size of the quantization dictionary\n self.assertEqual(len(quantization_params_dict), 11)\n \n #check the computation of zp and scale\n for key, value in quantization_params_dict.items():\n \n self.assertTrue(value is not None)\n self.assertTrue(len(value) == 2)\n \n thresholds = dict_for_quantization[key]\n rmin = min(thresholds[0], 0)\n rmax = max(thresholds[1], 0)\n if key == 'X2': #next_node is Relu\n if rmin < 0: rmin = 0\n \n scale_expected = np.float32((rmax - rmin) / 255 if rmin != rmax else 1)\n zp_expected = np.uint8(round(max(0, min(255, (0 - rmin) / scale_expected))))\n zp_actual = value[0]\n scale_actual = value[1]\n\n self.assertEqual(zp_expected, zp_actual)\n self.assertEqual(scale_expected, scale_actual)\n \n print('Finished' + ' test calculation of quantization params.')\n\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "numpy.random.seed", "torch.load", "torch.manual_seed", "torch.utils.data.DataLoader", "torch.no_grad", "torch.cuda.manual_seed_all", "numpy.load", "numpy.array", "torch.save" ], [ "numpy.array", "numpy.mean", "numpy.percentile" ], [ "tensorflow.math.add", "tensorflow.compat.v1.random_normal_initializer", "tensorflow.constant", "tensorflow.nn.relu6", "numpy.random.random", "tensorflow.compat.v1.get_variable", "tensorflow.compat.v1.global_variables_initializer", "tensorflow.compat.v1.Session", "tensorflow.compat.v1.placeholder", "tensorflow.python.framework.graph_util.convert_variables_to_constants", "numpy.random.randint", "tensorflow.pad", "tensorflow.core.framework.attr_value_pb2.AttrValue", "tensorflow.nn.conv2d" ], [ "numpy.array" ], [ "numpy.concatenate" ], [ "tensorflow.core.framework.graph_pb2.GraphDef" ], [ "numpy.random.random", "numpy.random.randn", "numpy.float32", "numpy.random.ranf", "numpy.array", "numpy.random.randint" ] ]
[ { "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": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ColinRTaylor/evalml
[ "5b372d0dfac05ff9b7e41eb494a9df1bf2da4a9d", "5b372d0dfac05ff9b7e41eb494a9df1bf2da4a9d" ]
[ "evalml/tests/integration_tests/test_data_checks_and_actions_integration.py", "evalml/model_understanding/_partial_dependence.py" ]
[ "import numpy as np\nimport pandas as pd\nimport pytest\nimport woodwork as ww\nfrom pandas.testing import assert_frame_equal, assert_series_equal\n\nfrom evalml.automl import get_default_primary_search_objective\nfrom evalml.data_checks import DefaultDataChecks, OutliersDataCheck\nfrom evalml.data_checks.invalid_target_data_check import InvalidTargetDataCheck\nfrom evalml.data_checks.null_data_check import NullDataCheck\nfrom evalml.pipelines import BinaryClassificationPipeline\nfrom evalml.pipelines.components import (\n DropColumns,\n DropRowsTransformer,\n TargetImputer,\n)\nfrom evalml.pipelines.components.transformers.imputers.per_column_imputer import (\n PerColumnImputer,\n)\nfrom evalml.pipelines.multiclass_classification_pipeline import (\n MulticlassClassificationPipeline,\n)\nfrom evalml.pipelines.regression_pipeline import RegressionPipeline\nfrom evalml.pipelines.utils import make_pipeline_from_data_check_output\n\n\ndef test_data_checks_with_healthy_data(X_y_binary):\n # Checks do not return any error.\n X, y = X_y_binary\n data_check = DefaultDataChecks(\n \"binary\", get_default_primary_search_objective(\"binary\")\n )\n data_checks_output = data_check.validate(X, y)\n\n assert make_pipeline_from_data_check_output(\n \"binary\", data_checks_output\n ) == BinaryClassificationPipeline(component_graph={}, parameters={}, random_seed=0)\n\n\ndef test_data_checks_suggests_drop_and_impute_cols():\n X = pd.DataFrame(\n {\n \"null_with_categorical\": [\"a\", None, \"b\", \"c\", \"c\"],\n \"lots_of_null\": [None, 7, None, 3, 5],\n \"all_null\": [None, None, None, None, None],\n \"no_null\": [1, 2, 3, 4, 5],\n }\n )\n X.ww.init(logical_types={\"null_with_categorical\": \"categorical\"})\n y = pd.Series([1, 0, 0, 1, 1])\n data_check = NullDataCheck()\n data_checks_output = data_check.validate(X, y)\n\n action_pipeline = make_pipeline_from_data_check_output(\"binary\", data_checks_output)\n assert action_pipeline == BinaryClassificationPipeline(\n component_graph={\n \"Per Column Imputer\": [PerColumnImputer, \"X\", \"y\"],\n \"Drop Columns Transformer\": [\n DropColumns,\n \"Per Column Imputer.x\",\n \"y\",\n ],\n },\n parameters={\n \"Per Column Imputer\": {\n \"impute_strategies\": {\n \"null_with_categorical\": {\"impute_strategy\": \"most_frequent\"},\n \"lots_of_null\": {\"impute_strategy\": \"mean\"},\n },\n \"default_impute_strategy\": \"most_frequent\",\n },\n \"Drop Columns Transformer\": {\"columns\": [\"all_null\"]},\n },\n random_seed=0,\n )\n X_expected = pd.DataFrame(\n {\n \"null_with_categorical\": [\"a\", \"c\", \"b\", \"c\", \"c\"],\n \"lots_of_null\": [5, 7, 5, 3, 5],\n \"no_null\": [1, 2, 3, 4, 5],\n }\n )\n X_expected.ww.init(\n logical_types={\"lots_of_null\": \"double\", \"null_with_categorical\": \"categorical\"}\n )\n action_pipeline.fit(X, y)\n X_t = action_pipeline.transform(X, y)\n assert_frame_equal(X_expected, X_t)\n\n\[email protected](\"problem_type\", [\"binary\", \"multiclass\", \"regression\"])\ndef test_data_checks_impute_cols(problem_type):\n X = pd.DataFrame()\n if problem_type == \"binary\":\n y = ww.init_series(pd.Series([0, 1, 1, None, None]))\n objective = \"Log Loss Binary\"\n expected_pipeline_class = BinaryClassificationPipeline\n y_expected = ww.init_series(pd.Series([0, 1, 1, 1, 1]), logical_type=\"double\")\n\n elif problem_type == \"multiclass\":\n y = ww.init_series(pd.Series([0, 1, 2, 2, None]))\n objective = \"Log Loss Multiclass\"\n expected_pipeline_class = MulticlassClassificationPipeline\n y_expected = ww.init_series(pd.Series([0, 1, 2, 2, 2]), logical_type=\"double\")\n\n else:\n y = ww.init_series(pd.Series([0, 0.1, 0.2, None, None]))\n objective = \"R2\"\n expected_pipeline_class = RegressionPipeline\n y_expected = ww.init_series(\n pd.Series([0, 0.1, 0.2, 0.1, 0.1]), logical_type=\"double\"\n )\n data_check = InvalidTargetDataCheck(problem_type, objective)\n data_checks_output = data_check.validate(None, y)\n\n action_pipeline = make_pipeline_from_data_check_output(\n problem_type, data_checks_output\n )\n expected_parameters = (\n {\"Target Imputer\": {\"impute_strategy\": \"mean\", \"fill_value\": None}}\n if problem_type == \"regression\"\n else {\n \"Target Imputer\": {\"impute_strategy\": \"most_frequent\", \"fill_value\": None}\n }\n )\n assert action_pipeline == expected_pipeline_class(\n component_graph={\"Target Imputer\": [TargetImputer, \"X\", \"y\"]},\n parameters=expected_parameters,\n random_seed=0,\n )\n\n action_pipeline.fit(X, y)\n _, y_t = action_pipeline.transform(X, y)\n assert_series_equal(y_expected, y_t)\n\n\ndef test_data_checks_suggests_drop_rows():\n a = np.arange(10) * 0.01\n data = np.tile(a, (100, 10))\n\n X = pd.DataFrame(data=data)\n X.iloc[0, 3] = 1000\n X.iloc[3, 25] = 1000\n X.iloc[5, 55] = 10000\n X.iloc[10, 72] = -1000\n X.iloc[:, 90] = \"string_values\"\n y = pd.Series(np.tile([0, 1], 50))\n\n outliers_check = OutliersDataCheck()\n data_checks_output = outliers_check.validate(X)\n\n action_pipeline = make_pipeline_from_data_check_output(\"binary\", data_checks_output)\n assert action_pipeline == BinaryClassificationPipeline(\n component_graph={\"Drop Rows Transformer\": [DropRowsTransformer, \"X\", \"y\"]},\n parameters={\"Drop Rows Transformer\": {\"indices_to_drop\": [0, 3, 5, 10]}},\n random_seed=0,\n )\n\n X_expected = X.drop([0, 3, 5, 10])\n X_expected.ww.init()\n y_expected = y.drop([0, 3, 5, 10])\n\n action_pipeline.fit(X, y)\n X_t, y_t = action_pipeline.transform(X, y)\n assert_frame_equal(X_expected, X_t)\n assert_series_equal(y_expected, y_t)\n", "\"\"\"Partial dependence implementation.\n\nBorrows from sklearn \"brute\" calculation but with our\nown modification to better handle mixed data types in the grid\nas well as EvalML pipelines.\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport woodwork as ww\nfrom scipy.stats.mstats import mquantiles\n\nfrom evalml.problem_types import is_regression\n\n\ndef _range_for_dates(X_dt, percentiles, grid_resolution):\n \"\"\"Compute the range of values used in partial dependence for datetime features.\n\n Interpolate between the percentiles of the dates converted to unix\n timestamps.\n\n Args:\n X_dt (pd.DataFrame): Datetime features in original data. We currently\n only support X_dt having a single column.\n percentiles (tuple float): Percentiles to interpolate between.\n grid_resolution (int): Number of points in range.\n\n Returns:\n pd.Series: Range of dates between percentiles.\n \"\"\"\n timestamps = np.array(\n [X_dt - pd.Timestamp(\"1970-01-01\")] // np.timedelta64(1, \"s\")\n ).reshape(-1, 1)\n timestamps = pd.DataFrame(timestamps)\n grid, values = _grid_from_X(\n timestamps,\n percentiles=percentiles,\n grid_resolution=grid_resolution,\n custom_range={},\n )\n grid_dates = pd.to_datetime(pd.Series(grid.squeeze()), unit=\"s\")\n return grid_dates\n\n\ndef _grid_from_X(X, percentiles, grid_resolution, custom_range):\n \"\"\"Create cartesian product of all the columns of input dataframe X.\n\n Args:\n X (pd.DataFrame): Input data\n percentiles (tuple float): Percentiles to use as endpoints of the grid\n for each feature.\n grid_resolution (int): How many points to interpolate between percentiles.\n custom_range (dict[str, np.ndarray]): Mapping from column name in X to\n range of values to use in partial dependence. If custom_range is specified,\n the percentile + interpolation procedure is skipped and the values in custom_range\n are used.\n\n Returns:\n pd.DataFrame: Cartesian product of input columns of X.\n \"\"\"\n values = []\n for feature in X.columns:\n if feature in custom_range:\n # Use values in the custom range\n feature_range = custom_range[feature]\n if not isinstance(feature_range, (np.ndarray, pd.Series)):\n feature_range = np.array(feature_range)\n if feature_range.ndim != 1:\n raise ValueError(\n \"Grid for feature {} is not a one-dimensional array. Got {}\"\n \" dimensions\".format(feature, feature_range.ndim)\n )\n axis = feature_range\n else:\n feature_vector = X.loc[:, feature].dropna()\n uniques = np.unique(feature_vector)\n if uniques.shape[0] < grid_resolution:\n # feature has low resolution use unique vals\n axis = uniques\n else:\n # create axis based on percentiles and grid resolution\n emp_percentiles = mquantiles(feature_vector, prob=percentiles, axis=0)\n if np.allclose(emp_percentiles[0], emp_percentiles[1]):\n raise ValueError(\n \"percentiles are too close to each other, \"\n \"unable to build the grid. Please choose percentiles \"\n \"that are further apart.\"\n )\n axis = np.linspace(\n emp_percentiles[0],\n emp_percentiles[1],\n num=grid_resolution,\n endpoint=True,\n )\n values.append(axis)\n\n return _cartesian(values), values\n\n\ndef _cartesian(arrays):\n \"\"\"Create cartesian product of elements of arrays list.\n\n Stored in a dataframe to allow mixed types like dates/str/numeric.\n\n Args:\n arrays (list(np.ndarray)): Arrays.\n\n Returns:\n pd.DataFrame: Cartesian product of arrays.\n \"\"\"\n arrays = [np.asarray(x) for x in arrays]\n shape = (len(x) for x in arrays)\n\n ix = np.indices(shape)\n ix = ix.reshape(len(arrays), -1).T\n\n out = pd.DataFrame()\n\n for n, arr in enumerate(arrays):\n out[n] = arrays[n][ix[:, n]]\n\n return out\n\n\ndef _partial_dependence_calculation(pipeline, grid, features, X):\n \"\"\"Do the partial dependence calculation once the grid is computed.\n\n Args:\n pipeline (PipelineBase): pipeline.\n grid (pd.DataFrame): Grid of features to compute the partial dependence on.\n features (list(str)): Column names of input data\n X (pd.DataFrame): Input data.\n\n Returns:\n Tuple (np.ndarray, np.ndarray): averaged and individual predictions for\n all points in the grid.\n \"\"\"\n predictions = []\n averaged_predictions = []\n\n if is_regression(pipeline.problem_type):\n prediction_method = pipeline.predict\n else:\n prediction_method = pipeline.predict_proba\n\n X_eval = X.ww.copy()\n for _, new_values in grid.iterrows():\n for i, variable in enumerate(features):\n part_dep_column = pd.Series(\n [new_values[i]] * X_eval.shape[0], index=X_eval.index\n )\n X_eval.ww[variable] = ww.init_series(\n part_dep_column, logical_type=X_eval.ww.logical_types[variable]\n )\n\n pred = prediction_method(X_eval)\n\n predictions.append(pred)\n # average over samples\n averaged_predictions.append(np.mean(pred, axis=0))\n\n n_samples = X.shape[0]\n\n # reshape to (n_instances, n_points) for binary/regression\n # reshape to (n_classes, n_instances, n_points) for multiclass\n predictions = np.array(predictions).T\n if is_regression(pipeline.problem_type) and predictions.ndim == 2:\n predictions = predictions.reshape(n_samples, -1)\n elif predictions.shape[0] == 2:\n predictions = predictions[1]\n predictions = predictions.reshape(n_samples, -1)\n\n # reshape averaged_predictions to (1, n_points) for binary/regression\n # reshape averaged_predictions to (n_classes, n_points) for multiclass.\n averaged_predictions = np.array(averaged_predictions).T\n if is_regression(pipeline.problem_type) and averaged_predictions.ndim == 1:\n averaged_predictions = averaged_predictions.reshape(1, -1)\n elif averaged_predictions.shape[0] == 2:\n averaged_predictions = averaged_predictions[1]\n averaged_predictions = averaged_predictions.reshape(1, -1)\n\n return averaged_predictions, predictions\n\n\ndef _partial_dependence(\n pipeline,\n X,\n features,\n percentiles=(0.05, 0.95),\n grid_resolution=100,\n kind=\"average\",\n custom_range=None,\n):\n \"\"\"Compute the partial dependence for features of X.\n\n Args:\n pipeline (PipelineBase): pipeline.\n X (pd.DataFrame): Holdout data\n features (list(str)): Column names of X to compute the partial dependence for.\n percentiles (tuple float): Percentiles to use in range calculation for a given\n feature.\n grid_resolution: Number of points in range of values used for each feature in\n partial dependence calculation.\n kind (str): The type of predictions to return.\n custom_range (dict[str, np.ndarray]): Mapping from column name in X to\n range of values to use in partial dependence. If custom_range is specified,\n the percentile + interpolation procedure is skipped and the values in custom_range\n are used.\n\n Returns:\n dict with 'average', 'individual', 'values' keys. 'values' is a list of\n the values used in the partial dependence for each feature.\n 'average' and 'individual' are averaged and individual predictions for\n each point in the grid.\n \"\"\"\n if grid_resolution <= 1:\n raise ValueError(\"'grid_resolution' must be strictly greater than 1.\")\n\n custom_range = custom_range or {}\n custom_range = {\n feature: custom_range.get(feature)\n for feature in features\n if feature in custom_range\n }\n grid, values = _grid_from_X(\n X.loc[:, features],\n percentiles,\n grid_resolution,\n custom_range,\n )\n averaged_predictions, predictions = _partial_dependence_calculation(\n pipeline,\n grid,\n features,\n X,\n )\n\n # reshape predictions to\n # (n_outputs, n_instances, n_values_feature_0, n_values_feature_1, ...)\n predictions = predictions.reshape(-1, X.shape[0], *[val.shape[0] for val in values])\n\n # reshape averaged_predictions to\n # (n_outputs, n_values_feature_0, n_values_feature_1, ...)\n averaged_predictions = averaged_predictions.reshape(\n -1, *[val.shape[0] for val in values]\n )\n\n if kind == \"average\":\n return {\"average\": averaged_predictions, \"values\": values}\n elif kind == \"individual\":\n return {\"individual\": predictions, \"values\": values}\n else: # kind='both'\n return {\n \"average\": averaged_predictions,\n \"individual\": predictions,\n \"values\": values,\n }\n" ]
[ [ "pandas.testing.assert_series_equal", "pandas.Series", "numpy.arange", "numpy.tile", "pandas.DataFrame", "pandas.testing.assert_frame_equal" ], [ "pandas.Series", "numpy.allclose", "numpy.unique", "numpy.asarray", "numpy.linspace", "pandas.Timestamp", "numpy.indices", "pandas.DataFrame", "numpy.timedelta64", "numpy.mean", "numpy.array", "scipy.stats.mstats.mquantiles" ] ]
[ { "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": [] }, { "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": [] } ]
markvilar/Cardinal
[ "a3d87d34ed253a7a4400ed056c5d59c20f15973b" ]
[ "Python/filter_dvl.py" ]
[ "import argparse\nimport datetime\nimport numpy as np\nimport pandas as pd\nimport matplotlib\nmatplotlib.use(\"TkAgg\")\nimport matplotlib.pyplot as plt\nplt.style.use(\"./Styles/Scientific.mplstyle\")\n\nfrom typing import Dict, List\n\nimport data\nimport filters\nimport utilities\nimport utm\n\ndef filter_dvl(data_config: data.DataConfiguration, \\\n filter_config: filters.FilterConfiguration):\n \"\"\"\n \"\"\"\n # Read data.\n data = pd.read_csv(data_config.input)\n\n # Extract relevant data for filtering.\n time = data[\"Epoch\"].to_numpy()\n altitude = data[\"Altitude\"].to_numpy()\n\n # Calculate sampling frequency.\n filter_config.sample_frequency = 1 / np.mean(time[1:] - time[0:-1])\n\n # Add end values.\n filtered_altitude = filters.add_appendage(altitude, filter_config)\n\n # Filter data and account for time delay.\n filtered_altitude, filter_delay = filters.FIR_filter(filtered_altitude, \\\n filter_config, axis=1)\n\n filtered_time = time - filter_delay\n\n print(\"\\nDVL:\")\n print(\" - Sampling time: {0:.4f}\".format( \\\n 1 / filter_config.sample_frequency))\n print(\" - Sampling frequency: {0:.4f}\".format( \\\n filter_config.sample_frequency))\n print(\" - Filter time delay: {0:.4f}\".format(filter_delay))\n\n # Remove end values.\n filtered_altitude = filters.remove_appendage(filtered_altitude, \\\n filter_config)\n\n filtered_data = pd.DataFrame()\n filtered_data[\"Epoch\"] = filtered_time\n filtered_data[\"Altitude\"] = filtered_altitude\n\n # Datetime calculations.\n times = []\n for epoch in filtered_data[\"Epoch\"]:\n time = datetime.datetime.fromtimestamp(epoch).strftime( \\\n data_config.datetime_format)\n times.append(time)\n\n filtered_data[\"Datetime\"] = np.array(times, dtype=str)\n\n # Save data.\n if data_config.save_output:\n filtered_data = pd.DataFrame(filtered_data)\n filtered_data.to_csv(data_config.output + \"ROV-DVL.csv\", sep=',')\n\ndef main():\n # Parse arguments.\n parser = argparse.ArgumentParser( \\\n description=\"Filter DVL data with a FIR lowpass filter.\")\n parser.add_argument(\"input\", type=str, help=\"Input file path.\")\n parser.add_argument(\"output\", type=str, help=\"Output directory path.\") \n parser.add_argument(\"order\", type=int, help=\"Filter order.\")\n parser.add_argument(\"cutoff\", type=float, help=\"Filter cutoff.\")\n parser.add_argument(\"appendage\", type=int, help=\"Filter appendage.\")\n parser.add_argument('--show_figures', type=bool, default=False, \\\n help= \"Show figures.\", action=argparse.BooleanOptionalAction)\n parser.add_argument('--save_figures', type=bool, default=False, \\\n help= \"Save figures.\", action=argparse.BooleanOptionalAction)\n parser.add_argument('--save_output', type=bool, default=False, \\\n help= \"Save output.\", action=argparse.BooleanOptionalAction)\n args = parser.parse_args()\n\n # Data configuration.\n data_config = data.DataConfiguration(args.input, args.output, \\\n args.show_figures, args.save_figures, args.save_output)\n\n # Filter configuration.\n filter_config = filters.FilterConfiguration(args.order, args.cutoff, \\\n args.appendage)\n\n # Filter data.\n filter_dvl(data_config, filter_config)\n \nif __name__ == '__main__':\n main()\n" ]
[ [ "pandas.read_csv", "matplotlib.use", "pandas.DataFrame", "numpy.mean", "numpy.array", "matplotlib.pyplot.style.use" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
natalia-rubio/py_grama
[ "968c1c0238d7165de3b1b96534791feacc4aa960" ]
[ "docs/scripts/ex_sinews.py" ]
[ "import grama as gr\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom grama.models import make_cantilever_beam\nmd_beam = make_cantilever_beam()\n\nmd_beam >> \\\n gr.ev_sinews(n_density=50, n_sweeps=10, df_det=\"nom\", skip=True) >> \\\n gr.pt_auto()\nplt.savefig(\"../images/ex_beam_sinews_doe.png\")\n\nmd_beam >> \\\n gr.ev_sinews(n_density=50, n_sweeps=10, df_det=\"nom\", skip=False) >> \\\n gr.pt_auto()\nplt.savefig(\"../images/ex_beam_sinews_res.png\")\n" ]
[ [ "matplotlib.pyplot.savefig" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ahmed-f-alrefaie/forecaster
[ "25b73a533f6195f3e5c703730e63cb3e242c649a" ]
[ "forecaster/func.py" ]
[ "import numpy as np\nfrom scipy.stats import norm, truncnorm\nfrom numpy.random import default_rng\n\n\n### fix the number of different populations\nn_pop = 4\n\ndef pick_random_hyper(all_hyper, sample_size=None):\n\trng = default_rng()\n\tsize = sample_size or all_hyper.shape[0]\n\treturn rng.choice(all_hyper, size=sample_size, replace=False)\n\n\n\n\n\ndef indicate(M, trans, i):\n\t'''\n\tindicate which M belongs to population i given transition parameter\n\t'''\n\tts = np.insert(np.insert(trans, n_pop-1, np.inf), 0, -np.inf)\n\treturn (M>=ts[i]) & (M<ts[i+1])\n\ndef indicate_II(M, trans, i):\n\n\treturn (M>=trans[...,i]) & (M<trans[...,i+1])\n\n\n\ndef split_hyper_linear(hyper):\n\t'''\n\tsplit hyper and derive c\n\t'''\n\tc0, slope,sigma, trans = \\\n\thyper[0], hyper[1:1+n_pop], hyper[1+n_pop:1+2*n_pop], hyper[1+2*n_pop:]\n\n\tc = np.zeros_like(slope)\n\tc[0] = c0\n\tfor i in range(1,n_pop):\n\t\tc[i] = c[i-1] + trans[i-1]*(slope[i-1]-slope[i])\n\n\treturn c, slope, sigma, trans\n\n\ndef split_hyper_linear_II(hyper):\n\t'''\n\tsplit hyper and derive c\n\t'''\n\tc0, slope,sigma, trans = \\\n\thyper[...,0], hyper[...,1:1+n_pop], hyper[...,1+n_pop:1+2*n_pop], hyper[...,1+2*n_pop:]\n\n\tc = np.zeros_like(slope)\n\tc[...,0] = c0\n\tfor i in range(1,n_pop):\n\t\tc[...,i] = c[...,i-1] + trans[...,i-1]*(slope[...,i-1]-slope[...,i])\n\ttrans = np.insert(np.insert(trans,n_pop-1,np.inf,axis=1), 0, -np.inf, axis=1)\n\treturn c, slope, sigma, trans\n\n\ndef piece_linear_II(hyper, M, prob_R):\n\tc, slope, sigma, trans = split_hyper_linear_II(hyper)\n\n\tM = M\n\n\tR = np.zeros_like(M)\n\n\tfor i in range(n_pop):\n\t\tind = indicate_II(M, trans, i)\n\t\tmu = c[...,i]\n\t\tmu[ind] += M[ind]*slope[ind,i]\n\t\tR[ind] = norm.ppf(prob_R[ind],mu[ind],sigma[ind,i])\n\n\treturn R\n\ndef generate_mass(mean, std, sample_size):\n\tmlower = 3e-4\n\tmupper = 3e5\n\treturn truncnorm.rvs( (mlower-mean)/std, (mupper-mean)/std, loc=mean, scale=std, size=sample_size)\t\n\n\ndef piece_linear(hyper, M, prob_R):\n\t'''\n\tmodel: straight line\n\t'''\n\n\tM = np.array(M)\n\tc, slope, sigma, trans = split_hyper_linear(hyper)\n\tR = np.zeros_like(M)\n\n\tfor i in range(4):\n\t\tind = indicate(M, trans, i)\n\n\t\tmu = c[i] + M[ind]*slope[i]\n\t\tR[ind] = norm.ppf(prob_R[ind], mu, sigma[i])\n\n\treturn R\n\n\ndef ProbRGivenM(radii, M, hyper):\n\t'''\n\tp(radii|M)\n\t'''\n\tc, slope, sigma, trans = split_hyper_linear(hyper)\n\tprob = np.zeros_like(M)\n\t#print('SHAPE', prob.shape, M.shape, slope.shape)\n\tfor i in range(4):\n\t\tind = indicate(M, trans, i)\n\t\t#print('MSHAPE',M[ind].shape)\n\t\tmu = c[i] + M[ind]*slope[i]\n\t\t#print('EXPECTED',mu)\n\t\tsig = sigma[i]\n\t\tprob[ind] = norm.pdf(radii, mu, sig)\n\n\tprob = prob/np.sum(prob)\n\n\treturn prob\n\ndef ProbRGivenM_II(radii, M, hyper):\n\tc, slope, sigma, trans = split_hyper_linear_II(hyper)\n\t# 10, 100\n\tprob = np.zeros(shape=(radii.shape[0], M.shape[0]))\n\tmu = np.zeros_like(prob)\n\tfor i in range(n_pop):\n\t\tmu[...] = 0.0\n\t\tind = indicate_II(M[None,...], trans[:,None,:], i)\n\t\tradii_id,mass_id = np.where(ind)\n\t\t#\n\t\tmu[radii_id, mass_id] = c[radii_id,i] + slope[radii_id,i]*M[mass_id]#M[None,...]*slope[:,None,i][ind]\n\t\t#print(mu[0])\n\t\tprob[ind] = norm.pdf(radii[radii_id],mu[radii_id, mass_id],sigma[radii_id,i])\n\t#print('C',c[:,None,i])\n\treturn (prob/np.sum(prob, axis=1)[:,None])\n\ndef random_choice_2d(arr, probs):\n\tidx = (probs.cumsum(1) > np.random.rand(probs.shape[0])[:,None]).argmax(1)\n\treturn arr[idx]\n\n\n\ndef classification( logm, trans ):\n\t'''\n\tclassify as four worlds\n\t'''\n\tcount = np.zeros(4)\n\tsample_size = len(logm)\n\tts = np.insert(np.insert(trans, n_pop-1, np.inf), 0, -np.inf)\n\tfor iclass in range(4):\n\t\t\n\t\tind = indicate_II( logm, ts, iclass)\n\t\tcount[iclass] = count[iclass] + ind.sum()\n\t\n\tprob = count / np.sum(count) * 100.\n\tprint ('Terran %(T).1f %%, Neptunian %(N).1f %%, Jovian %(J).1f %%, Star %(S).1f %%' \\\n\t\t\t% {'T': prob[0], 'N': prob[1], 'J': prob[2], 'S': prob[3]})\n\treturn None" ]
[ [ "scipy.stats.norm.ppf", "numpy.sum", "scipy.stats.norm.pdf", "numpy.zeros_like", "numpy.insert", "numpy.where", "numpy.random.rand", "numpy.array", "numpy.zeros", "scipy.stats.truncnorm.rvs", "numpy.random.default_rng" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
drkostas/SemiSeg-Contrastive
[ "af6b133400368911ef77f401b7673894fe6aa05c" ]
[ "utils/transformsgpu.py" ]
[ "'''\nCode taken from https://github.com/WilhelmT/ClassMix\nSlightly modified\n'''\n\nimport kornia\nimport torch\nimport random\nimport torch.nn as nn\n\n\ndef normalize_rgb(data, dataset):\n \"\"\"\n\n Args:\n data: data to normalize BxCxWxH\n dataset: name of the dataset to normalize\n\n Returns:\n normalized data as (x-mean)/255\n\n \"\"\"\n if dataset == 'pascal_voc':\n mean = (122.6789143, 116.66876762, 104.00698793) # rgb\n elif dataset == 'cityscapes':\n mean = (73.15835921, 82.90891754, 72.39239876) # rgb\n else:\n mean = (127.5, 127.5, 127.5 )\n\n mean = torch.Tensor(mean).unsqueeze(0).unsqueeze(2).unsqueeze(3).cuda()\n data_norm = ((data-mean)/255.0)\n return data_norm\n\n\ndef normalize_bgr(data, dataset):\n \"\"\"\n\n Args:\n data: data to normalize BxCxWxH\n dataset: name of the dataset to normalize\n\n Returns:\n normalized data as (x-mean)/255\n\n \"\"\"\n if dataset == 'pascal_voc':\n mean = (104.00698793, 116.66876762, 122.6789143) # bgr\n elif dataset == 'cityscapes':\n mean = (72.39239876, 82.90891754, 73.15835921) # bgr\n else:\n mean = (127.5, 127.5, 127.5 )\n\n mean = torch.Tensor(mean).unsqueeze(0).unsqueeze(2).unsqueeze(3).cuda()\n data_norm = ((data-mean)/255.0)\n return data_norm\n\n\n\ndef grayscale(grayscale, data = None, target = None, probs = None):\n \"\"\"\n\n Args:\n grayscale: boolean whether to apply grayscale augmentation\n data: input data to augment BxCxWxH\n target: labels to augment BxWxH\n probs: probability masks to augment BxCxWxH\n\n Returns:\n data is converted from rgb to grayscale if [grayscale] is True\n target and probs are also returned with no modifications applied\n\n \"\"\"\n if not (data is None):\n if grayscale and data.shape[1]==3:\n seq = nn.Sequential(kornia.augmentation.RandomGrayscale(p=1.) )\n data = seq(data)\n return data, target, probs\n\ndef colorJitter(colorJitter, data = None, target = None, s=0.1, probs = None):\n \"\"\"\n\n Args:\n colorJitter: boolean whether to apply colorJitter augmentation\n data: input data to augment BxCxWxH\n target: labels to augment BxWxH\n probs: probability masks to augment BxCxWxH\n s: brightness and contrast strength of the color jitter\n\n Returns:\n colorJitter is applied to data if [colorJitter] is True\n target and probs are also returned with no modifications applied\n\n\n \"\"\"\n if not (data is None):\n if colorJitter and data.shape[1]==3:\n seq = nn.Sequential(kornia.augmentation.ColorJitter(brightness=s,contrast=s,saturation=s/2.,hue=s/3.))\n data = seq(data/255.)*255. # assumes [0,1]\n return data, target, probs\n\ndef gaussian_blur(blur, data = None, target = None, min_sigma=0.2, max_sigma=3, probs = None):\n \"\"\"\n\n Args:\n blur: boolean whether to apply blur\n data: input data to augment BxCxWxH\n target: labels to augment BxWxH\n probs: probability masks to augment BxCxWxH\n min_sigma: minimum sigma value for the gaussian blur\n max_sigma: maximum sigma value for the gaussian blur\n\n Returns:\n gaussian blur is applied to data if [blur] is True\n target and probs are also returned with no modifications applied\n\n \"\"\"\n if not (data is None):\n if blur and data.shape[1]==3:\n seq = nn.Sequential(kornia.filters.GaussianBlur2d(kernel_size=(23, 23), sigma=(min_sigma, max_sigma)))\n data = seq(data)\n return data, target, probs\n\ndef flip(flip, data = None, target = None, probs = None):\n \"\"\"\n\n Args:\n flip: boolean whether to apply flip augmentation\n data: input data to augment BxCxWxH\n target: labels to augment BxWxH\n probs: probability masks to augment BxCxWxH\n\n Returns:\n data, target and probs are flipped if the boolean flip is True\n\n \"\"\"\n if flip:\n if not (data is None): data = torch.flip(data,(3,))\n if not (target is None):\n target = torch.flip(target,(2,))\n if not (probs is None):\n probs = torch.flip(probs,(2,))\n return data, target, probs\n\ndef solarize(solarize, data = None, target = None, probs = None):\n \"\"\"\n\n Args:\n solarize: boolean whether to apply solarize augmentation\n data: input data to augment BxCxWxH\n target: labels to augment BxWxH\n probs: probability masks to augment BxCxWxH\n\n Returns:\n data, target, probs, where\n data is solarized if [solarize] is True\n\n \"\"\"\n if not (data is None):\n if solarize and data.shape[1]==3:\n seq = nn.Sequential(kornia.augmentation.RandomSolarize((0, 1)))\n data = seq(data.cpu()/255.).cuda()*255.\n return data, target, probs\n\n\n\n\ndef mix(mask, data = None, target = None, probs = None):\n \"\"\"\n Applies classMix augmentation:\n https://openaccess.thecvf.com/content/WACV2021/papers/Olsson_ClassMix_Segmentation-Based_Data_Augmentation_for_Semi-Supervised_Learning_WACV_2021_paper.pdf\n Args:\n mask: masks for applying ClassMix. A list of B elements of CxWxH tensors\n data: input data to augment BxCxWxH\n target: labels to augment BxWxH\n probs: probability masks to augment BxCxWxH\n\n Returns:\n data, target and probs augmented with classMix\n\n \"\"\"\n if not (data is None):\n if mask.shape[0] == data.shape[0]:\n data = torch.cat([((1 - mask[(i + 1) % data.shape[0]]) * data[i] + mask[(i + 1) % data.shape[0]] * data[(i + 1) % data.shape[0]]).unsqueeze(0) for i in range(data.shape[0])])\n\n if not (target is None):\n target = torch.cat([((1 - mask[(i + 1) % data.shape[0]]) * target[i] + mask[(i + 1) % data.shape[0]] * target[(i + 1) % target.shape[0]]).unsqueeze(0) for i in range(target.shape[0])])\n\n if not (probs is None):\n probs = torch.cat([((1 - mask[(i + 1) % data.shape[0]]) * probs[i] + mask[(i + 1) % data.shape[0]] * probs[(i + 1) % probs.shape[0]]).unsqueeze(0) for i in range(probs.shape[0])])\n\n return data, target, probs\n\n\ndef random_scale_crop(scale, data = None, target = None, ignore_label=255, probs = None):\n \"\"\"\n\n Args:\n scale: scale ratio. Float\n data: input data to augment BxCxWxH\n target: labels to augment BxWxH\n probs: probability masks to augment BxCxWxH\n ignore_label: integeer value that defines the ignore class in the datasets for the labels\n\n Returns:\n data, target and prob, after applied a scaling operation. output resolution is preserve as the same as the input resolution WxH\n \"\"\"\n if scale != 1:\n init_size_w = data.shape[2]\n init_size_h = data.shape[3]\n\n # scale data, labels and probs\n data = nn.functional.interpolate(data, scale_factor=scale, mode='bilinear', align_corners=True, recompute_scale_factor=True)\n if target is not None:\n target = nn.functional.interpolate(target.unsqueeze(1).float(), scale_factor=scale, mode='nearest', recompute_scale_factor=True).long().squeeze(1)\n if probs is not None:\n probs = nn.functional.interpolate(probs.unsqueeze(1), scale_factor=scale, mode='bilinear', align_corners=True, recompute_scale_factor=True).squeeze(1)\n\n final_size_w = data.shape[2]\n final_size_h = data.shape[3]\n diff_h = init_size_h - final_size_h\n diff_w = init_size_w - final_size_w\n if scale < 1: # add padding if needed\n if diff_h % 2 == 1:\n pad = nn.ConstantPad2d((diff_w//2, diff_w//2+1, diff_h//2+1, diff_h//2), 0)\n else:\n pad = nn.ConstantPad2d((diff_w//2, diff_w//2, diff_h//2, diff_h//2), 0)\n\n data = pad(data)\n if probs is not None:\n probs = pad(probs)\n\n # padding with ignore label to add to labels\n if diff_h % 2 == 1:\n pad = nn.ConstantPad2d((diff_w//2, diff_w//2+1, diff_h//2+1, diff_h//2), ignore_label)\n else:\n pad = nn.ConstantPad2d((diff_w//2, diff_w//2, diff_h//2, diff_h//2), ignore_label)\n\n if target is not None:\n target = pad(target)\n\n else: # crop if needed\n w = random.randint(0, data.shape[2] - init_size_w)\n h = random.randint(0, data.shape[3] - init_size_h)\n data = data [:,:,h:h+init_size_h,w:w + init_size_w]\n if probs is not None:\n probs = probs [:,h:h+init_size_h,w:w + init_size_w]\n if target is not None:\n target = target [:,h:h+init_size_h,w:w + init_size_w]\n\n return data, target, probs\n\n\n" ]
[ [ "torch.nn.ConstantPad2d", "torch.flip", "torch.Tensor", "torch.nn.functional.interpolate" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
krowck/ISDA-NCjDE-HJ
[ "44c33ba12542a88eaa39fe2b72398ffd7b439372" ]
[ "NDBSCANjDE/CF3.py" ]
[ "###############################################################################\n# Version: 1.1\n# Last modified on: 3 April, 2016 \n# Developers: Michael G. Epitropakis\n# email: m_(DOT)_epitropakis_(AT)_lancaster_(DOT)_ac_(DOT)_uk \n###############################################################################\nfrom cfunction import *\nimport numpy as np\n\nclass CF3(CFunction):\n\tdef __init__(self, dim):\n\t\tsuper(CF3, self).__init__(dim, 6)\n\n\t\t# Initialize data for composition\n\t\tself._CFunction__sigma_ = np.array( [1.0, 1.0, 2.0, 2.0, 2.0, 2.0] )\n\t\tself._CFunction__bias_ = np.zeros( self._CFunction__nofunc_ )\n\t\tself._CFunction__weight_ = np.zeros( self._CFunction__nofunc_ )\n\t\tself._CFunction__lambda_ = np.array( [1.0/4.0, 1.0/10.0, 2.0, 1.0, 2.0, 5.0] )\n\t\t\n\t\t# Lower/Upper Bounds\n\t\tself._CFunction__lbound_ = -5.0 * np.ones( dim )\n\t\tself._CFunction__ubound_ = 5.0 * np.ones( dim )\n\n\t\t# Load optima\n\t\to = np.loadtxt('data/optima.dat') \n\t\tif o.shape[1] >= dim:\n\t\t\tself._CFunction__O_ = o[:self._CFunction__nofunc_, :dim]\n\t\telse: # randomly initialize\n\t\t\tself._CFunction__O_ = self._CFunction__lbound_ + (self._CFunction__ubound_ - self._CFunction__lbound_) * np.random.rand( (self._CFunction__nofunc_, dim) )\n\n\t\t# Load M_: Rotation matrices\n\t\tif dim == 2 or dim == 3 or dim == 5 or dim == 10 or dim == 20:\n\t\t\tfname = \"data/CF3_M_D\" + str(dim) + \".dat\"\n\t\t\tself._CFunction__load_rotmat(fname)\n\t\telse:\n\t\t\t# M_ Identity matrices # TODO: Generate dimension independent rotation matrices\n\t\t\tself._CFunction__M_ = [ np.eye(dim) ] * self._CFunction__nofunc_\n\n\t\t# Initialize functions of the composition\n\t\tself._CFunction__function_ = {0:FEF8F2, 1:FEF8F2, 2:FWeierstrass, 3:FWeierstrass, 4:FGrienwank, 5:FGrienwank}\n\n\t\t# Calculate fmaxi\n\t\tself._CFunction__calculate_fmaxi()\n\n\tdef evaluate(self, x):\n\t\treturn self._CFunction__evaluate_inner_(x)\n" ]
[ [ "numpy.eye", "numpy.ones", "numpy.random.rand", "numpy.array", "numpy.zeros", "numpy.loadtxt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
13rianlucero/CrabAgePrediction
[ "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "d73a6b7f68d7bab25d134d3f85c6b63a86c206c5", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "d73a6b7f68d7bab25d134d3f85c6b63a86c206c5", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "d73a6b7f68d7bab25d134d3f85c6b63a86c206c5", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "92bc7fbe1040f49e820473e33cc3902a5a7177c7", "92bc7fbe1040f49e820473e33cc3902a5a7177c7" ]
[ "crabageprediction/venv/Lib/site-packages/pandas/tests/extension/base/dim2.py", "crabageprediction/venv/Lib/site-packages/pandas/tests/frame/methods/test_values.py", "crabageprediction/venv/Lib/site-packages/numpy/f2py/tests/test_compile_function.py", "crabageprediction/venv/Lib/site-packages/pandas/tests/io/json/test_json_table_schema.py", "crabageprediction/venv/Lib/site-packages/pandas/tests/reshape/test_qcut.py", "crabageprediction/venv/Lib/site-packages/pandas/tests/tools/test_to_time.py", "crabageprediction/venv/Lib/site-packages/numpy/distutils/__init__.py", "crabageprediction/venv/Lib/site-packages/numpy/distutils/exec_command.py", "crabageprediction/venv/Lib/site-packages/sklearn/decomposition/tests/test_sparse_pca.py", "crabageprediction/venv/Lib/site-packages/pandas/tests/io/excel/test_xlsxwriter.py", "crabageprediction/venv/Lib/site-packages/pandas/tests/groupby/test_frame_value_counts.py", "crabageprediction/venv/Lib/site-packages/pandas/core/tools/times.py", "crabageprediction/venv/Lib/site-packages/pandas/io/common.py", "crabageprediction/venv/Lib/site-packages/scipy/fft/tests/test_fftlog.py", "crabageprediction/venv/Lib/site-packages/pandas/tests/frame/methods/test_align.py", "crabageprediction/venv/Lib/site-packages/pandas/tests/scalar/timedelta/test_arithmetic.py", "crabageprediction/venv/Lib/site-packages/pandas/tests/io/conftest.py", "crabageprediction/venv/Lib/site-packages/sklearn/svm/_classes.py", "crabageprediction/venv/Lib/site-packages/sklearn/metrics/_regression.py", "crabageprediction/venv/Lib/site-packages/numpy/distutils/tests/test_fcompiler_gnu.py", "crabageprediction/venv/Lib/site-packages/pandas/tests/series/methods/test_interpolate.py", "crabageprediction/venv/Lib/site-packages/pandas/plotting/_matplotlib/hist.py", "crabageprediction/venv/Lib/site-packages/pandas/tests/frame/methods/test_copy.py", "crabageprediction/venv/Lib/site-packages/numpy/core/tests/test_indexing.py", "crabageprediction/venv/Lib/site-packages/pandas/tests/series/methods/test_duplicated.py", "crabageprediction/venv/Lib/site-packages/mpl_toolkits/mplot3d/axes3d.py" ]
[ "\"\"\"\nTests for 2D compatibility.\n\"\"\"\nimport numpy as np\nimport pytest\n\nfrom pandas._libs.missing import is_matching_na\n\nimport pandas as pd\nfrom pandas.core.arrays.integer import INT_STR_TO_DTYPE\nfrom pandas.tests.extension.base.base import BaseExtensionTests\n\n\nclass Dim2CompatTests(BaseExtensionTests):\n def test_transpose(self, data):\n arr2d = data.repeat(2).reshape(-1, 2)\n shape = arr2d.shape\n assert shape[0] != shape[-1] # otherwise the rest of the test is useless\n\n assert arr2d.T.shape == shape[::-1]\n\n def test_frame_from_2d_array(self, data):\n arr2d = data.repeat(2).reshape(-1, 2)\n\n df = pd.DataFrame(arr2d)\n expected = pd.DataFrame({0: arr2d[:, 0], 1: arr2d[:, 1]})\n self.assert_frame_equal(df, expected)\n\n def test_swapaxes(self, data):\n arr2d = data.repeat(2).reshape(-1, 2)\n\n result = arr2d.swapaxes(0, 1)\n expected = arr2d.T\n self.assert_extension_array_equal(result, expected)\n\n def test_delete_2d(self, data):\n arr2d = data.repeat(3).reshape(-1, 3)\n\n # axis = 0\n result = arr2d.delete(1, axis=0)\n expected = data.delete(1).repeat(3).reshape(-1, 3)\n self.assert_extension_array_equal(result, expected)\n\n # axis = 1\n result = arr2d.delete(1, axis=1)\n expected = data.repeat(2).reshape(-1, 2)\n self.assert_extension_array_equal(result, expected)\n\n def test_take_2d(self, data):\n arr2d = data.reshape(-1, 1)\n\n result = arr2d.take([0, 0, -1], axis=0)\n\n expected = data.take([0, 0, -1]).reshape(-1, 1)\n self.assert_extension_array_equal(result, expected)\n\n def test_repr_2d(self, data):\n # this could fail in a corner case where an element contained the name\n res = repr(data.reshape(1, -1))\n assert res.count(f\"<{type(data).__name__}\") == 1\n\n res = repr(data.reshape(-1, 1))\n assert res.count(f\"<{type(data).__name__}\") == 1\n\n def test_reshape(self, data):\n arr2d = data.reshape(-1, 1)\n assert arr2d.shape == (data.size, 1)\n assert len(arr2d) == len(data)\n\n arr2d = data.reshape((-1, 1))\n assert arr2d.shape == (data.size, 1)\n assert len(arr2d) == len(data)\n\n with pytest.raises(ValueError):\n data.reshape((data.size, 2))\n with pytest.raises(ValueError):\n data.reshape(data.size, 2)\n\n def test_getitem_2d(self, data):\n arr2d = data.reshape(1, -1)\n\n result = arr2d[0]\n self.assert_extension_array_equal(result, data)\n\n with pytest.raises(IndexError):\n arr2d[1]\n\n with pytest.raises(IndexError):\n arr2d[-2]\n\n result = arr2d[:]\n self.assert_extension_array_equal(result, arr2d)\n\n result = arr2d[:, :]\n self.assert_extension_array_equal(result, arr2d)\n\n result = arr2d[:, 0]\n expected = data[[0]]\n self.assert_extension_array_equal(result, expected)\n\n # dimension-expanding getitem on 1D\n result = data[:, np.newaxis]\n self.assert_extension_array_equal(result, arr2d.T)\n\n def test_iter_2d(self, data):\n arr2d = data.reshape(1, -1)\n\n objs = list(iter(arr2d))\n assert len(objs) == arr2d.shape[0]\n\n for obj in objs:\n assert isinstance(obj, type(data))\n assert obj.dtype == data.dtype\n assert obj.ndim == 1\n assert len(obj) == arr2d.shape[1]\n\n def test_tolist_2d(self, data):\n arr2d = data.reshape(1, -1)\n\n result = arr2d.tolist()\n expected = [data.tolist()]\n\n assert isinstance(result, list)\n assert all(isinstance(x, list) for x in result)\n\n assert result == expected\n\n def test_concat_2d(self, data):\n left = type(data)._concat_same_type([data, data]).reshape(-1, 2)\n right = left.copy()\n\n # axis=0\n result = left._concat_same_type([left, right], axis=0)\n expected = data._concat_same_type([data] * 4).reshape(-1, 2)\n self.assert_extension_array_equal(result, expected)\n\n # axis=1\n result = left._concat_same_type([left, right], axis=1)\n assert result.shape == (len(data), 4)\n self.assert_extension_array_equal(result[:, :2], left)\n self.assert_extension_array_equal(result[:, 2:], right)\n\n # axis > 1 -> invalid\n msg = \"axis 2 is out of bounds for array of dimension 2\"\n with pytest.raises(ValueError, match=msg):\n left._concat_same_type([left, right], axis=2)\n\n @pytest.mark.parametrize(\"method\", [\"backfill\", \"pad\"])\n def test_fillna_2d_method(self, data_missing, method):\n arr = data_missing.repeat(2).reshape(2, 2)\n assert arr[0].isna().all()\n assert not arr[1].isna().any()\n\n result = arr.fillna(method=method)\n\n expected = data_missing.fillna(method=method).repeat(2).reshape(2, 2)\n self.assert_extension_array_equal(result, expected)\n\n @pytest.mark.parametrize(\"method\", [\"mean\", \"median\", \"var\", \"std\", \"sum\", \"prod\"])\n def test_reductions_2d_axis_none(self, data, method):\n arr2d = data.reshape(1, -1)\n\n err_expected = None\n err_result = None\n try:\n expected = getattr(data, method)()\n except Exception as err:\n # if the 1D reduction is invalid, the 2D reduction should be as well\n err_expected = err\n try:\n result = getattr(arr2d, method)(axis=None)\n except Exception as err2:\n err_result = err2\n\n else:\n result = getattr(arr2d, method)(axis=None)\n\n if err_result is not None or err_expected is not None:\n assert type(err_result) == type(err_expected)\n return\n\n assert is_matching_na(result, expected) or result == expected\n\n @pytest.mark.parametrize(\"method\", [\"mean\", \"median\", \"var\", \"std\", \"sum\", \"prod\"])\n def test_reductions_2d_axis0(self, data, method):\n arr2d = data.reshape(1, -1)\n\n kwargs = {}\n if method == \"std\":\n # pass ddof=0 so we get all-zero std instead of all-NA std\n kwargs[\"ddof\"] = 0\n\n try:\n result = getattr(arr2d, method)(axis=0, **kwargs)\n except Exception as err:\n try:\n getattr(data, method)()\n except Exception as err2:\n assert type(err) == type(err2)\n return\n else:\n raise AssertionError(\"Both reductions should raise or neither\")\n\n def get_reduction_result_dtype(dtype):\n # windows and 32bit builds will in some cases have int32/uint32\n # where other builds will have int64/uint64.\n if dtype.itemsize == 8:\n return dtype\n elif dtype.kind in \"ib\":\n return INT_STR_TO_DTYPE[np.dtype(int).name]\n else:\n # i.e. dtype.kind == \"u\"\n return INT_STR_TO_DTYPE[np.dtype(np.uint).name]\n\n if method in [\"mean\", \"median\", \"sum\", \"prod\"]:\n # std and var are not dtype-preserving\n expected = data\n if method in [\"sum\", \"prod\"] and data.dtype.kind in \"iub\":\n dtype = get_reduction_result_dtype(data.dtype)\n\n expected = data.astype(dtype)\n if data.dtype.kind == \"b\" and method in [\"sum\", \"prod\"]:\n # We get IntegerArray instead of BooleanArray\n pass\n else:\n assert type(expected) == type(data), type(expected)\n assert dtype == expected.dtype\n\n self.assert_extension_array_equal(result, expected)\n elif method == \"std\":\n self.assert_extension_array_equal(result, data - data)\n # punt on method == \"var\"\n\n @pytest.mark.parametrize(\"method\", [\"mean\", \"median\", \"var\", \"std\", \"sum\", \"prod\"])\n def test_reductions_2d_axis1(self, data, method):\n arr2d = data.reshape(1, -1)\n\n try:\n result = getattr(arr2d, method)(axis=1)\n except Exception as err:\n try:\n getattr(data, method)()\n except Exception as err2:\n assert type(err) == type(err2)\n return\n else:\n raise AssertionError(\"Both reductions should raise or neither\")\n\n # not necessarily type/dtype-preserving, so weaker assertions\n assert result.shape == (1,)\n expected_scalar = getattr(data, method)()\n res = result[0]\n assert is_matching_na(res, expected_scalar) or res == expected_scalar\n\n\nclass NDArrayBacked2DTests(Dim2CompatTests):\n # More specific tests for NDArrayBackedExtensionArray subclasses\n\n def test_copy_order(self, data):\n # We should be matching numpy semantics for the \"order\" keyword in 'copy'\n arr2d = data.repeat(2).reshape(-1, 2)\n assert arr2d._ndarray.flags[\"C_CONTIGUOUS\"]\n\n res = arr2d.copy()\n assert res._ndarray.flags[\"C_CONTIGUOUS\"]\n\n res = arr2d[::2, ::2].copy()\n assert res._ndarray.flags[\"C_CONTIGUOUS\"]\n\n res = arr2d.copy(\"F\")\n assert not res._ndarray.flags[\"C_CONTIGUOUS\"]\n assert res._ndarray.flags[\"F_CONTIGUOUS\"]\n\n res = arr2d.copy(\"K\")\n assert res._ndarray.flags[\"C_CONTIGUOUS\"]\n\n res = arr2d.T.copy(\"K\")\n assert not res._ndarray.flags[\"C_CONTIGUOUS\"]\n assert res._ndarray.flags[\"F_CONTIGUOUS\"]\n\n # order not accepted by numpy\n msg = r\"order must be one of 'C', 'F', 'A', or 'K' \\(got 'Q'\\)\"\n with pytest.raises(ValueError, match=msg):\n arr2d.copy(\"Q\")\n\n # neither contiguity\n arr_nc = arr2d[::2]\n assert not arr_nc._ndarray.flags[\"C_CONTIGUOUS\"]\n assert not arr_nc._ndarray.flags[\"F_CONTIGUOUS\"]\n\n assert arr_nc.copy()._ndarray.flags[\"C_CONTIGUOUS\"]\n assert not arr_nc.copy()._ndarray.flags[\"F_CONTIGUOUS\"]\n\n assert arr_nc.copy(\"C\")._ndarray.flags[\"C_CONTIGUOUS\"]\n assert not arr_nc.copy(\"C\")._ndarray.flags[\"F_CONTIGUOUS\"]\n\n assert not arr_nc.copy(\"F\")._ndarray.flags[\"C_CONTIGUOUS\"]\n assert arr_nc.copy(\"F\")._ndarray.flags[\"F_CONTIGUOUS\"]\n\n assert arr_nc.copy(\"K\")._ndarray.flags[\"C_CONTIGUOUS\"]\n assert not arr_nc.copy(\"K\")._ndarray.flags[\"F_CONTIGUOUS\"]\n", "import numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nfrom pandas import (\n DataFrame,\n NaT,\n Series,\n Timestamp,\n date_range,\n period_range,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameValues:\n @td.skip_array_manager_invalid_test\n def test_values(self, float_frame):\n float_frame.values[:, 0] = 5.0\n assert (float_frame.values[:, 0] == 5).all()\n\n def test_more_values(self, float_string_frame):\n values = float_string_frame.values\n assert values.shape[1] == len(float_string_frame.columns)\n\n def test_values_mixed_dtypes(self, float_frame, float_string_frame):\n frame = float_frame\n arr = frame.values\n\n frame_cols = frame.columns\n for i, row in enumerate(arr):\n for j, value in enumerate(row):\n col = frame_cols[j]\n if np.isnan(value):\n assert np.isnan(frame[col][i])\n else:\n assert value == frame[col][i]\n\n # mixed type\n arr = float_string_frame[[\"foo\", \"A\"]].values\n assert arr[0, 0] == \"bar\"\n\n df = DataFrame({\"complex\": [1j, 2j, 3j], \"real\": [1, 2, 3]})\n arr = df.values\n assert arr[0, 0] == 1j\n\n def test_values_duplicates(self):\n df = DataFrame(\n [[1, 2, \"a\", \"b\"], [1, 2, \"a\", \"b\"]], columns=[\"one\", \"one\", \"two\", \"two\"]\n )\n\n result = df.values\n expected = np.array([[1, 2, \"a\", \"b\"], [1, 2, \"a\", \"b\"]], dtype=object)\n\n tm.assert_numpy_array_equal(result, expected)\n\n def test_values_with_duplicate_columns(self):\n df = DataFrame([[1, 2.5], [3, 4.5]], index=[1, 2], columns=[\"x\", \"x\"])\n result = df.values\n expected = np.array([[1, 2.5], [3, 4.5]])\n assert (result == expected).all().all()\n\n @pytest.mark.parametrize(\"constructor\", [date_range, period_range])\n def test_values_casts_datetimelike_to_object(self, constructor):\n series = Series(constructor(\"2000-01-01\", periods=10, freq=\"D\"))\n\n expected = series.astype(\"object\")\n\n df = DataFrame({\"a\": series, \"b\": np.random.randn(len(series))})\n\n result = df.values.squeeze()\n assert (result[:, 0] == expected.values).all()\n\n df = DataFrame({\"a\": series, \"b\": [\"foo\"] * len(series)})\n\n result = df.values.squeeze()\n assert (result[:, 0] == expected.values).all()\n\n def test_frame_values_with_tz(self):\n tz = \"US/Central\"\n df = DataFrame({\"A\": date_range(\"2000\", periods=4, tz=tz)})\n result = df.values\n expected = np.array(\n [\n [Timestamp(\"2000-01-01\", tz=tz)],\n [Timestamp(\"2000-01-02\", tz=tz)],\n [Timestamp(\"2000-01-03\", tz=tz)],\n [Timestamp(\"2000-01-04\", tz=tz)],\n ]\n )\n tm.assert_numpy_array_equal(result, expected)\n\n # two columns, homogeneous\n\n df[\"B\"] = df[\"A\"]\n result = df.values\n expected = np.concatenate([expected, expected], axis=1)\n tm.assert_numpy_array_equal(result, expected)\n\n # three columns, heterogeneous\n est = \"US/Eastern\"\n df[\"C\"] = df[\"A\"].dt.tz_convert(est)\n\n new = np.array(\n [\n [Timestamp(\"2000-01-01T01:00:00\", tz=est)],\n [Timestamp(\"2000-01-02T01:00:00\", tz=est)],\n [Timestamp(\"2000-01-03T01:00:00\", tz=est)],\n [Timestamp(\"2000-01-04T01:00:00\", tz=est)],\n ]\n )\n expected = np.concatenate([expected, new], axis=1)\n result = df.values\n tm.assert_numpy_array_equal(result, expected)\n\n def test_interleave_with_tzaware(self, timezone_frame):\n\n # interleave with object\n result = timezone_frame.assign(D=\"foo\").values\n expected = np.array(\n [\n [\n Timestamp(\"2013-01-01 00:00:00\"),\n Timestamp(\"2013-01-02 00:00:00\"),\n Timestamp(\"2013-01-03 00:00:00\"),\n ],\n [\n Timestamp(\"2013-01-01 00:00:00-0500\", tz=\"US/Eastern\"),\n NaT,\n Timestamp(\"2013-01-03 00:00:00-0500\", tz=\"US/Eastern\"),\n ],\n [\n Timestamp(\"2013-01-01 00:00:00+0100\", tz=\"CET\"),\n NaT,\n Timestamp(\"2013-01-03 00:00:00+0100\", tz=\"CET\"),\n ],\n [\"foo\", \"foo\", \"foo\"],\n ],\n dtype=object,\n ).T\n tm.assert_numpy_array_equal(result, expected)\n\n # interleave with only datetime64[ns]\n result = timezone_frame.values\n expected = np.array(\n [\n [\n Timestamp(\"2013-01-01 00:00:00\"),\n Timestamp(\"2013-01-02 00:00:00\"),\n Timestamp(\"2013-01-03 00:00:00\"),\n ],\n [\n Timestamp(\"2013-01-01 00:00:00-0500\", tz=\"US/Eastern\"),\n NaT,\n Timestamp(\"2013-01-03 00:00:00-0500\", tz=\"US/Eastern\"),\n ],\n [\n Timestamp(\"2013-01-01 00:00:00+0100\", tz=\"CET\"),\n NaT,\n Timestamp(\"2013-01-03 00:00:00+0100\", tz=\"CET\"),\n ],\n ],\n dtype=object,\n ).T\n tm.assert_numpy_array_equal(result, expected)\n\n def test_values_interleave_non_unique_cols(self):\n df = DataFrame(\n [[Timestamp(\"20130101\"), 3.5], [Timestamp(\"20130102\"), 4.5]],\n columns=[\"x\", \"x\"],\n index=[1, 2],\n )\n\n df_unique = df.copy()\n df_unique.columns = [\"x\", \"y\"]\n assert df_unique.values.shape == df.values.shape\n tm.assert_numpy_array_equal(df_unique.values[0], df.values[0])\n tm.assert_numpy_array_equal(df_unique.values[1], df.values[1])\n\n def test_values_numeric_cols(self, float_frame):\n float_frame[\"foo\"] = \"bar\"\n\n values = float_frame[[\"A\", \"B\", \"C\", \"D\"]].values\n assert values.dtype == np.float64\n\n def test_values_lcd(self, mixed_float_frame, mixed_int_frame):\n\n # mixed lcd\n values = mixed_float_frame[[\"A\", \"B\", \"C\", \"D\"]].values\n assert values.dtype == np.float64\n\n values = mixed_float_frame[[\"A\", \"B\", \"C\"]].values\n assert values.dtype == np.float32\n\n values = mixed_float_frame[[\"C\"]].values\n assert values.dtype == np.float16\n\n # GH#10364\n # B uint64 forces float because there are other signed int types\n values = mixed_int_frame[[\"A\", \"B\", \"C\", \"D\"]].values\n assert values.dtype == np.float64\n\n values = mixed_int_frame[[\"A\", \"D\"]].values\n assert values.dtype == np.int64\n\n # B uint64 forces float because there are other signed int types\n values = mixed_int_frame[[\"A\", \"B\", \"C\"]].values\n assert values.dtype == np.float64\n\n # as B and C are both unsigned, no forcing to float is needed\n values = mixed_int_frame[[\"B\", \"C\"]].values\n assert values.dtype == np.uint64\n\n values = mixed_int_frame[[\"A\", \"C\"]].values\n assert values.dtype == np.int32\n\n values = mixed_int_frame[[\"C\", \"D\"]].values\n assert values.dtype == np.int64\n\n values = mixed_int_frame[[\"A\"]].values\n assert values.dtype == np.int32\n\n values = mixed_int_frame[[\"C\"]].values\n assert values.dtype == np.uint8\n\n\nclass TestPrivateValues:\n @td.skip_array_manager_invalid_test\n def test_private_values_dt64tz(self):\n dta = date_range(\"2000\", periods=4, tz=\"US/Central\")._data.reshape(-1, 1)\n\n df = DataFrame(dta, columns=[\"A\"])\n tm.assert_equal(df._values, dta)\n\n # we have a view\n assert np.shares_memory(df._values._ndarray, dta._ndarray)\n\n # TimedeltaArray\n tda = dta - dta\n df2 = df - df\n tm.assert_equal(df2._values, tda)\n\n @td.skip_array_manager_invalid_test\n def test_private_values_dt64tz_multicol(self):\n dta = date_range(\"2000\", periods=8, tz=\"US/Central\")._data.reshape(-1, 2)\n\n df = DataFrame(dta, columns=[\"A\", \"B\"])\n tm.assert_equal(df._values, dta)\n\n # we have a view\n assert np.shares_memory(df._values._ndarray, dta._ndarray)\n\n # TimedeltaArray\n tda = dta - dta\n df2 = df - df\n tm.assert_equal(df2._values, tda)\n\n def test_private_values_dt64_multiblock(self, using_array_manager, request):\n if using_array_manager:\n mark = pytest.mark.xfail(reason=\"returns ndarray\")\n request.node.add_marker(mark)\n\n dta = date_range(\"2000\", periods=8)._data\n\n df = DataFrame({\"A\": dta[:4]}, copy=False)\n df[\"B\"] = dta[4:]\n\n assert len(df._mgr.arrays) == 2\n\n result = df._values\n expected = dta.reshape(2, 4).T\n tm.assert_equal(result, expected)\n", "\"\"\"See https://github.com/numpy/numpy/pull/11937.\n\n\"\"\"\nimport sys\nimport os\nimport uuid\nfrom importlib import import_module\nimport pytest\n\nimport numpy.f2py\n\nfrom numpy.testing import assert_equal\nfrom . import util\n\n\ndef setup_module():\n if not util.has_c_compiler():\n pytest.skip(\"Needs C compiler\")\n if not util.has_f77_compiler():\n pytest.skip('Needs FORTRAN 77 compiler')\n\n\n# extra_args can be a list (since gh-11937) or string.\n# also test absence of extra_args\[email protected](\n \"extra_args\", [['--noopt', '--debug'], '--noopt --debug', '']\n )\[email protected]_references(reason=\"Imported module seems never deleted.\")\ndef test_f2py_init_compile(extra_args):\n # flush through the f2py __init__ compile() function code path as a\n # crude test for input handling following migration from\n # exec_command() to subprocess.check_output() in gh-11937\n\n # the Fortran 77 syntax requires 6 spaces before any commands, but\n # more space may be added/\n fsource = \"\"\"\n integer function foo()\n foo = 10 + 5\n return\n end\n \"\"\"\n # use various helper functions in util.py to enable robust build /\n # compile and reimport cycle in test suite\n moddir = util.get_module_dir()\n modname = util.get_temp_module_name()\n\n cwd = os.getcwd()\n target = os.path.join(moddir, str(uuid.uuid4()) + '.f')\n # try running compile() with and without a source_fn provided so\n # that the code path where a temporary file for writing Fortran\n # source is created is also explored\n for source_fn in [target, None]:\n # mimic the path changing behavior used by build_module() in\n # util.py, but don't actually use build_module() because it has\n # its own invocation of subprocess that circumvents the\n # f2py.compile code block under test\n try:\n os.chdir(moddir)\n ret_val = numpy.f2py.compile(\n fsource,\n modulename=modname,\n extra_args=extra_args,\n source_fn=source_fn\n )\n finally:\n os.chdir(cwd)\n\n # check for compile success return value\n assert_equal(ret_val, 0)\n\n # we are not currently able to import the Python-Fortran\n # interface module on Windows / Appveyor, even though we do get\n # successful compilation on that platform with Python 3.x\n if sys.platform != 'win32':\n # check for sensible result of Fortran function; that means\n # we can import the module name in Python and retrieve the\n # result of the sum operation\n return_check = import_module(modname)\n calc_result = return_check.foo()\n assert_equal(calc_result, 15)\n # Removal from sys.modules, is not as such necessary. Even with\n # removal, the module (dict) stays alive.\n del sys.modules[modname]\n\n\ndef test_f2py_init_compile_failure():\n # verify an appropriate integer status value returned by\n # f2py.compile() when invalid Fortran is provided\n ret_val = numpy.f2py.compile(b\"invalid\")\n assert_equal(ret_val, 1)\n\n\ndef test_f2py_init_compile_bad_cmd():\n # verify that usage of invalid command in f2py.compile() returns\n # status value of 127 for historic consistency with exec_command()\n # error handling\n\n # patch the sys Python exe path temporarily to induce an OSError\n # downstream NOTE: how bad of an idea is this patching?\n try:\n temp = sys.executable\n sys.executable = 'does not exist'\n\n # the OSError should take precedence over invalid Fortran\n ret_val = numpy.f2py.compile(b\"invalid\")\n assert_equal(ret_val, 127)\n finally:\n sys.executable = temp\n\n\[email protected]('fsource',\n ['program test_f2py\\nend program test_f2py',\n b'program test_f2py\\nend program test_f2py',])\ndef test_compile_from_strings(tmpdir, fsource):\n # Make sure we can compile str and bytes gh-12796\n cwd = os.getcwd()\n try:\n os.chdir(str(tmpdir))\n ret_val = numpy.f2py.compile(\n fsource,\n modulename='test_compile_from_strings',\n extension='.f90')\n assert_equal(ret_val, 0)\n finally:\n os.chdir(cwd)\n", "\"\"\"Tests for Table Schema integration.\"\"\"\nfrom collections import OrderedDict\nimport json\n\nimport numpy as np\nimport pytest\n\nfrom pandas.core.dtypes.dtypes import (\n CategoricalDtype,\n DatetimeTZDtype,\n PeriodDtype,\n)\n\nimport pandas as pd\nfrom pandas import DataFrame\nimport pandas._testing as tm\n\nfrom pandas.io.json._table_schema import (\n as_json_table_type,\n build_table_schema,\n convert_json_field_to_pandas_type,\n convert_pandas_type_to_json_field,\n set_default_names,\n)\n\n\nclass TestBuildSchema:\n def setup_method(self, method):\n self.df = DataFrame(\n {\n \"A\": [1, 2, 3, 4],\n \"B\": [\"a\", \"b\", \"c\", \"c\"],\n \"C\": pd.date_range(\"2016-01-01\", freq=\"d\", periods=4),\n \"D\": pd.timedelta_range(\"1H\", periods=4, freq=\"T\"),\n },\n index=pd.Index(range(4), name=\"idx\"),\n )\n\n def test_build_table_schema(self):\n result = build_table_schema(self.df, version=False)\n expected = {\n \"fields\": [\n {\"name\": \"idx\", \"type\": \"integer\"},\n {\"name\": \"A\", \"type\": \"integer\"},\n {\"name\": \"B\", \"type\": \"string\"},\n {\"name\": \"C\", \"type\": \"datetime\"},\n {\"name\": \"D\", \"type\": \"duration\"},\n ],\n \"primaryKey\": [\"idx\"],\n }\n assert result == expected\n result = build_table_schema(self.df)\n assert \"pandas_version\" in result\n\n def test_series(self):\n s = pd.Series([1, 2, 3], name=\"foo\")\n result = build_table_schema(s, version=False)\n expected = {\n \"fields\": [\n {\"name\": \"index\", \"type\": \"integer\"},\n {\"name\": \"foo\", \"type\": \"integer\"},\n ],\n \"primaryKey\": [\"index\"],\n }\n assert result == expected\n result = build_table_schema(s)\n assert \"pandas_version\" in result\n\n def test_series_unnamed(self):\n result = build_table_schema(pd.Series([1, 2, 3]), version=False)\n expected = {\n \"fields\": [\n {\"name\": \"index\", \"type\": \"integer\"},\n {\"name\": \"values\", \"type\": \"integer\"},\n ],\n \"primaryKey\": [\"index\"],\n }\n assert result == expected\n\n def test_multiindex(self):\n df = self.df.copy()\n idx = pd.MultiIndex.from_product([(\"a\", \"b\"), (1, 2)])\n df.index = idx\n\n result = build_table_schema(df, version=False)\n expected = {\n \"fields\": [\n {\"name\": \"level_0\", \"type\": \"string\"},\n {\"name\": \"level_1\", \"type\": \"integer\"},\n {\"name\": \"A\", \"type\": \"integer\"},\n {\"name\": \"B\", \"type\": \"string\"},\n {\"name\": \"C\", \"type\": \"datetime\"},\n {\"name\": \"D\", \"type\": \"duration\"},\n ],\n \"primaryKey\": [\"level_0\", \"level_1\"],\n }\n assert result == expected\n\n df.index.names = [\"idx0\", None]\n expected[\"fields\"][0][\"name\"] = \"idx0\"\n expected[\"primaryKey\"] = [\"idx0\", \"level_1\"]\n result = build_table_schema(df, version=False)\n assert result == expected\n\n\nclass TestTableSchemaType:\n @pytest.mark.parametrize(\"int_type\", [int, np.int16, np.int32, np.int64])\n def test_as_json_table_type_int_data(self, int_type):\n int_data = [1, 2, 3]\n assert as_json_table_type(np.array(int_data, dtype=int_type).dtype) == \"integer\"\n\n @pytest.mark.parametrize(\"float_type\", [float, np.float16, np.float32, np.float64])\n def test_as_json_table_type_float_data(self, float_type):\n float_data = [1.0, 2.0, 3.0]\n assert (\n as_json_table_type(np.array(float_data, dtype=float_type).dtype) == \"number\"\n )\n\n @pytest.mark.parametrize(\"bool_type\", [bool, np.bool_])\n def test_as_json_table_type_bool_data(self, bool_type):\n bool_data = [True, False]\n assert (\n as_json_table_type(np.array(bool_data, dtype=bool_type).dtype) == \"boolean\"\n )\n\n @pytest.mark.parametrize(\n \"date_data\",\n [\n pd.to_datetime([\"2016\"]),\n pd.to_datetime([\"2016\"], utc=True),\n pd.Series(pd.to_datetime([\"2016\"])),\n pd.Series(pd.to_datetime([\"2016\"], utc=True)),\n pd.period_range(\"2016\", freq=\"A\", periods=3),\n ],\n )\n def test_as_json_table_type_date_data(self, date_data):\n assert as_json_table_type(date_data.dtype) == \"datetime\"\n\n @pytest.mark.parametrize(\"str_data\", [pd.Series([\"a\", \"b\"]), pd.Index([\"a\", \"b\"])])\n def test_as_json_table_type_string_data(self, str_data):\n assert as_json_table_type(str_data.dtype) == \"string\"\n\n @pytest.mark.parametrize(\n \"cat_data\",\n [\n pd.Categorical([\"a\"]),\n pd.Categorical([1]),\n pd.Series(pd.Categorical([1])),\n pd.CategoricalIndex([1]),\n pd.Categorical([1]),\n ],\n )\n def test_as_json_table_type_categorical_data(self, cat_data):\n assert as_json_table_type(cat_data.dtype) == \"any\"\n\n # ------\n # dtypes\n # ------\n @pytest.mark.parametrize(\"int_dtype\", [int, np.int16, np.int32, np.int64])\n def test_as_json_table_type_int_dtypes(self, int_dtype):\n assert as_json_table_type(int_dtype) == \"integer\"\n\n @pytest.mark.parametrize(\"float_dtype\", [float, np.float16, np.float32, np.float64])\n def test_as_json_table_type_float_dtypes(self, float_dtype):\n assert as_json_table_type(float_dtype) == \"number\"\n\n @pytest.mark.parametrize(\"bool_dtype\", [bool, np.bool_])\n def test_as_json_table_type_bool_dtypes(self, bool_dtype):\n assert as_json_table_type(bool_dtype) == \"boolean\"\n\n @pytest.mark.parametrize(\n \"date_dtype\",\n [\n np.datetime64,\n np.dtype(\"<M8[ns]\"),\n PeriodDtype(\"D\"),\n DatetimeTZDtype(\"ns\", \"US/Central\"),\n ],\n )\n def test_as_json_table_type_date_dtypes(self, date_dtype):\n # TODO: datedate.date? datetime.time?\n assert as_json_table_type(date_dtype) == \"datetime\"\n\n @pytest.mark.parametrize(\"td_dtype\", [np.timedelta64, np.dtype(\"<m8[ns]\")])\n def test_as_json_table_type_timedelta_dtypes(self, td_dtype):\n assert as_json_table_type(td_dtype) == \"duration\"\n\n @pytest.mark.parametrize(\"str_dtype\", [object]) # TODO(GH#14904) flesh out dtypes?\n def test_as_json_table_type_string_dtypes(self, str_dtype):\n assert as_json_table_type(str_dtype) == \"string\"\n\n def test_as_json_table_type_categorical_dtypes(self):\n assert as_json_table_type(pd.Categorical([\"a\"]).dtype) == \"any\"\n assert as_json_table_type(CategoricalDtype()) == \"any\"\n\n\nclass TestTableOrient:\n def setup_method(self, method):\n self.df = DataFrame(\n {\n \"A\": [1, 2, 3, 4],\n \"B\": [\"a\", \"b\", \"c\", \"c\"],\n \"C\": pd.date_range(\"2016-01-01\", freq=\"d\", periods=4),\n \"D\": pd.timedelta_range(\"1H\", periods=4, freq=\"T\"),\n \"E\": pd.Series(pd.Categorical([\"a\", \"b\", \"c\", \"c\"])),\n \"F\": pd.Series(pd.Categorical([\"a\", \"b\", \"c\", \"c\"], ordered=True)),\n \"G\": [1.0, 2.0, 3, 4.0],\n \"H\": pd.date_range(\"2016-01-01\", freq=\"d\", periods=4, tz=\"US/Central\"),\n },\n index=pd.Index(range(4), name=\"idx\"),\n )\n\n def test_build_series(self):\n s = pd.Series([1, 2], name=\"a\")\n s.index.name = \"id\"\n result = s.to_json(orient=\"table\", date_format=\"iso\")\n result = json.loads(result, object_pairs_hook=OrderedDict)\n\n assert \"pandas_version\" in result[\"schema\"]\n result[\"schema\"].pop(\"pandas_version\")\n\n fields = [{\"name\": \"id\", \"type\": \"integer\"}, {\"name\": \"a\", \"type\": \"integer\"}]\n\n schema = {\"fields\": fields, \"primaryKey\": [\"id\"]}\n\n expected = OrderedDict(\n [\n (\"schema\", schema),\n (\n \"data\",\n [\n OrderedDict([(\"id\", 0), (\"a\", 1)]),\n OrderedDict([(\"id\", 1), (\"a\", 2)]),\n ],\n ),\n ]\n )\n\n assert result == expected\n\n def test_read_json_from_to_json_results(self):\n # GH32383\n df = DataFrame(\n {\n \"_id\": {\"row_0\": 0},\n \"category\": {\"row_0\": \"Goods\"},\n \"recommender_id\": {\"row_0\": 3},\n \"recommender_name_jp\": {\"row_0\": \"浦田\"},\n \"recommender_name_en\": {\"row_0\": \"Urata\"},\n \"name_jp\": {\"row_0\": \"博多人形(松尾吉将まつお よしまさ)\"},\n \"name_en\": {\"row_0\": \"Hakata Dolls Matsuo\"},\n }\n )\n result1 = pd.read_json(df.to_json())\n result2 = DataFrame.from_dict(json.loads(df.to_json()))\n tm.assert_frame_equal(result1, df)\n tm.assert_frame_equal(result2, df)\n\n @pytest.mark.filterwarnings(\n \"ignore:an integer is required (got type float)*:DeprecationWarning\"\n )\n def test_to_json(self):\n df = self.df.copy()\n df.index.name = \"idx\"\n result = df.to_json(orient=\"table\", date_format=\"iso\")\n result = json.loads(result, object_pairs_hook=OrderedDict)\n\n assert \"pandas_version\" in result[\"schema\"]\n result[\"schema\"].pop(\"pandas_version\")\n\n fields = [\n {\"name\": \"idx\", \"type\": \"integer\"},\n {\"name\": \"A\", \"type\": \"integer\"},\n {\"name\": \"B\", \"type\": \"string\"},\n {\"name\": \"C\", \"type\": \"datetime\"},\n {\"name\": \"D\", \"type\": \"duration\"},\n {\n \"constraints\": {\"enum\": [\"a\", \"b\", \"c\"]},\n \"name\": \"E\",\n \"ordered\": False,\n \"type\": \"any\",\n },\n {\n \"constraints\": {\"enum\": [\"a\", \"b\", \"c\"]},\n \"name\": \"F\",\n \"ordered\": True,\n \"type\": \"any\",\n },\n {\"name\": \"G\", \"type\": \"number\"},\n {\"name\": \"H\", \"type\": \"datetime\", \"tz\": \"US/Central\"},\n ]\n\n schema = {\"fields\": fields, \"primaryKey\": [\"idx\"]}\n data = [\n OrderedDict(\n [\n (\"idx\", 0),\n (\"A\", 1),\n (\"B\", \"a\"),\n (\"C\", \"2016-01-01T00:00:00.000Z\"),\n (\"D\", \"P0DT1H0M0S\"),\n (\"E\", \"a\"),\n (\"F\", \"a\"),\n (\"G\", 1.0),\n (\"H\", \"2016-01-01T06:00:00.000Z\"),\n ]\n ),\n OrderedDict(\n [\n (\"idx\", 1),\n (\"A\", 2),\n (\"B\", \"b\"),\n (\"C\", \"2016-01-02T00:00:00.000Z\"),\n (\"D\", \"P0DT1H1M0S\"),\n (\"E\", \"b\"),\n (\"F\", \"b\"),\n (\"G\", 2.0),\n (\"H\", \"2016-01-02T06:00:00.000Z\"),\n ]\n ),\n OrderedDict(\n [\n (\"idx\", 2),\n (\"A\", 3),\n (\"B\", \"c\"),\n (\"C\", \"2016-01-03T00:00:00.000Z\"),\n (\"D\", \"P0DT1H2M0S\"),\n (\"E\", \"c\"),\n (\"F\", \"c\"),\n (\"G\", 3.0),\n (\"H\", \"2016-01-03T06:00:00.000Z\"),\n ]\n ),\n OrderedDict(\n [\n (\"idx\", 3),\n (\"A\", 4),\n (\"B\", \"c\"),\n (\"C\", \"2016-01-04T00:00:00.000Z\"),\n (\"D\", \"P0DT1H3M0S\"),\n (\"E\", \"c\"),\n (\"F\", \"c\"),\n (\"G\", 4.0),\n (\"H\", \"2016-01-04T06:00:00.000Z\"),\n ]\n ),\n ]\n expected = OrderedDict([(\"schema\", schema), (\"data\", data)])\n\n assert result == expected\n\n def test_to_json_float_index(self):\n data = pd.Series(1, index=[1.0, 2.0])\n result = data.to_json(orient=\"table\", date_format=\"iso\")\n result = json.loads(result, object_pairs_hook=OrderedDict)\n result[\"schema\"].pop(\"pandas_version\")\n\n expected = OrderedDict(\n [\n (\n \"schema\",\n {\n \"fields\": [\n {\"name\": \"index\", \"type\": \"number\"},\n {\"name\": \"values\", \"type\": \"integer\"},\n ],\n \"primaryKey\": [\"index\"],\n },\n ),\n (\n \"data\",\n [\n OrderedDict([(\"index\", 1.0), (\"values\", 1)]),\n OrderedDict([(\"index\", 2.0), (\"values\", 1)]),\n ],\n ),\n ]\n )\n\n assert result == expected\n\n def test_to_json_period_index(self):\n idx = pd.period_range(\"2016\", freq=\"Q-JAN\", periods=2)\n data = pd.Series(1, idx)\n result = data.to_json(orient=\"table\", date_format=\"iso\")\n result = json.loads(result, object_pairs_hook=OrderedDict)\n result[\"schema\"].pop(\"pandas_version\")\n\n fields = [\n {\"freq\": \"Q-JAN\", \"name\": \"index\", \"type\": \"datetime\"},\n {\"name\": \"values\", \"type\": \"integer\"},\n ]\n\n schema = {\"fields\": fields, \"primaryKey\": [\"index\"]}\n data = [\n OrderedDict([(\"index\", \"2015-11-01T00:00:00.000Z\"), (\"values\", 1)]),\n OrderedDict([(\"index\", \"2016-02-01T00:00:00.000Z\"), (\"values\", 1)]),\n ]\n expected = OrderedDict([(\"schema\", schema), (\"data\", data)])\n\n assert result == expected\n\n def test_to_json_categorical_index(self):\n data = pd.Series(1, pd.CategoricalIndex([\"a\", \"b\"]))\n result = data.to_json(orient=\"table\", date_format=\"iso\")\n result = json.loads(result, object_pairs_hook=OrderedDict)\n result[\"schema\"].pop(\"pandas_version\")\n\n expected = OrderedDict(\n [\n (\n \"schema\",\n {\n \"fields\": [\n {\n \"name\": \"index\",\n \"type\": \"any\",\n \"constraints\": {\"enum\": [\"a\", \"b\"]},\n \"ordered\": False,\n },\n {\"name\": \"values\", \"type\": \"integer\"},\n ],\n \"primaryKey\": [\"index\"],\n },\n ),\n (\n \"data\",\n [\n OrderedDict([(\"index\", \"a\"), (\"values\", 1)]),\n OrderedDict([(\"index\", \"b\"), (\"values\", 1)]),\n ],\n ),\n ]\n )\n\n assert result == expected\n\n @pytest.mark.filterwarnings(\n \"ignore:an integer is required (got type float)*:DeprecationWarning\"\n )\n def test_date_format_raises(self):\n msg = (\n \"Trying to write with `orient='table'` and `date_format='epoch'`. Table \"\n \"Schema requires dates to be formatted with `date_format='iso'`\"\n )\n with pytest.raises(ValueError, match=msg):\n self.df.to_json(orient=\"table\", date_format=\"epoch\")\n\n # others work\n self.df.to_json(orient=\"table\", date_format=\"iso\")\n self.df.to_json(orient=\"table\")\n\n def test_convert_pandas_type_to_json_field_int(self, index_or_series):\n kind = index_or_series\n data = [1, 2, 3]\n result = convert_pandas_type_to_json_field(kind(data, name=\"name\"))\n expected = {\"name\": \"name\", \"type\": \"integer\"}\n assert result == expected\n\n def test_convert_pandas_type_to_json_field_float(self, index_or_series):\n kind = index_or_series\n data = [1.0, 2.0, 3.0]\n result = convert_pandas_type_to_json_field(kind(data, name=\"name\"))\n expected = {\"name\": \"name\", \"type\": \"number\"}\n assert result == expected\n\n @pytest.mark.parametrize(\n \"dt_args,extra_exp\", [({}, {}), ({\"utc\": True}, {\"tz\": \"UTC\"})]\n )\n @pytest.mark.parametrize(\"wrapper\", [None, pd.Series])\n def test_convert_pandas_type_to_json_field_datetime(\n self, dt_args, extra_exp, wrapper\n ):\n data = [1.0, 2.0, 3.0]\n data = pd.to_datetime(data, **dt_args)\n if wrapper is pd.Series:\n data = pd.Series(data, name=\"values\")\n result = convert_pandas_type_to_json_field(data)\n expected = {\"name\": \"values\", \"type\": \"datetime\"}\n expected.update(extra_exp)\n assert result == expected\n\n def test_convert_pandas_type_to_json_period_range(self):\n arr = pd.period_range(\"2016\", freq=\"A-DEC\", periods=4)\n result = convert_pandas_type_to_json_field(arr)\n expected = {\"name\": \"values\", \"type\": \"datetime\", \"freq\": \"A-DEC\"}\n assert result == expected\n\n @pytest.mark.parametrize(\"kind\", [pd.Categorical, pd.CategoricalIndex])\n @pytest.mark.parametrize(\"ordered\", [True, False])\n def test_convert_pandas_type_to_json_field_categorical(self, kind, ordered):\n data = [\"a\", \"b\", \"c\"]\n if kind is pd.Categorical:\n arr = pd.Series(kind(data, ordered=ordered), name=\"cats\")\n elif kind is pd.CategoricalIndex:\n arr = kind(data, ordered=ordered, name=\"cats\")\n\n result = convert_pandas_type_to_json_field(arr)\n expected = {\n \"name\": \"cats\",\n \"type\": \"any\",\n \"constraints\": {\"enum\": data},\n \"ordered\": ordered,\n }\n assert result == expected\n\n @pytest.mark.parametrize(\n \"inp,exp\",\n [\n ({\"type\": \"integer\"}, \"int64\"),\n ({\"type\": \"number\"}, \"float64\"),\n ({\"type\": \"boolean\"}, \"bool\"),\n ({\"type\": \"duration\"}, \"timedelta64\"),\n ({\"type\": \"datetime\"}, \"datetime64[ns]\"),\n ({\"type\": \"datetime\", \"tz\": \"US/Hawaii\"}, \"datetime64[ns, US/Hawaii]\"),\n ({\"type\": \"any\"}, \"object\"),\n (\n {\n \"type\": \"any\",\n \"constraints\": {\"enum\": [\"a\", \"b\", \"c\"]},\n \"ordered\": False,\n },\n CategoricalDtype(categories=[\"a\", \"b\", \"c\"], ordered=False),\n ),\n (\n {\n \"type\": \"any\",\n \"constraints\": {\"enum\": [\"a\", \"b\", \"c\"]},\n \"ordered\": True,\n },\n CategoricalDtype(categories=[\"a\", \"b\", \"c\"], ordered=True),\n ),\n ({\"type\": \"string\"}, \"object\"),\n ],\n )\n def test_convert_json_field_to_pandas_type(self, inp, exp):\n field = {\"name\": \"foo\"}\n field.update(inp)\n assert convert_json_field_to_pandas_type(field) == exp\n\n @pytest.mark.parametrize(\"inp\", [\"geopoint\", \"geojson\", \"fake_type\"])\n def test_convert_json_field_to_pandas_type_raises(self, inp):\n field = {\"type\": inp}\n with pytest.raises(\n ValueError, match=f\"Unsupported or invalid field type: {inp}\"\n ):\n convert_json_field_to_pandas_type(field)\n\n def test_categorical(self):\n s = pd.Series(pd.Categorical([\"a\", \"b\", \"a\"]))\n s.index.name = \"idx\"\n result = s.to_json(orient=\"table\", date_format=\"iso\")\n result = json.loads(result, object_pairs_hook=OrderedDict)\n result[\"schema\"].pop(\"pandas_version\")\n\n fields = [\n {\"name\": \"idx\", \"type\": \"integer\"},\n {\n \"constraints\": {\"enum\": [\"a\", \"b\"]},\n \"name\": \"values\",\n \"ordered\": False,\n \"type\": \"any\",\n },\n ]\n\n expected = OrderedDict(\n [\n (\"schema\", {\"fields\": fields, \"primaryKey\": [\"idx\"]}),\n (\n \"data\",\n [\n OrderedDict([(\"idx\", 0), (\"values\", \"a\")]),\n OrderedDict([(\"idx\", 1), (\"values\", \"b\")]),\n OrderedDict([(\"idx\", 2), (\"values\", \"a\")]),\n ],\n ),\n ]\n )\n\n assert result == expected\n\n @pytest.mark.parametrize(\n \"idx,nm,prop\",\n [\n (pd.Index([1]), \"index\", \"name\"),\n (pd.Index([1], name=\"myname\"), \"myname\", \"name\"),\n (\n pd.MultiIndex.from_product([(\"a\", \"b\"), (\"c\", \"d\")]),\n [\"level_0\", \"level_1\"],\n \"names\",\n ),\n (\n pd.MultiIndex.from_product(\n [(\"a\", \"b\"), (\"c\", \"d\")], names=[\"n1\", \"n2\"]\n ),\n [\"n1\", \"n2\"],\n \"names\",\n ),\n (\n pd.MultiIndex.from_product(\n [(\"a\", \"b\"), (\"c\", \"d\")], names=[\"n1\", None]\n ),\n [\"n1\", \"level_1\"],\n \"names\",\n ),\n ],\n )\n def test_set_names_unset(self, idx, nm, prop):\n data = pd.Series(1, idx)\n result = set_default_names(data)\n assert getattr(result.index, prop) == nm\n\n @pytest.mark.parametrize(\n \"idx\",\n [\n pd.Index([], name=\"index\"),\n pd.MultiIndex.from_arrays([[\"foo\"], [\"bar\"]], names=(\"level_0\", \"level_1\")),\n pd.MultiIndex.from_arrays([[\"foo\"], [\"bar\"]], names=(\"foo\", \"level_1\")),\n ],\n )\n def test_warns_non_roundtrippable_names(self, idx):\n # GH 19130\n df = DataFrame(index=idx)\n df.index.name = \"index\"\n with tm.assert_produces_warning():\n set_default_names(df)\n\n def test_timestamp_in_columns(self):\n df = DataFrame(\n [[1, 2]], columns=[pd.Timestamp(\"2016\"), pd.Timedelta(10, unit=\"s\")]\n )\n result = df.to_json(orient=\"table\")\n js = json.loads(result)\n assert js[\"schema\"][\"fields\"][1][\"name\"] == \"2016-01-01T00:00:00.000Z\"\n assert js[\"schema\"][\"fields\"][2][\"name\"] == \"P0DT0H0M10S\"\n\n @pytest.mark.parametrize(\n \"case\",\n [\n pd.Series([1], index=pd.Index([1], name=\"a\"), name=\"a\"),\n DataFrame({\"A\": [1]}, index=pd.Index([1], name=\"A\")),\n DataFrame(\n {\"A\": [1]},\n index=pd.MultiIndex.from_arrays([[\"a\"], [1]], names=[\"A\", \"a\"]),\n ),\n ],\n )\n def test_overlapping_names(self, case):\n with pytest.raises(ValueError, match=\"Overlapping\"):\n case.to_json(orient=\"table\")\n\n def test_mi_falsey_name(self):\n # GH 16203\n df = DataFrame(\n np.random.randn(4, 4),\n index=pd.MultiIndex.from_product([(\"A\", \"B\"), (\"a\", \"b\")]),\n )\n result = [x[\"name\"] for x in build_table_schema(df)[\"fields\"]]\n assert result == [\"level_0\", \"level_1\", 0, 1, 2, 3]\n\n\nclass TestTableOrientReader:\n @pytest.mark.parametrize(\n \"index_nm\",\n [None, \"idx\", pytest.param(\"index\", marks=pytest.mark.xfail), \"level_0\"],\n )\n @pytest.mark.parametrize(\n \"vals\",\n [\n {\"ints\": [1, 2, 3, 4]},\n {\"objects\": [\"a\", \"b\", \"c\", \"d\"]},\n {\"objects\": [\"1\", \"2\", \"3\", \"4\"]},\n {\"date_ranges\": pd.date_range(\"2016-01-01\", freq=\"d\", periods=4)},\n {\"categoricals\": pd.Series(pd.Categorical([\"a\", \"b\", \"c\", \"c\"]))},\n {\n \"ordered_cats\": pd.Series(\n pd.Categorical([\"a\", \"b\", \"c\", \"c\"], ordered=True)\n )\n },\n {\"floats\": [1.0, 2.0, 3.0, 4.0]},\n {\"floats\": [1.1, 2.2, 3.3, 4.4]},\n {\"bools\": [True, False, False, True]},\n {\n \"timezones\": pd.date_range(\n \"2016-01-01\", freq=\"d\", periods=4, tz=\"US/Central\"\n ) # added in # GH 35973\n },\n ],\n )\n def test_read_json_table_orient(self, index_nm, vals, recwarn):\n df = DataFrame(vals, index=pd.Index(range(4), name=index_nm))\n out = df.to_json(orient=\"table\")\n result = pd.read_json(out, orient=\"table\")\n tm.assert_frame_equal(df, result)\n\n @pytest.mark.parametrize(\"index_nm\", [None, \"idx\", \"index\"])\n @pytest.mark.parametrize(\n \"vals\",\n [{\"timedeltas\": pd.timedelta_range(\"1H\", periods=4, freq=\"T\")}],\n )\n def test_read_json_table_orient_raises(self, index_nm, vals, recwarn):\n df = DataFrame(vals, index=pd.Index(range(4), name=index_nm))\n out = df.to_json(orient=\"table\")\n with pytest.raises(NotImplementedError, match=\"can not yet read \"):\n pd.read_json(out, orient=\"table\")\n\n @pytest.mark.parametrize(\n \"idx\",\n [\n pd.Index(range(4)),\n pd.date_range(\n \"2020-08-30\",\n freq=\"d\",\n periods=4,\n )._with_freq(None),\n pd.date_range(\n \"2020-08-30\", freq=\"d\", periods=4, tz=\"US/Central\"\n )._with_freq(None),\n pd.MultiIndex.from_product(\n [\n pd.date_range(\"2020-08-30\", freq=\"d\", periods=2, tz=\"US/Central\"),\n [\"x\", \"y\"],\n ],\n ),\n ],\n )\n @pytest.mark.parametrize(\n \"vals\",\n [\n {\"floats\": [1.1, 2.2, 3.3, 4.4]},\n {\"dates\": pd.date_range(\"2020-08-30\", freq=\"d\", periods=4)},\n {\n \"timezones\": pd.date_range(\n \"2020-08-30\", freq=\"d\", periods=4, tz=\"Europe/London\"\n )\n },\n ],\n )\n def test_read_json_table_timezones_orient(self, idx, vals, recwarn):\n # GH 35973\n df = DataFrame(vals, index=idx)\n out = df.to_json(orient=\"table\")\n result = pd.read_json(out, orient=\"table\")\n tm.assert_frame_equal(df, result)\n\n @pytest.mark.filterwarnings(\n \"ignore:an integer is required (got type float)*:DeprecationWarning\"\n )\n def test_comprehensive(self):\n df = DataFrame(\n {\n \"A\": [1, 2, 3, 4],\n \"B\": [\"a\", \"b\", \"c\", \"c\"],\n \"C\": pd.date_range(\"2016-01-01\", freq=\"d\", periods=4),\n # 'D': pd.timedelta_range('1H', periods=4, freq='T'),\n \"E\": pd.Series(pd.Categorical([\"a\", \"b\", \"c\", \"c\"])),\n \"F\": pd.Series(pd.Categorical([\"a\", \"b\", \"c\", \"c\"], ordered=True)),\n \"G\": [1.1, 2.2, 3.3, 4.4],\n \"H\": pd.date_range(\"2016-01-01\", freq=\"d\", periods=4, tz=\"US/Central\"),\n \"I\": [True, False, False, True],\n },\n index=pd.Index(range(4), name=\"idx\"),\n )\n\n out = df.to_json(orient=\"table\")\n result = pd.read_json(out, orient=\"table\")\n tm.assert_frame_equal(df, result)\n\n @pytest.mark.parametrize(\n \"index_names\",\n [[None, None], [\"foo\", \"bar\"], [\"foo\", None], [None, \"foo\"], [\"index\", \"foo\"]],\n )\n def test_multiindex(self, index_names):\n # GH 18912\n df = DataFrame(\n [[\"Arr\", \"alpha\", [1, 2, 3, 4]], [\"Bee\", \"Beta\", [10, 20, 30, 40]]],\n index=[[\"A\", \"B\"], [\"Null\", \"Eins\"]],\n columns=[\"Aussprache\", \"Griechisch\", \"Args\"],\n )\n df.index.names = index_names\n out = df.to_json(orient=\"table\")\n result = pd.read_json(out, orient=\"table\")\n tm.assert_frame_equal(df, result)\n\n def test_empty_frame_roundtrip(self):\n # GH 21287\n df = DataFrame(columns=[\"a\", \"b\", \"c\"])\n expected = df.copy()\n out = df.to_json(orient=\"table\")\n result = pd.read_json(out, orient=\"table\")\n tm.assert_frame_equal(expected, result)\n\n def test_read_json_orient_table_old_schema_version(self):\n df_json = \"\"\"\n {\n \"schema\":{\n \"fields\":[\n {\"name\":\"index\",\"type\":\"integer\"},\n {\"name\":\"a\",\"type\":\"string\"}\n ],\n \"primaryKey\":[\"index\"],\n \"pandas_version\":\"0.20.0\"\n },\n \"data\":[\n {\"index\":0,\"a\":1},\n {\"index\":1,\"a\":2.0},\n {\"index\":2,\"a\":\"s\"}\n ]\n }\n \"\"\"\n expected = DataFrame({\"a\": [1, 2.0, \"s\"]})\n result = pd.read_json(df_json, orient=\"table\")\n tm.assert_frame_equal(expected, result)\n", "import os\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n Categorical,\n DatetimeIndex,\n Interval,\n IntervalIndex,\n NaT,\n Series,\n TimedeltaIndex,\n Timestamp,\n cut,\n date_range,\n isna,\n qcut,\n timedelta_range,\n)\nimport pandas._testing as tm\nfrom pandas.api.types import CategoricalDtype as CDT\n\nfrom pandas.tseries.offsets import (\n Day,\n Nano,\n)\n\n\ndef test_qcut():\n arr = np.random.randn(1000)\n\n # We store the bins as Index that have been\n # rounded to comparisons are a bit tricky.\n labels, _ = qcut(arr, 4, retbins=True)\n ex_bins = np.quantile(arr, [0, 0.25, 0.5, 0.75, 1.0])\n\n result = labels.categories.left.values\n assert np.allclose(result, ex_bins[:-1], atol=1e-2)\n\n result = labels.categories.right.values\n assert np.allclose(result, ex_bins[1:], atol=1e-2)\n\n ex_levels = cut(arr, ex_bins, include_lowest=True)\n tm.assert_categorical_equal(labels, ex_levels)\n\n\ndef test_qcut_bounds():\n arr = np.random.randn(1000)\n\n factor = qcut(arr, 10, labels=False)\n assert len(np.unique(factor)) == 10\n\n\ndef test_qcut_specify_quantiles():\n arr = np.random.randn(100)\n factor = qcut(arr, [0, 0.25, 0.5, 0.75, 1.0])\n\n expected = qcut(arr, 4)\n tm.assert_categorical_equal(factor, expected)\n\n\ndef test_qcut_all_bins_same():\n with pytest.raises(ValueError, match=\"edges.*unique\"):\n qcut([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 3)\n\n\ndef test_qcut_include_lowest():\n values = np.arange(10)\n ii = qcut(values, 4)\n\n ex_levels = IntervalIndex(\n [\n Interval(-0.001, 2.25),\n Interval(2.25, 4.5),\n Interval(4.5, 6.75),\n Interval(6.75, 9),\n ]\n )\n tm.assert_index_equal(ii.categories, ex_levels)\n\n\ndef test_qcut_nas():\n arr = np.random.randn(100)\n arr[:20] = np.nan\n\n result = qcut(arr, 4)\n assert isna(result[:20]).all()\n\n\ndef test_qcut_index():\n result = qcut([0, 2], 2)\n intervals = [Interval(-0.001, 1), Interval(1, 2)]\n\n expected = Categorical(intervals, ordered=True)\n tm.assert_categorical_equal(result, expected)\n\n\ndef test_qcut_binning_issues(datapath):\n # see gh-1978, gh-1979\n cut_file = datapath(os.path.join(\"reshape\", \"data\", \"cut_data.csv\"))\n arr = np.loadtxt(cut_file)\n result = qcut(arr, 20)\n\n starts = []\n ends = []\n\n for lev in np.unique(result):\n s = lev.left\n e = lev.right\n assert s != e\n\n starts.append(float(s))\n ends.append(float(e))\n\n for (sp, sn), (ep, en) in zip(\n zip(starts[:-1], starts[1:]), zip(ends[:-1], ends[1:])\n ):\n assert sp < sn\n assert ep < en\n assert ep <= sn\n\n\ndef test_qcut_return_intervals():\n ser = Series([0, 1, 2, 3, 4, 5, 6, 7, 8])\n res = qcut(ser, [0, 0.333, 0.666, 1])\n\n exp_levels = np.array(\n [Interval(-0.001, 2.664), Interval(2.664, 5.328), Interval(5.328, 8)]\n )\n exp = Series(exp_levels.take([0, 0, 0, 1, 1, 1, 2, 2, 2])).astype(CDT(ordered=True))\n tm.assert_series_equal(res, exp)\n\n\[email protected](\"labels\", [\"foo\", 1, True])\ndef test_qcut_incorrect_labels(labels):\n # GH 13318\n values = range(5)\n msg = \"Bin labels must either be False, None or passed in as a list-like argument\"\n with pytest.raises(ValueError, match=msg):\n qcut(values, 4, labels=labels)\n\n\[email protected](\"labels\", [[\"a\", \"b\", \"c\"], list(range(3))])\ndef test_qcut_wrong_length_labels(labels):\n # GH 13318\n values = range(10)\n msg = \"Bin labels must be one fewer than the number of bin edges\"\n with pytest.raises(ValueError, match=msg):\n qcut(values, 4, labels=labels)\n\n\[email protected](\n \"labels, expected\",\n [\n ([\"a\", \"b\", \"c\"], Categorical([\"a\", \"b\", \"c\"], ordered=True)),\n (list(range(3)), Categorical([0, 1, 2], ordered=True)),\n ],\n)\ndef test_qcut_list_like_labels(labels, expected):\n # GH 13318\n values = range(3)\n result = qcut(values, 3, labels=labels)\n tm.assert_categorical_equal(result, expected)\n\n\[email protected](\n \"kwargs,msg\",\n [\n ({\"duplicates\": \"drop\"}, None),\n ({}, \"Bin edges must be unique\"),\n ({\"duplicates\": \"raise\"}, \"Bin edges must be unique\"),\n ({\"duplicates\": \"foo\"}, \"invalid value for 'duplicates' parameter\"),\n ],\n)\ndef test_qcut_duplicates_bin(kwargs, msg):\n # see gh-7751\n values = [0, 0, 0, 0, 1, 2, 3]\n\n if msg is not None:\n with pytest.raises(ValueError, match=msg):\n qcut(values, 3, **kwargs)\n else:\n result = qcut(values, 3, **kwargs)\n expected = IntervalIndex([Interval(-0.001, 1), Interval(1, 3)])\n tm.assert_index_equal(result.categories, expected)\n\n\[email protected](\n \"data,start,end\", [(9.0, 8.999, 9.0), (0.0, -0.001, 0.0), (-9.0, -9.001, -9.0)]\n)\[email protected](\"length\", [1, 2])\[email protected](\"labels\", [None, False])\ndef test_single_quantile(data, start, end, length, labels):\n # see gh-15431\n ser = Series([data] * length)\n result = qcut(ser, 1, labels=labels)\n\n if labels is None:\n intervals = IntervalIndex([Interval(start, end)] * length, closed=\"right\")\n expected = Series(intervals).astype(CDT(ordered=True))\n else:\n expected = Series([0] * length, dtype=np.intp)\n\n tm.assert_series_equal(result, expected)\n\n\[email protected](\n \"ser\",\n [\n Series(DatetimeIndex([\"20180101\", NaT, \"20180103\"])),\n Series(TimedeltaIndex([\"0 days\", NaT, \"2 days\"])),\n ],\n ids=lambda x: str(x.dtype),\n)\ndef test_qcut_nat(ser):\n # see gh-19768\n intervals = IntervalIndex.from_tuples(\n [(ser[0] - Nano(), ser[2] - Day()), np.nan, (ser[2] - Day(), ser[2])]\n )\n expected = Series(Categorical(intervals, ordered=True))\n\n result = qcut(ser, 2)\n tm.assert_series_equal(result, expected)\n\n\[email protected](\"bins\", [3, np.linspace(0, 1, 4)])\ndef test_datetime_tz_qcut(bins):\n # see gh-19872\n tz = \"US/Eastern\"\n ser = Series(date_range(\"20130101\", periods=3, tz=tz))\n\n result = qcut(ser, bins)\n expected = Series(\n IntervalIndex(\n [\n Interval(\n Timestamp(\"2012-12-31 23:59:59.999999999\", tz=tz),\n Timestamp(\"2013-01-01 16:00:00\", tz=tz),\n ),\n Interval(\n Timestamp(\"2013-01-01 16:00:00\", tz=tz),\n Timestamp(\"2013-01-02 08:00:00\", tz=tz),\n ),\n Interval(\n Timestamp(\"2013-01-02 08:00:00\", tz=tz),\n Timestamp(\"2013-01-03 00:00:00\", tz=tz),\n ),\n ]\n )\n ).astype(CDT(ordered=True))\n tm.assert_series_equal(result, expected)\n\n\[email protected](\n \"arg,expected_bins\",\n [\n [\n timedelta_range(\"1day\", periods=3),\n TimedeltaIndex([\"1 days\", \"2 days\", \"3 days\"]),\n ],\n [\n date_range(\"20180101\", periods=3),\n DatetimeIndex([\"2018-01-01\", \"2018-01-02\", \"2018-01-03\"]),\n ],\n ],\n)\ndef test_date_like_qcut_bins(arg, expected_bins):\n # see gh-19891\n ser = Series(arg)\n result, result_bins = qcut(ser, 2, retbins=True)\n tm.assert_index_equal(result_bins, expected_bins)\n\n\[email protected](\"bins\", [6, 7])\[email protected](\n \"box, compare\",\n [\n (Series, tm.assert_series_equal),\n (np.array, tm.assert_categorical_equal),\n (list, tm.assert_equal),\n ],\n)\ndef test_qcut_bool_coercion_to_int(bins, box, compare):\n # issue 20303\n data_expected = box([0, 1, 1, 0, 1] * 10)\n data_result = box([False, True, True, False, True] * 10)\n expected = qcut(data_expected, bins, duplicates=\"drop\")\n result = qcut(data_result, bins, duplicates=\"drop\")\n compare(result, expected)\n\n\[email protected](\"q\", [2, 5, 10])\ndef test_qcut_nullable_integer(q, any_numeric_ea_dtype):\n arr = pd.array(np.arange(100), dtype=any_numeric_ea_dtype)\n arr[::2] = pd.NA\n\n result = qcut(arr, q)\n expected = qcut(arr.astype(float), q)\n\n tm.assert_categorical_equal(result, expected)\n", "from datetime import time\nimport locale\n\nimport numpy as np\nimport pytest\n\nfrom pandas import Series\nimport pandas._testing as tm\nfrom pandas.core.tools.datetimes import to_time as to_time_alias\nfrom pandas.core.tools.times import to_time\n\nfails_on_non_english = pytest.mark.xfail(\n locale.getlocale()[0] in (\"zh_CN\", \"it_IT\"),\n reason=\"fail on a CI build with LC_ALL=zh_CN.utf8/it_IT.utf8\",\n)\n\n\nclass TestToTime:\n @pytest.mark.parametrize(\n \"time_string\",\n [\n \"14:15\",\n \"1415\",\n pytest.param(\"2:15pm\", marks=fails_on_non_english),\n pytest.param(\"0215pm\", marks=fails_on_non_english),\n \"14:15:00\",\n \"141500\",\n pytest.param(\"2:15:00pm\", marks=fails_on_non_english),\n pytest.param(\"021500pm\", marks=fails_on_non_english),\n time(14, 15),\n ],\n )\n def test_parsers_time(self, time_string):\n # GH#11818\n assert to_time(time_string) == time(14, 15)\n\n def test_odd_format(self):\n new_string = \"14.15\"\n msg = r\"Cannot convert arg \\['14\\.15'\\] to a time\"\n with pytest.raises(ValueError, match=msg):\n to_time(new_string)\n assert to_time(new_string, format=\"%H.%M\") == time(14, 15)\n\n def test_arraylike(self):\n arg = [\"14:15\", \"20:20\"]\n expected_arr = [time(14, 15), time(20, 20)]\n assert to_time(arg) == expected_arr\n assert to_time(arg, format=\"%H:%M\") == expected_arr\n assert to_time(arg, infer_time_format=True) == expected_arr\n assert to_time(arg, format=\"%I:%M%p\", errors=\"coerce\") == [None, None]\n\n res = to_time(arg, format=\"%I:%M%p\", errors=\"ignore\")\n tm.assert_numpy_array_equal(res, np.array(arg, dtype=np.object_))\n\n msg = \"Cannot convert.+to a time with given format\"\n with pytest.raises(ValueError, match=msg):\n to_time(arg, format=\"%I:%M%p\", errors=\"raise\")\n\n tm.assert_series_equal(\n to_time(Series(arg, name=\"test\")), Series(expected_arr, name=\"test\")\n )\n\n res = to_time(np.array(arg))\n assert isinstance(res, list)\n assert res == expected_arr\n\n\ndef test_to_time_alias():\n expected = time(14, 15)\n\n with tm.assert_produces_warning(FutureWarning):\n result = to_time_alias(expected)\n\n assert result == expected\n", "\"\"\"\nAn enhanced distutils, providing support for Fortran compilers, for BLAS,\nLAPACK and other common libraries for numerical computing, and more.\n\nPublic submodules are::\n\n misc_util\n system_info\n cpu_info\n log\n exec_command\n\nFor details, please see the *Packaging* and *NumPy Distutils User Guide*\nsections of the NumPy Reference Guide.\n\nFor configuring the preference for and location of libraries like BLAS and\nLAPACK, and for setting include paths and similar build options, please see\n``site.cfg.example`` in the root of the NumPy repository or sdist.\n\n\"\"\"\n\n# Must import local ccompiler ASAP in order to get\n# customized CCompiler.spawn effective.\nfrom . import ccompiler\nfrom . import unixccompiler\n\nfrom .npy_pkg_config import *\n\n# If numpy is installed, add distutils.test()\ntry:\n from . import __config__\n # Normally numpy is installed if the above import works, but an interrupted\n # in-place build could also have left a __config__.py. In that case the\n # next import may still fail, so keep it inside the try block.\n from numpy._pytesttester import PytestTester\n test = PytestTester(__name__)\n del PytestTester\nexcept ImportError:\n pass\n\n\ndef customized_fcompiler(plat=None, compiler=None):\n from numpy.distutils.fcompiler import new_fcompiler\n c = new_fcompiler(plat=plat, compiler=compiler)\n c.customize()\n return c\n\ndef customized_ccompiler(plat=None, compiler=None, verbose=1):\n c = ccompiler.new_compiler(plat=plat, compiler=compiler, verbose=verbose)\n c.customize('')\n return c\n", "\"\"\"\nexec_command\n\nImplements exec_command function that is (almost) equivalent to\ncommands.getstatusoutput function but on NT, DOS systems the\nreturned status is actually correct (though, the returned status\nvalues may be different by a factor). In addition, exec_command\ntakes keyword arguments for (re-)defining environment variables.\n\nProvides functions:\n\n exec_command --- execute command in a specified directory and\n in the modified environment.\n find_executable --- locate a command using info from environment\n variable PATH. Equivalent to posix `which`\n command.\n\nAuthor: Pearu Peterson <[email protected]>\nCreated: 11 January 2003\n\nRequires: Python 2.x\n\nSuccessfully tested on:\n\n======== ============ =================================================\nos.name sys.platform comments\n======== ============ =================================================\nposix linux2 Debian (sid) Linux, Python 2.1.3+, 2.2.3+, 2.3.3\n PyCrust 0.9.3, Idle 1.0.2\nposix linux2 Red Hat 9 Linux, Python 2.1.3, 2.2.2, 2.3.2\nposix sunos5 SunOS 5.9, Python 2.2, 2.3.2\nposix darwin Darwin 7.2.0, Python 2.3\nnt win32 Windows Me\n Python 2.3(EE), Idle 1.0, PyCrust 0.7.2\n Python 2.1.1 Idle 0.8\nnt win32 Windows 98, Python 2.1.1. Idle 0.8\nnt win32 Cygwin 98-4.10, Python 2.1.1(MSC) - echo tests\n fail i.e. redefining environment variables may\n not work. FIXED: don't use cygwin echo!\n Comment: also `cmd /c echo` will not work\n but redefining environment variables do work.\nposix cygwin Cygwin 98-4.10, Python 2.3.3(cygming special)\nnt win32 Windows XP, Python 2.3.3\n======== ============ =================================================\n\nKnown bugs:\n\n* Tests, that send messages to stderr, fail when executed from MSYS prompt\n because the messages are lost at some point.\n\n\"\"\"\n__all__ = ['exec_command', 'find_executable']\n\nimport os\nimport sys\nimport subprocess\nimport locale\nimport warnings\n\nfrom numpy.distutils.misc_util import is_sequence, make_temp_file\nfrom numpy.distutils import log\n\ndef filepath_from_subprocess_output(output):\n \"\"\"\n Convert `bytes` in the encoding used by a subprocess into a filesystem-appropriate `str`.\n\n Inherited from `exec_command`, and possibly incorrect.\n \"\"\"\n mylocale = locale.getpreferredencoding(False)\n if mylocale is None:\n mylocale = 'ascii'\n output = output.decode(mylocale, errors='replace')\n output = output.replace('\\r\\n', '\\n')\n # Another historical oddity\n if output[-1:] == '\\n':\n output = output[:-1]\n return output\n\n\ndef forward_bytes_to_stdout(val):\n \"\"\"\n Forward bytes from a subprocess call to the console, without attempting to\n decode them.\n\n The assumption is that the subprocess call already returned bytes in\n a suitable encoding.\n \"\"\"\n if hasattr(sys.stdout, 'buffer'):\n # use the underlying binary output if there is one\n sys.stdout.buffer.write(val)\n elif hasattr(sys.stdout, 'encoding'):\n # round-trip the encoding if necessary\n sys.stdout.write(val.decode(sys.stdout.encoding))\n else:\n # make a best-guess at the encoding\n sys.stdout.write(val.decode('utf8', errors='replace'))\n\n\ndef temp_file_name():\n # 2019-01-30, 1.17\n warnings.warn('temp_file_name is deprecated since NumPy v1.17, use '\n 'tempfile.mkstemp instead', DeprecationWarning, stacklevel=1)\n fo, name = make_temp_file()\n fo.close()\n return name\n\ndef get_pythonexe():\n pythonexe = sys.executable\n if os.name in ['nt', 'dos']:\n fdir, fn = os.path.split(pythonexe)\n fn = fn.upper().replace('PYTHONW', 'PYTHON')\n pythonexe = os.path.join(fdir, fn)\n assert os.path.isfile(pythonexe), '%r is not a file' % (pythonexe,)\n return pythonexe\n\ndef find_executable(exe, path=None, _cache={}):\n \"\"\"Return full path of a executable or None.\n\n Symbolic links are not followed.\n \"\"\"\n key = exe, path\n try:\n return _cache[key]\n except KeyError:\n pass\n log.debug('find_executable(%r)' % exe)\n orig_exe = exe\n\n if path is None:\n path = os.environ.get('PATH', os.defpath)\n if os.name=='posix':\n realpath = os.path.realpath\n else:\n realpath = lambda a:a\n\n if exe.startswith('\"'):\n exe = exe[1:-1]\n\n suffixes = ['']\n if os.name in ['nt', 'dos', 'os2']:\n fn, ext = os.path.splitext(exe)\n extra_suffixes = ['.exe', '.com', '.bat']\n if ext.lower() not in extra_suffixes:\n suffixes = extra_suffixes\n\n if os.path.isabs(exe):\n paths = ['']\n else:\n paths = [ os.path.abspath(p) for p in path.split(os.pathsep) ]\n\n for path in paths:\n fn = os.path.join(path, exe)\n for s in suffixes:\n f_ext = fn+s\n if not os.path.islink(f_ext):\n f_ext = realpath(f_ext)\n if os.path.isfile(f_ext) and os.access(f_ext, os.X_OK):\n log.info('Found executable %s' % f_ext)\n _cache[key] = f_ext\n return f_ext\n\n log.warn('Could not locate executable %s' % orig_exe)\n return None\n\n############################################################\n\ndef _preserve_environment( names ):\n log.debug('_preserve_environment(%r)' % (names))\n env = {name: os.environ.get(name) for name in names}\n return env\n\ndef _update_environment( **env ):\n log.debug('_update_environment(...)')\n for name, value in env.items():\n os.environ[name] = value or ''\n\ndef exec_command(command, execute_in='', use_shell=None, use_tee=None,\n _with_python = 1, **env ):\n \"\"\"\n Return (status,output) of executed command.\n\n .. deprecated:: 1.17\n Use subprocess.Popen instead\n\n Parameters\n ----------\n command : str\n A concatenated string of executable and arguments.\n execute_in : str\n Before running command ``cd execute_in`` and after ``cd -``.\n use_shell : {bool, None}, optional\n If True, execute ``sh -c command``. Default None (True)\n use_tee : {bool, None}, optional\n If True use tee. Default None (True)\n\n\n Returns\n -------\n res : str\n Both stdout and stderr messages.\n\n Notes\n -----\n On NT, DOS systems the returned status is correct for external commands.\n Wild cards will not work for non-posix systems or when use_shell=0.\n\n \"\"\"\n # 2019-01-30, 1.17\n warnings.warn('exec_command is deprecated since NumPy v1.17, use '\n 'subprocess.Popen instead', DeprecationWarning, stacklevel=1)\n log.debug('exec_command(%r,%s)' % (command,\n ','.join(['%s=%r'%kv for kv in env.items()])))\n\n if use_tee is None:\n use_tee = os.name=='posix'\n if use_shell is None:\n use_shell = os.name=='posix'\n execute_in = os.path.abspath(execute_in)\n oldcwd = os.path.abspath(os.getcwd())\n\n if __name__[-12:] == 'exec_command':\n exec_dir = os.path.dirname(os.path.abspath(__file__))\n elif os.path.isfile('exec_command.py'):\n exec_dir = os.path.abspath('.')\n else:\n exec_dir = os.path.abspath(sys.argv[0])\n if os.path.isfile(exec_dir):\n exec_dir = os.path.dirname(exec_dir)\n\n if oldcwd!=execute_in:\n os.chdir(execute_in)\n log.debug('New cwd: %s' % execute_in)\n else:\n log.debug('Retaining cwd: %s' % oldcwd)\n\n oldenv = _preserve_environment( list(env.keys()) )\n _update_environment( **env )\n\n try:\n st = _exec_command(command,\n use_shell=use_shell,\n use_tee=use_tee,\n **env)\n finally:\n if oldcwd!=execute_in:\n os.chdir(oldcwd)\n log.debug('Restored cwd to %s' % oldcwd)\n _update_environment(**oldenv)\n\n return st\n\n\ndef _exec_command(command, use_shell=None, use_tee = None, **env):\n \"\"\"\n Internal workhorse for exec_command().\n \"\"\"\n if use_shell is None:\n use_shell = os.name=='posix'\n if use_tee is None:\n use_tee = os.name=='posix'\n\n if os.name == 'posix' and use_shell:\n # On POSIX, subprocess always uses /bin/sh, override\n sh = os.environ.get('SHELL', '/bin/sh')\n if is_sequence(command):\n command = [sh, '-c', ' '.join(command)]\n else:\n command = [sh, '-c', command]\n use_shell = False\n\n elif os.name == 'nt' and is_sequence(command):\n # On Windows, join the string for CreateProcess() ourselves as\n # subprocess does it a bit differently\n command = ' '.join(_quote_arg(arg) for arg in command)\n\n # Inherit environment by default\n env = env or None\n try:\n # universal_newlines is set to False so that communicate()\n # will return bytes. We need to decode the output ourselves\n # so that Python will not raise a UnicodeDecodeError when\n # it encounters an invalid character; rather, we simply replace it\n proc = subprocess.Popen(command, shell=use_shell, env=env,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n universal_newlines=False)\n except OSError:\n # Return 127, as os.spawn*() and /bin/sh do\n return 127, ''\n\n text, err = proc.communicate()\n mylocale = locale.getpreferredencoding(False)\n if mylocale is None:\n mylocale = 'ascii'\n text = text.decode(mylocale, errors='replace')\n text = text.replace('\\r\\n', '\\n')\n # Another historical oddity\n if text[-1:] == '\\n':\n text = text[:-1]\n\n if use_tee and text:\n print(text)\n return proc.returncode, text\n\n\ndef _quote_arg(arg):\n \"\"\"\n Quote the argument for safe use in a shell command line.\n \"\"\"\n # If there is a quote in the string, assume relevants parts of the\n # string are already quoted (e.g. '-I\"C:\\\\Program Files\\\\...\"')\n if '\"' not in arg and ' ' in arg:\n return '\"%s\"' % arg\n return arg\n\n############################################################\n", "# Author: Vlad Niculae\n# License: BSD 3 clause\n\nimport sys\nimport pytest\n\nimport numpy as np\n\nfrom sklearn.utils._testing import assert_array_almost_equal\nfrom sklearn.utils._testing import assert_allclose\nfrom sklearn.utils._testing import if_safe_multiprocessing_with_blas\n\nfrom sklearn.decomposition import SparsePCA, MiniBatchSparsePCA, PCA\nfrom sklearn.utils import check_random_state\n\n\ndef generate_toy_data(n_components, n_samples, image_size, random_state=None):\n n_features = image_size[0] * image_size[1]\n\n rng = check_random_state(random_state)\n U = rng.randn(n_samples, n_components)\n V = rng.randn(n_components, n_features)\n\n centers = [(3, 3), (6, 7), (8, 1)]\n sz = [1, 2, 1]\n for k in range(n_components):\n img = np.zeros(image_size)\n xmin, xmax = centers[k][0] - sz[k], centers[k][0] + sz[k]\n ymin, ymax = centers[k][1] - sz[k], centers[k][1] + sz[k]\n img[xmin:xmax][:, ymin:ymax] = 1.0\n V[k, :] = img.ravel()\n\n # Y is defined by : Y = UV + noise\n Y = np.dot(U, V)\n Y += 0.1 * rng.randn(Y.shape[0], Y.shape[1]) # Add noise\n return Y, U, V\n\n\n# SparsePCA can be a bit slow. To avoid having test times go up, we\n# test different aspects of the code in the same test\n\n\ndef test_correct_shapes():\n rng = np.random.RandomState(0)\n X = rng.randn(12, 10)\n spca = SparsePCA(n_components=8, random_state=rng)\n U = spca.fit_transform(X)\n assert spca.components_.shape == (8, 10)\n assert U.shape == (12, 8)\n # test overcomplete decomposition\n spca = SparsePCA(n_components=13, random_state=rng)\n U = spca.fit_transform(X)\n assert spca.components_.shape == (13, 10)\n assert U.shape == (12, 13)\n\n\ndef test_fit_transform():\n alpha = 1\n rng = np.random.RandomState(0)\n Y, _, _ = generate_toy_data(3, 10, (8, 8), random_state=rng) # wide array\n spca_lars = SparsePCA(n_components=3, method=\"lars\", alpha=alpha, random_state=0)\n spca_lars.fit(Y)\n\n # Test that CD gives similar results\n spca_lasso = SparsePCA(n_components=3, method=\"cd\", random_state=0, alpha=alpha)\n spca_lasso.fit(Y)\n assert_array_almost_equal(spca_lasso.components_, spca_lars.components_)\n\n\n@if_safe_multiprocessing_with_blas\ndef test_fit_transform_parallel():\n alpha = 1\n rng = np.random.RandomState(0)\n Y, _, _ = generate_toy_data(3, 10, (8, 8), random_state=rng) # wide array\n spca_lars = SparsePCA(n_components=3, method=\"lars\", alpha=alpha, random_state=0)\n spca_lars.fit(Y)\n U1 = spca_lars.transform(Y)\n # Test multiple CPUs\n spca = SparsePCA(\n n_components=3, n_jobs=2, method=\"lars\", alpha=alpha, random_state=0\n ).fit(Y)\n U2 = spca.transform(Y)\n assert not np.all(spca_lars.components_ == 0)\n assert_array_almost_equal(U1, U2)\n\n\ndef test_transform_nan():\n # Test that SparsePCA won't return NaN when there is 0 feature in all\n # samples.\n rng = np.random.RandomState(0)\n Y, _, _ = generate_toy_data(3, 10, (8, 8), random_state=rng) # wide array\n Y[:, 0] = 0\n estimator = SparsePCA(n_components=8)\n assert not np.any(np.isnan(estimator.fit_transform(Y)))\n\n\ndef test_fit_transform_tall():\n rng = np.random.RandomState(0)\n Y, _, _ = generate_toy_data(3, 65, (8, 8), random_state=rng) # tall array\n spca_lars = SparsePCA(n_components=3, method=\"lars\", random_state=rng)\n U1 = spca_lars.fit_transform(Y)\n spca_lasso = SparsePCA(n_components=3, method=\"cd\", random_state=rng)\n U2 = spca_lasso.fit(Y).transform(Y)\n assert_array_almost_equal(U1, U2)\n\n\ndef test_initialization():\n rng = np.random.RandomState(0)\n U_init = rng.randn(5, 3)\n V_init = rng.randn(3, 4)\n model = SparsePCA(\n n_components=3, U_init=U_init, V_init=V_init, max_iter=0, random_state=rng\n )\n model.fit(rng.randn(5, 4))\n assert_allclose(model.components_, V_init / np.linalg.norm(V_init, axis=1)[:, None])\n\n\ndef test_mini_batch_correct_shapes():\n rng = np.random.RandomState(0)\n X = rng.randn(12, 10)\n pca = MiniBatchSparsePCA(n_components=8, random_state=rng)\n U = pca.fit_transform(X)\n assert pca.components_.shape == (8, 10)\n assert U.shape == (12, 8)\n # test overcomplete decomposition\n pca = MiniBatchSparsePCA(n_components=13, random_state=rng)\n U = pca.fit_transform(X)\n assert pca.components_.shape == (13, 10)\n assert U.shape == (12, 13)\n\n\n# XXX: test always skipped\[email protected](True, reason=\"skipping mini_batch_fit_transform.\")\ndef test_mini_batch_fit_transform():\n alpha = 1\n rng = np.random.RandomState(0)\n Y, _, _ = generate_toy_data(3, 10, (8, 8), random_state=rng) # wide array\n spca_lars = MiniBatchSparsePCA(n_components=3, random_state=0, alpha=alpha).fit(Y)\n U1 = spca_lars.transform(Y)\n # Test multiple CPUs\n if sys.platform == \"win32\": # fake parallelism for win32\n import joblib\n\n _mp = joblib.parallel.multiprocessing\n joblib.parallel.multiprocessing = None\n try:\n spca = MiniBatchSparsePCA(\n n_components=3, n_jobs=2, alpha=alpha, random_state=0\n )\n U2 = spca.fit(Y).transform(Y)\n finally:\n joblib.parallel.multiprocessing = _mp\n else: # we can efficiently use parallelism\n spca = MiniBatchSparsePCA(n_components=3, n_jobs=2, alpha=alpha, random_state=0)\n U2 = spca.fit(Y).transform(Y)\n assert not np.all(spca_lars.components_ == 0)\n assert_array_almost_equal(U1, U2)\n # Test that CD gives similar results\n spca_lasso = MiniBatchSparsePCA(\n n_components=3, method=\"cd\", alpha=alpha, random_state=0\n ).fit(Y)\n assert_array_almost_equal(spca_lasso.components_, spca_lars.components_)\n\n\ndef test_scaling_fit_transform():\n alpha = 1\n rng = np.random.RandomState(0)\n Y, _, _ = generate_toy_data(3, 1000, (8, 8), random_state=rng)\n spca_lars = SparsePCA(n_components=3, method=\"lars\", alpha=alpha, random_state=rng)\n results_train = spca_lars.fit_transform(Y)\n results_test = spca_lars.transform(Y[:10])\n assert_allclose(results_train[0], results_test[0])\n\n\ndef test_pca_vs_spca():\n rng = np.random.RandomState(0)\n Y, _, _ = generate_toy_data(3, 1000, (8, 8), random_state=rng)\n Z, _, _ = generate_toy_data(3, 10, (8, 8), random_state=rng)\n spca = SparsePCA(alpha=0, ridge_alpha=0, n_components=2)\n pca = PCA(n_components=2)\n pca.fit(Y)\n spca.fit(Y)\n results_test_pca = pca.transform(Z)\n results_test_spca = spca.transform(Z)\n assert_allclose(\n np.abs(spca.components_.dot(pca.components_.T)), np.eye(2), atol=1e-5\n )\n results_test_pca *= np.sign(results_test_pca[0, :])\n results_test_spca *= np.sign(results_test_spca[0, :])\n assert_allclose(results_test_pca, results_test_spca)\n\n\[email protected](\"SPCA\", [SparsePCA, MiniBatchSparsePCA])\[email protected](\"n_components\", [None, 3])\ndef test_spca_n_components_(SPCA, n_components):\n rng = np.random.RandomState(0)\n n_samples, n_features = 12, 10\n X = rng.randn(n_samples, n_features)\n\n model = SPCA(n_components=n_components).fit(X)\n\n if n_components is not None:\n assert model.n_components_ == n_components\n else:\n assert model.n_components_ == n_features\n", "import re\nimport warnings\n\nimport pytest\n\nfrom pandas import DataFrame\nimport pandas._testing as tm\n\nfrom pandas.io.excel import ExcelWriter\n\nxlsxwriter = pytest.importorskip(\"xlsxwriter\")\n\npytestmark = pytest.mark.parametrize(\"ext\", [\".xlsx\"])\n\n\ndef test_column_format(ext):\n # Test that column formats are applied to cells. Test for issue #9167.\n # Applicable to xlsxwriter only.\n with warnings.catch_warnings():\n # Ignore the openpyxl lxml warning.\n warnings.simplefilter(\"ignore\")\n openpyxl = pytest.importorskip(\"openpyxl\")\n\n with tm.ensure_clean(ext) as path:\n frame = DataFrame({\"A\": [123456, 123456], \"B\": [123456, 123456]})\n\n with ExcelWriter(path) as writer:\n frame.to_excel(writer)\n\n # Add a number format to col B and ensure it is applied to cells.\n num_format = \"#,##0\"\n write_workbook = writer.book\n write_worksheet = write_workbook.worksheets()[0]\n col_format = write_workbook.add_format({\"num_format\": num_format})\n write_worksheet.set_column(\"B:B\", None, col_format)\n\n read_workbook = openpyxl.load_workbook(path)\n try:\n read_worksheet = read_workbook[\"Sheet1\"]\n except TypeError:\n # compat\n read_worksheet = read_workbook.get_sheet_by_name(name=\"Sheet1\")\n\n # Get the number format from the cell.\n try:\n cell = read_worksheet[\"B2\"]\n except TypeError:\n # compat\n cell = read_worksheet.cell(\"B2\")\n\n try:\n read_num_format = cell.number_format\n except AttributeError:\n read_num_format = cell.style.number_format._format_code\n\n assert read_num_format == num_format\n\n\ndef test_write_append_mode_raises(ext):\n msg = \"Append mode is not supported with xlsxwriter!\"\n\n with tm.ensure_clean(ext) as f:\n with pytest.raises(ValueError, match=msg):\n ExcelWriter(f, engine=\"xlsxwriter\", mode=\"a\")\n\n\[email protected](\"nan_inf_to_errors\", [True, False])\ndef test_kwargs(ext, nan_inf_to_errors):\n # GH 42286\n kwargs = {\"options\": {\"nan_inf_to_errors\": nan_inf_to_errors}}\n with tm.ensure_clean(ext) as f:\n msg = re.escape(\"Use of **kwargs is deprecated\")\n with tm.assert_produces_warning(FutureWarning, match=msg):\n with ExcelWriter(f, engine=\"xlsxwriter\", **kwargs) as writer:\n assert writer.book.nan_inf_to_errors == nan_inf_to_errors\n\n\[email protected](\"nan_inf_to_errors\", [True, False])\ndef test_engine_kwargs(ext, nan_inf_to_errors):\n # GH 42286\n engine_kwargs = {\"options\": {\"nan_inf_to_errors\": nan_inf_to_errors}}\n with tm.ensure_clean(ext) as f:\n with ExcelWriter(f, engine=\"xlsxwriter\", engine_kwargs=engine_kwargs) as writer:\n assert writer.book.nan_inf_to_errors == nan_inf_to_errors\n", "import numpy as np\nimport pytest\n\nfrom pandas import (\n CategoricalIndex,\n DataFrame,\n Index,\n MultiIndex,\n Series,\n)\nimport pandas._testing as tm\n\n\[email protected]\ndef education_df():\n return DataFrame(\n {\n \"gender\": [\"male\", \"male\", \"female\", \"male\", \"female\", \"male\"],\n \"education\": [\"low\", \"medium\", \"high\", \"low\", \"high\", \"low\"],\n \"country\": [\"US\", \"FR\", \"US\", \"FR\", \"FR\", \"FR\"],\n }\n )\n\n\ndef test_axis(education_df):\n gp = education_df.groupby(\"country\", axis=1)\n with pytest.raises(NotImplementedError, match=\"axis\"):\n gp.value_counts()\n\n\ndef test_bad_subset(education_df):\n gp = education_df.groupby(\"country\")\n with pytest.raises(ValueError, match=\"subset\"):\n gp.value_counts(subset=[\"country\"])\n\n\ndef test_basic(education_df):\n # gh43564\n result = education_df.groupby(\"country\")[[\"gender\", \"education\"]].value_counts(\n normalize=True\n )\n expected = Series(\n data=[0.5, 0.25, 0.25, 0.5, 0.5],\n index=MultiIndex.from_tuples(\n [\n (\"FR\", \"male\", \"low\"),\n (\"FR\", \"female\", \"high\"),\n (\"FR\", \"male\", \"medium\"),\n (\"US\", \"female\", \"high\"),\n (\"US\", \"male\", \"low\"),\n ],\n names=[\"country\", \"gender\", \"education\"],\n ),\n )\n tm.assert_series_equal(result, expected)\n\n\ndef _frame_value_counts(df, keys, normalize, sort, ascending):\n return df[keys].value_counts(normalize=normalize, sort=sort, ascending=ascending)\n\n\[email protected](\"groupby\", [\"column\", \"array\", \"function\"])\[email protected](\"normalize\", [True, False])\[email protected](\n \"sort, ascending\",\n [\n (False, None),\n (True, True),\n (True, False),\n ],\n)\[email protected](\"as_index\", [True, False])\[email protected](\"frame\", [True, False])\ndef test_against_frame_and_seriesgroupby(\n education_df, groupby, normalize, sort, ascending, as_index, frame\n):\n # test all parameters:\n # - Use column, array or function as by= parameter\n # - Whether or not to normalize\n # - Whether or not to sort and how\n # - Whether or not to use the groupby as an index\n # - 3-way compare against:\n # - apply with :meth:`~DataFrame.value_counts`\n # - `~SeriesGroupBy.value_counts`\n by = {\n \"column\": \"country\",\n \"array\": education_df[\"country\"].values,\n \"function\": lambda x: education_df[\"country\"][x] == \"US\",\n }[groupby]\n\n gp = education_df.groupby(by=by, as_index=as_index)\n result = gp[[\"gender\", \"education\"]].value_counts(\n normalize=normalize, sort=sort, ascending=ascending\n )\n if frame:\n # compare against apply with DataFrame value_counts\n expected = gp.apply(\n _frame_value_counts, [\"gender\", \"education\"], normalize, sort, ascending\n )\n\n if as_index:\n tm.assert_series_equal(result, expected)\n else:\n name = \"proportion\" if normalize else \"count\"\n expected = expected.reset_index().rename({0: name}, axis=1)\n if groupby == \"column\":\n expected = expected.rename({\"level_0\": \"country\"}, axis=1)\n expected[\"country\"] = np.where(expected[\"country\"], \"US\", \"FR\")\n elif groupby == \"function\":\n expected[\"level_0\"] = expected[\"level_0\"] == 1\n else:\n expected[\"level_0\"] = np.where(expected[\"level_0\"], \"US\", \"FR\")\n tm.assert_frame_equal(result, expected)\n else:\n # compare against SeriesGroupBy value_counts\n education_df[\"both\"] = education_df[\"gender\"] + \"-\" + education_df[\"education\"]\n expected = gp[\"both\"].value_counts(\n normalize=normalize, sort=sort, ascending=ascending\n )\n expected.name = None\n if as_index:\n index_frame = expected.index.to_frame(index=False)\n index_frame[\"gender\"] = index_frame[\"both\"].str.split(\"-\").str.get(0)\n index_frame[\"education\"] = index_frame[\"both\"].str.split(\"-\").str.get(1)\n del index_frame[\"both\"]\n index_frame = index_frame.rename({0: None}, axis=1)\n expected.index = MultiIndex.from_frame(index_frame)\n tm.assert_series_equal(result, expected)\n else:\n expected.insert(1, \"gender\", expected[\"both\"].str.split(\"-\").str.get(0))\n expected.insert(2, \"education\", expected[\"both\"].str.split(\"-\").str.get(1))\n del expected[\"both\"]\n tm.assert_frame_equal(result, expected)\n\n\[email protected](\"normalize\", [True, False])\[email protected](\n \"sort, ascending, expected_rows, expected_count, expected_group_size\",\n [\n (False, None, [0, 1, 2, 3, 4], [1, 1, 1, 2, 1], [1, 3, 1, 3, 1]),\n (True, False, [4, 3, 1, 2, 0], [1, 2, 1, 1, 1], [1, 3, 3, 1, 1]),\n (True, True, [4, 1, 3, 2, 0], [1, 1, 2, 1, 1], [1, 3, 3, 1, 1]),\n ],\n)\ndef test_compound(\n education_df,\n normalize,\n sort,\n ascending,\n expected_rows,\n expected_count,\n expected_group_size,\n):\n # Multiple groupby keys and as_index=False\n gp = education_df.groupby([\"country\", \"gender\"], as_index=False, sort=False)\n result = gp[\"education\"].value_counts(\n normalize=normalize, sort=sort, ascending=ascending\n )\n expected = DataFrame()\n for column in [\"country\", \"gender\", \"education\"]:\n expected[column] = [education_df[column][row] for row in expected_rows]\n if normalize:\n expected[\"proportion\"] = expected_count\n expected[\"proportion\"] /= expected_group_size\n else:\n expected[\"count\"] = expected_count\n tm.assert_frame_equal(result, expected)\n\n\[email protected]\ndef animals_df():\n return DataFrame(\n {\"key\": [1, 1, 1, 1], \"num_legs\": [2, 4, 4, 6], \"num_wings\": [2, 0, 0, 0]},\n index=[\"falcon\", \"dog\", \"cat\", \"ant\"],\n )\n\n\[email protected](\n \"sort, ascending, normalize, expected_data, expected_index\",\n [\n (False, None, False, [1, 2, 1], [(1, 1, 1), (2, 4, 6), (2, 0, 0)]),\n (True, True, False, [1, 1, 2], [(1, 1, 1), (2, 6, 4), (2, 0, 0)]),\n (True, False, False, [2, 1, 1], [(1, 1, 1), (4, 2, 6), (0, 2, 0)]),\n (True, False, True, [0.5, 0.25, 0.25], [(1, 1, 1), (4, 2, 6), (0, 2, 0)]),\n ],\n)\ndef test_data_frame_value_counts(\n animals_df, sort, ascending, normalize, expected_data, expected_index\n):\n # 3-way compare with :meth:`~DataFrame.value_counts`\n # Tests from frame/methods/test_value_counts.py\n result_frame = animals_df.value_counts(\n sort=sort, ascending=ascending, normalize=normalize\n )\n expected = Series(\n data=expected_data,\n index=MultiIndex.from_arrays(\n expected_index, names=[\"key\", \"num_legs\", \"num_wings\"]\n ),\n )\n tm.assert_series_equal(result_frame, expected)\n\n result_frame_groupby = animals_df.groupby(\"key\").value_counts(\n sort=sort, ascending=ascending, normalize=normalize\n )\n\n tm.assert_series_equal(result_frame_groupby, expected)\n\n\[email protected]\ndef nulls_df():\n n = np.nan\n return DataFrame(\n {\n \"A\": [1, 1, n, 4, n, 6, 6, 6, 6],\n \"B\": [1, 1, 3, n, n, 6, 6, 6, 6],\n \"C\": [1, 2, 3, 4, 5, 6, n, 8, n],\n \"D\": [1, 2, 3, 4, 5, 6, 7, n, n],\n }\n )\n\n\[email protected](\n \"group_dropna, count_dropna, expected_rows, expected_values\",\n [\n (\n False,\n False,\n [0, 1, 3, 5, 7, 6, 8, 2, 4],\n [0.5, 0.5, 1.0, 0.25, 0.25, 0.25, 0.25, 1.0, 1.0],\n ),\n (False, True, [0, 1, 3, 5, 2, 4], [0.5, 0.5, 1.0, 1.0, 1.0, 1.0]),\n (True, False, [0, 1, 5, 7, 6, 8], [0.5, 0.5, 0.25, 0.25, 0.25, 0.25]),\n (True, True, [0, 1, 5], [0.5, 0.5, 1.0]),\n ],\n)\ndef test_dropna_combinations(\n nulls_df, group_dropna, count_dropna, expected_rows, expected_values\n):\n gp = nulls_df.groupby([\"A\", \"B\"], dropna=group_dropna)\n result = gp.value_counts(normalize=True, sort=True, dropna=count_dropna)\n columns = DataFrame()\n for column in nulls_df.columns:\n columns[column] = [nulls_df[column][row] for row in expected_rows]\n index = MultiIndex.from_frame(columns)\n expected = Series(data=expected_values, index=index)\n tm.assert_series_equal(result, expected)\n\n\[email protected]\ndef names_with_nulls_df(nulls_fixture):\n return DataFrame(\n {\n \"key\": [1, 1, 1, 1],\n \"first_name\": [\"John\", \"Anne\", \"John\", \"Beth\"],\n \"middle_name\": [\"Smith\", nulls_fixture, nulls_fixture, \"Louise\"],\n },\n )\n\n\[email protected](\n \"dropna, expected_data, expected_index\",\n [\n (\n True,\n [1, 1],\n MultiIndex.from_arrays(\n [(1, 1), (\"Beth\", \"John\"), (\"Louise\", \"Smith\")],\n names=[\"key\", \"first_name\", \"middle_name\"],\n ),\n ),\n (\n False,\n [1, 1, 1, 1],\n MultiIndex(\n levels=[\n Index([1]),\n Index([\"Anne\", \"Beth\", \"John\"]),\n Index([\"Louise\", \"Smith\", np.nan]),\n ],\n codes=[[0, 0, 0, 0], [0, 1, 2, 2], [2, 0, 1, 2]],\n names=[\"key\", \"first_name\", \"middle_name\"],\n ),\n ),\n ],\n)\[email protected](\"normalize\", [False, True])\ndef test_data_frame_value_counts_dropna(\n names_with_nulls_df, dropna, normalize, expected_data, expected_index\n):\n # GH 41334\n # 3-way compare with :meth:`~DataFrame.value_counts`\n # Tests with nulls from frame/methods/test_value_counts.py\n result_frame = names_with_nulls_df.value_counts(dropna=dropna, normalize=normalize)\n expected = Series(\n data=expected_data,\n index=expected_index,\n )\n if normalize:\n expected /= float(len(expected_data))\n\n tm.assert_series_equal(result_frame, expected)\n\n result_frame_groupby = names_with_nulls_df.groupby(\"key\").value_counts(\n dropna=dropna, normalize=normalize\n )\n\n tm.assert_series_equal(result_frame_groupby, expected)\n\n\[email protected](\"as_index\", [False, True])\[email protected](\n \"observed, expected_index\",\n [\n (\n False,\n [\n (\"FR\", \"male\", \"low\"),\n (\"FR\", \"female\", \"high\"),\n (\"FR\", \"male\", \"medium\"),\n (\"FR\", \"female\", \"low\"),\n (\"FR\", \"female\", \"medium\"),\n (\"FR\", \"male\", \"high\"),\n (\"US\", \"female\", \"high\"),\n (\"US\", \"male\", \"low\"),\n (\"US\", \"female\", \"low\"),\n (\"US\", \"female\", \"medium\"),\n (\"US\", \"male\", \"high\"),\n (\"US\", \"male\", \"medium\"),\n ],\n ),\n (\n True,\n [\n (\"FR\", \"male\", \"low\"),\n (\"FR\", \"female\", \"high\"),\n (\"FR\", \"male\", \"medium\"),\n (\"US\", \"female\", \"high\"),\n (\"US\", \"male\", \"low\"),\n ],\n ),\n ],\n)\[email protected](\n \"normalize, expected_data\",\n [\n (False, np.array([2, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0], dtype=np.int64)),\n (\n True,\n np.array([0.5, 0.25, 0.25, 0.0, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0]),\n ),\n ],\n)\ndef test_categorical(\n education_df, as_index, observed, expected_index, normalize, expected_data\n):\n # Test categorical data whether or not observed\n gp = education_df.astype(\"category\").groupby(\n \"country\", as_index=as_index, observed=observed\n )\n result = gp.value_counts(normalize=normalize)\n\n expected_series = Series(\n data=expected_data[expected_data > 0.0] if observed else expected_data,\n index=MultiIndex.from_tuples(\n expected_index,\n names=[\"country\", \"gender\", \"education\"],\n ),\n )\n for i in range(3):\n expected_series.index = expected_series.index.set_levels(\n CategoricalIndex(expected_series.index.levels[i]), level=i\n )\n\n if as_index:\n tm.assert_series_equal(result, expected_series)\n else:\n expected = expected_series.reset_index(\n name=\"proportion\" if normalize else \"count\"\n )\n tm.assert_frame_equal(result, expected)\n\n\[email protected](\n \"normalize, expected_label, expected_values\",\n [\n (False, \"count\", [1, 1, 1]),\n (True, \"proportion\", [0.5, 0.5, 1.0]),\n ],\n)\ndef test_mixed_groupings(normalize, expected_label, expected_values):\n # Test multiple groupings\n df = DataFrame({\"A\": [1, 2, 1], \"B\": [1, 2, 3]})\n gp = df.groupby([[4, 5, 4], \"A\", lambda i: 7 if i == 1 else 8], as_index=False)\n result = gp.value_counts(sort=True, normalize=normalize)\n expected = DataFrame(\n {\n \"level_0\": [4, 4, 5],\n \"A\": [1, 1, 2],\n \"level_2\": [8, 8, 7],\n \"B\": [1, 3, 2],\n expected_label: expected_values,\n }\n )\n tm.assert_frame_equal(result, expected)\n\n\[email protected](\n \"test, expected_names\",\n [\n (\"repeat\", [\"a\", None, \"d\", \"b\", \"b\", \"e\"]),\n (\"level\", [\"a\", None, \"d\", \"b\", \"c\", \"level_1\"]),\n ],\n)\[email protected](\"as_index\", [False, True])\ndef test_column_name_clashes(test, expected_names, as_index):\n df = DataFrame({\"a\": [1, 2], \"b\": [3, 4], \"c\": [5, 6], \"d\": [7, 8], \"e\": [9, 10]})\n if test == \"repeat\":\n df.columns = list(\"abbde\")\n else:\n df.columns = list(\"abcd\") + [\"level_1\"]\n\n if as_index:\n result = df.groupby([\"a\", [0, 1], \"d\"], as_index=as_index).value_counts()\n expected = Series(\n data=(1, 1),\n index=MultiIndex.from_tuples(\n [(1, 0, 7, 3, 5, 9), (2, 1, 8, 4, 6, 10)],\n names=expected_names,\n ),\n )\n tm.assert_series_equal(result, expected)\n else:\n with pytest.raises(ValueError, match=\"cannot insert\"):\n df.groupby([\"a\", [0, 1], \"d\"], as_index=as_index).value_counts()\n\n\ndef test_ambiguous_grouping():\n # Test that groupby is not confused by groupings length equal to row count\n df = DataFrame({\"a\": [1, 1]})\n gb = df.groupby([1, 1])\n result = gb.value_counts()\n expected = Series([2], index=MultiIndex.from_tuples([[1, 1]], names=[None, \"a\"]))\n tm.assert_series_equal(result, expected)\n", "from __future__ import annotations\n\nfrom datetime import (\n datetime,\n time,\n)\n\nimport numpy as np\n\nfrom pandas._libs.lib import is_list_like\n\nfrom pandas.core.dtypes.generic import (\n ABCIndex,\n ABCSeries,\n)\nfrom pandas.core.dtypes.missing import notna\n\n\ndef to_time(arg, format=None, infer_time_format=False, errors=\"raise\"):\n \"\"\"\n Parse time strings to time objects using fixed strptime formats (\"%H:%M\",\n \"%H%M\", \"%I:%M%p\", \"%I%M%p\", \"%H:%M:%S\", \"%H%M%S\", \"%I:%M:%S%p\",\n \"%I%M%S%p\")\n\n Use infer_time_format if all the strings are in the same format to speed\n up conversion.\n\n Parameters\n ----------\n arg : string in time format, datetime.time, list, tuple, 1-d array, Series\n format : str, default None\n Format used to convert arg into a time object. If None, fixed formats\n are used.\n infer_time_format: bool, default False\n Infer the time format based on the first non-NaN element. If all\n strings are in the same format, this will speed up conversion.\n errors : {'ignore', 'raise', 'coerce'}, default 'raise'\n - If 'raise', then invalid parsing will raise an exception\n - If 'coerce', then invalid parsing will be set as None\n - If 'ignore', then invalid parsing will return the input\n\n Returns\n -------\n datetime.time\n \"\"\"\n\n def _convert_listlike(arg, format):\n\n if isinstance(arg, (list, tuple)):\n arg = np.array(arg, dtype=\"O\")\n\n elif getattr(arg, \"ndim\", 1) > 1:\n raise TypeError(\n \"arg must be a string, datetime, list, tuple, 1-d array, or Series\"\n )\n\n arg = np.asarray(arg, dtype=\"O\")\n\n if infer_time_format and format is None:\n format = _guess_time_format_for_array(arg)\n\n times: list[time | None] = []\n if format is not None:\n for element in arg:\n try:\n times.append(datetime.strptime(element, format).time())\n except (ValueError, TypeError) as err:\n if errors == \"raise\":\n msg = (\n f\"Cannot convert {element} to a time with given \"\n f\"format {format}\"\n )\n raise ValueError(msg) from err\n elif errors == \"ignore\":\n return arg\n else:\n times.append(None)\n else:\n formats = _time_formats[:]\n format_found = False\n for element in arg:\n time_object = None\n for time_format in formats:\n try:\n time_object = datetime.strptime(element, time_format).time()\n if not format_found:\n # Put the found format in front\n fmt = formats.pop(formats.index(time_format))\n formats.insert(0, fmt)\n format_found = True\n break\n except (ValueError, TypeError):\n continue\n\n if time_object is not None:\n times.append(time_object)\n elif errors == \"raise\":\n raise ValueError(f\"Cannot convert arg {arg} to a time\")\n elif errors == \"ignore\":\n return arg\n else:\n times.append(None)\n\n return times\n\n if arg is None:\n return arg\n elif isinstance(arg, time):\n return arg\n elif isinstance(arg, ABCSeries):\n values = _convert_listlike(arg._values, format)\n return arg._constructor(values, index=arg.index, name=arg.name)\n elif isinstance(arg, ABCIndex):\n return _convert_listlike(arg, format)\n elif is_list_like(arg):\n return _convert_listlike(arg, format)\n\n return _convert_listlike(np.array([arg]), format)[0]\n\n\n# Fixed time formats for time parsing\n_time_formats = [\n \"%H:%M\",\n \"%H%M\",\n \"%I:%M%p\",\n \"%I%M%p\",\n \"%H:%M:%S\",\n \"%H%M%S\",\n \"%I:%M:%S%p\",\n \"%I%M%S%p\",\n]\n\n\ndef _guess_time_format_for_array(arr):\n # Try to guess the format based on the first non-NaN element\n non_nan_elements = notna(arr).nonzero()[0]\n if len(non_nan_elements):\n element = arr[non_nan_elements[0]]\n for time_format in _time_formats:\n try:\n datetime.strptime(element, time_format)\n return time_format\n except ValueError:\n pass\n\n return None\n", "\"\"\"Common IO api utilities\"\"\"\nfrom __future__ import annotations\n\nimport bz2\nimport codecs\nfrom collections import abc\nimport dataclasses\nimport functools\nimport gzip\nfrom io import (\n BufferedIOBase,\n BytesIO,\n RawIOBase,\n StringIO,\n TextIOBase,\n TextIOWrapper,\n)\nimport mmap\nimport os\nfrom pathlib import Path\nimport re\nfrom typing import (\n IO,\n Any,\n AnyStr,\n Generic,\n Literal,\n Mapping,\n TypeVar,\n cast,\n overload,\n)\nfrom urllib.parse import (\n urljoin,\n urlparse as parse_url,\n uses_netloc,\n uses_params,\n uses_relative,\n)\nimport warnings\nimport zipfile\n\nfrom pandas._typing import (\n BaseBuffer,\n CompressionDict,\n CompressionOptions,\n FilePath,\n ReadBuffer,\n StorageOptions,\n WriteBuffer,\n)\nfrom pandas.compat import get_lzma_file\nfrom pandas.compat._optional import import_optional_dependency\nfrom pandas.util._decorators import doc\nfrom pandas.util._exceptions import find_stack_level\n\nfrom pandas.core.dtypes.common import is_file_like\n\nfrom pandas.core.shared_docs import _shared_docs\n\n_VALID_URLS = set(uses_relative + uses_netloc + uses_params)\n_VALID_URLS.discard(\"\")\n_RFC_3986_PATTERN = re.compile(r\"^[A-Za-z][A-Za-z0-9+\\-+.]*://\")\n\nBaseBufferT = TypeVar(\"BaseBufferT\", bound=BaseBuffer)\n\n\[email protected]\nclass IOArgs:\n \"\"\"\n Return value of io/common.py:_get_filepath_or_buffer.\n \"\"\"\n\n filepath_or_buffer: str | BaseBuffer\n encoding: str\n mode: str\n compression: CompressionDict\n should_close: bool = False\n\n\[email protected]\nclass IOHandles(Generic[AnyStr]):\n \"\"\"\n Return value of io/common.py:get_handle\n\n Can be used as a context manager.\n\n This is used to easily close created buffers and to handle corner cases when\n TextIOWrapper is inserted.\n\n handle: The file handle to be used.\n created_handles: All file handles that are created by get_handle\n is_wrapped: Whether a TextIOWrapper needs to be detached.\n \"\"\"\n\n # handle might not implement the IO-interface\n handle: IO[AnyStr]\n compression: CompressionDict\n created_handles: list[IO[bytes] | IO[str]] = dataclasses.field(default_factory=list)\n is_wrapped: bool = False\n is_mmap: bool = False\n\n def close(self) -> None:\n \"\"\"\n Close all created buffers.\n\n Note: If a TextIOWrapper was inserted, it is flushed and detached to\n avoid closing the potentially user-created buffer.\n \"\"\"\n if self.is_wrapped:\n assert isinstance(self.handle, TextIOWrapper)\n self.handle.flush()\n self.handle.detach()\n self.created_handles.remove(self.handle)\n try:\n for handle in self.created_handles:\n handle.close()\n except (OSError, ValueError):\n pass\n self.created_handles = []\n self.is_wrapped = False\n\n def __enter__(self) -> IOHandles[AnyStr]:\n return self\n\n def __exit__(self, *args: Any) -> None:\n self.close()\n\n\ndef is_url(url: object) -> bool:\n \"\"\"\n Check to see if a URL has a valid protocol.\n\n Parameters\n ----------\n url : str or unicode\n\n Returns\n -------\n isurl : bool\n If `url` has a valid protocol return True otherwise False.\n \"\"\"\n if not isinstance(url, str):\n return False\n return parse_url(url).scheme in _VALID_URLS\n\n\n@overload\ndef _expand_user(filepath_or_buffer: str) -> str:\n ...\n\n\n@overload\ndef _expand_user(filepath_or_buffer: BaseBufferT) -> BaseBufferT:\n ...\n\n\ndef _expand_user(filepath_or_buffer: str | BaseBufferT) -> str | BaseBufferT:\n \"\"\"\n Return the argument with an initial component of ~ or ~user\n replaced by that user's home directory.\n\n Parameters\n ----------\n filepath_or_buffer : object to be converted if possible\n\n Returns\n -------\n expanded_filepath_or_buffer : an expanded filepath or the\n input if not expandable\n \"\"\"\n if isinstance(filepath_or_buffer, str):\n return os.path.expanduser(filepath_or_buffer)\n return filepath_or_buffer\n\n\ndef validate_header_arg(header: object) -> None:\n if isinstance(header, bool):\n raise TypeError(\n \"Passing a bool to header is invalid. Use header=None for no header or \"\n \"header=int or list-like of ints to specify \"\n \"the row(s) making up the column names\"\n )\n\n\n@overload\ndef stringify_path(filepath_or_buffer: FilePath, convert_file_like: bool = ...) -> str:\n ...\n\n\n@overload\ndef stringify_path(\n filepath_or_buffer: BaseBufferT, convert_file_like: bool = ...\n) -> BaseBufferT:\n ...\n\n\ndef stringify_path(\n filepath_or_buffer: FilePath | BaseBufferT,\n convert_file_like: bool = False,\n) -> str | BaseBufferT:\n \"\"\"\n Attempt to convert a path-like object to a string.\n\n Parameters\n ----------\n filepath_or_buffer : object to be converted\n\n Returns\n -------\n str_filepath_or_buffer : maybe a string version of the object\n\n Notes\n -----\n Objects supporting the fspath protocol (python 3.6+) are coerced\n according to its __fspath__ method.\n\n Any other object is passed through unchanged, which includes bytes,\n strings, buffers, or anything else that's not even path-like.\n \"\"\"\n if not convert_file_like and is_file_like(filepath_or_buffer):\n # GH 38125: some fsspec objects implement os.PathLike but have already opened a\n # file. This prevents opening the file a second time. infer_compression calls\n # this function with convert_file_like=True to infer the compression.\n return cast(BaseBufferT, filepath_or_buffer)\n\n if isinstance(filepath_or_buffer, os.PathLike):\n filepath_or_buffer = filepath_or_buffer.__fspath__()\n return _expand_user(filepath_or_buffer)\n\n\ndef urlopen(*args, **kwargs):\n \"\"\"\n Lazy-import wrapper for stdlib urlopen, as that imports a big chunk of\n the stdlib.\n \"\"\"\n import urllib.request\n\n return urllib.request.urlopen(*args, **kwargs)\n\n\ndef is_fsspec_url(url: FilePath | BaseBuffer) -> bool:\n \"\"\"\n Returns true if the given URL looks like\n something fsspec can handle\n \"\"\"\n return (\n isinstance(url, str)\n and bool(_RFC_3986_PATTERN.match(url))\n and not url.startswith((\"http://\", \"https://\"))\n )\n\n\n@doc(compression_options=_shared_docs[\"compression_options\"] % \"filepath_or_buffer\")\ndef _get_filepath_or_buffer(\n filepath_or_buffer: FilePath | BaseBuffer,\n encoding: str = \"utf-8\",\n compression: CompressionOptions = None,\n mode: str = \"r\",\n storage_options: StorageOptions = None,\n) -> IOArgs:\n \"\"\"\n If the filepath_or_buffer is a url, translate and return the buffer.\n Otherwise passthrough.\n\n Parameters\n ----------\n filepath_or_buffer : a url, filepath (str, py.path.local or pathlib.Path),\n or buffer\n {compression_options}\n\n .. versionchanged:: 1.4.0 Zstandard support.\n\n encoding : the encoding to use to decode bytes, default is 'utf-8'\n mode : str, optional\n\n storage_options : dict, optional\n Extra options that make sense for a particular storage connection, e.g.\n host, port, username, password, etc., if using a URL that will\n be parsed by ``fsspec``, e.g., starting \"s3://\", \"gcs://\". An error\n will be raised if providing this argument with a local path or\n a file-like buffer. See the fsspec and backend storage implementation\n docs for the set of allowed keys and values\n\n .. versionadded:: 1.2.0\n\n ..versionchange:: 1.2.0\n\n Returns the dataclass IOArgs.\n \"\"\"\n filepath_or_buffer = stringify_path(filepath_or_buffer)\n\n # handle compression dict\n compression_method, compression = get_compression_method(compression)\n compression_method = infer_compression(filepath_or_buffer, compression_method)\n\n # GH21227 internal compression is not used for non-binary handles.\n if compression_method and hasattr(filepath_or_buffer, \"write\") and \"b\" not in mode:\n warnings.warn(\n \"compression has no effect when passing a non-binary object as input.\",\n RuntimeWarning,\n stacklevel=find_stack_level(),\n )\n compression_method = None\n\n compression = dict(compression, method=compression_method)\n\n # bz2 and xz do not write the byte order mark for utf-16 and utf-32\n # print a warning when writing such files\n if (\n \"w\" in mode\n and compression_method in [\"bz2\", \"xz\"]\n and encoding in [\"utf-16\", \"utf-32\"]\n ):\n warnings.warn(\n f\"{compression} will not write the byte order mark for {encoding}\",\n UnicodeWarning,\n )\n\n # Use binary mode when converting path-like objects to file-like objects (fsspec)\n # except when text mode is explicitly requested. The original mode is returned if\n # fsspec is not used.\n fsspec_mode = mode\n if \"t\" not in fsspec_mode and \"b\" not in fsspec_mode:\n fsspec_mode += \"b\"\n\n if isinstance(filepath_or_buffer, str) and is_url(filepath_or_buffer):\n # TODO: fsspec can also handle HTTP via requests, but leaving this\n # unchanged. using fsspec appears to break the ability to infer if the\n # server responded with gzipped data\n storage_options = storage_options or {}\n\n # waiting until now for importing to match intended lazy logic of\n # urlopen function defined elsewhere in this module\n import urllib.request\n\n # assuming storage_options is to be interpreted as headers\n req_info = urllib.request.Request(filepath_or_buffer, headers=storage_options)\n with urlopen(req_info) as req:\n content_encoding = req.headers.get(\"Content-Encoding\", None)\n if content_encoding == \"gzip\":\n # Override compression based on Content-Encoding header\n compression = {\"method\": \"gzip\"}\n reader = BytesIO(req.read())\n return IOArgs(\n filepath_or_buffer=reader,\n encoding=encoding,\n compression=compression,\n should_close=True,\n mode=fsspec_mode,\n )\n\n if is_fsspec_url(filepath_or_buffer):\n assert isinstance(\n filepath_or_buffer, str\n ) # just to appease mypy for this branch\n # two special-case s3-like protocols; these have special meaning in Hadoop,\n # but are equivalent to just \"s3\" from fsspec's point of view\n # cc #11071\n if filepath_or_buffer.startswith(\"s3a://\"):\n filepath_or_buffer = filepath_or_buffer.replace(\"s3a://\", \"s3://\")\n if filepath_or_buffer.startswith(\"s3n://\"):\n filepath_or_buffer = filepath_or_buffer.replace(\"s3n://\", \"s3://\")\n fsspec = import_optional_dependency(\"fsspec\")\n\n # If botocore is installed we fallback to reading with anon=True\n # to allow reads from public buckets\n err_types_to_retry_with_anon: list[Any] = []\n try:\n import_optional_dependency(\"botocore\")\n from botocore.exceptions import (\n ClientError,\n NoCredentialsError,\n )\n\n err_types_to_retry_with_anon = [\n ClientError,\n NoCredentialsError,\n PermissionError,\n ]\n except ImportError:\n pass\n\n try:\n file_obj = fsspec.open(\n filepath_or_buffer, mode=fsspec_mode, **(storage_options or {})\n ).open()\n # GH 34626 Reads from Public Buckets without Credentials needs anon=True\n except tuple(err_types_to_retry_with_anon):\n if storage_options is None:\n storage_options = {\"anon\": True}\n else:\n # don't mutate user input.\n storage_options = dict(storage_options)\n storage_options[\"anon\"] = True\n file_obj = fsspec.open(\n filepath_or_buffer, mode=fsspec_mode, **(storage_options or {})\n ).open()\n\n return IOArgs(\n filepath_or_buffer=file_obj,\n encoding=encoding,\n compression=compression,\n should_close=True,\n mode=fsspec_mode,\n )\n elif storage_options:\n raise ValueError(\n \"storage_options passed with file object or non-fsspec file path\"\n )\n\n if isinstance(filepath_or_buffer, (str, bytes, mmap.mmap)):\n return IOArgs(\n filepath_or_buffer=_expand_user(filepath_or_buffer),\n encoding=encoding,\n compression=compression,\n should_close=False,\n mode=mode,\n )\n\n # is_file_like requires (read | write) & __iter__ but __iter__ is only\n # needed for read_csv(engine=python)\n if not (\n hasattr(filepath_or_buffer, \"read\") or hasattr(filepath_or_buffer, \"write\")\n ):\n msg = f\"Invalid file path or buffer object type: {type(filepath_or_buffer)}\"\n raise ValueError(msg)\n\n return IOArgs(\n filepath_or_buffer=filepath_or_buffer,\n encoding=encoding,\n compression=compression,\n should_close=False,\n mode=mode,\n )\n\n\ndef file_path_to_url(path: str) -> str:\n \"\"\"\n converts an absolute native path to a FILE URL.\n\n Parameters\n ----------\n path : a path in native format\n\n Returns\n -------\n a valid FILE URL\n \"\"\"\n # lazify expensive import (~30ms)\n from urllib.request import pathname2url\n\n return urljoin(\"file:\", pathname2url(path))\n\n\n_compression_to_extension = {\n \"gzip\": \".gz\",\n \"bz2\": \".bz2\",\n \"zip\": \".zip\",\n \"xz\": \".xz\",\n \"zstd\": \".zst\",\n}\n\n\ndef get_compression_method(\n compression: CompressionOptions,\n) -> tuple[str | None, CompressionDict]:\n \"\"\"\n Simplifies a compression argument to a compression method string and\n a mapping containing additional arguments.\n\n Parameters\n ----------\n compression : str or mapping\n If string, specifies the compression method. If mapping, value at key\n 'method' specifies compression method.\n\n Returns\n -------\n tuple of ({compression method}, Optional[str]\n {compression arguments}, Dict[str, Any])\n\n Raises\n ------\n ValueError on mapping missing 'method' key\n \"\"\"\n compression_method: str | None\n if isinstance(compression, Mapping):\n compression_args = dict(compression)\n try:\n compression_method = compression_args.pop(\"method\")\n except KeyError as err:\n raise ValueError(\"If mapping, compression must have key 'method'\") from err\n else:\n compression_args = {}\n compression_method = compression\n return compression_method, compression_args\n\n\n@doc(compression_options=_shared_docs[\"compression_options\"] % \"filepath_or_buffer\")\ndef infer_compression(\n filepath_or_buffer: FilePath | BaseBuffer, compression: str | None\n) -> str | None:\n \"\"\"\n Get the compression method for filepath_or_buffer. If compression='infer',\n the inferred compression method is returned. Otherwise, the input\n compression method is returned unchanged, unless it's invalid, in which\n case an error is raised.\n\n Parameters\n ----------\n filepath_or_buffer : str or file handle\n File path or object.\n {compression_options}\n\n .. versionchanged:: 1.4.0 Zstandard support.\n\n Returns\n -------\n string or None\n\n Raises\n ------\n ValueError on invalid compression specified.\n \"\"\"\n if compression is None:\n return None\n\n # Infer compression\n if compression == \"infer\":\n # Convert all path types (e.g. pathlib.Path) to strings\n filepath_or_buffer = stringify_path(filepath_or_buffer, convert_file_like=True)\n if not isinstance(filepath_or_buffer, str):\n # Cannot infer compression of a buffer, assume no compression\n return None\n\n # Infer compression from the filename/URL extension\n for compression, extension in _compression_to_extension.items():\n if filepath_or_buffer.lower().endswith(extension):\n return compression\n return None\n\n # Compression has been specified. Check that it's valid\n if compression in _compression_to_extension:\n return compression\n\n # https://github.com/python/mypy/issues/5492\n # Unsupported operand types for + (\"List[Optional[str]]\" and \"List[str]\")\n valid = [\"infer\", None] + sorted(\n _compression_to_extension\n ) # type: ignore[operator]\n msg = (\n f\"Unrecognized compression type: {compression}\\n\"\n f\"Valid compression types are {valid}\"\n )\n raise ValueError(msg)\n\n\ndef check_parent_directory(path: Path | str) -> None:\n \"\"\"\n Check if parent directory of a file exists, raise OSError if it does not\n\n Parameters\n ----------\n path: Path or str\n Path to check parent directory of\n\n \"\"\"\n parent = Path(path).parent\n if not parent.is_dir():\n raise OSError(rf\"Cannot save file into a non-existent directory: '{parent}'\")\n\n\n@overload\ndef get_handle(\n path_or_buf: FilePath | BaseBuffer,\n mode: str,\n *,\n encoding: str | None = ...,\n compression: CompressionOptions = ...,\n memory_map: bool = ...,\n is_text: Literal[False],\n errors: str | None = ...,\n storage_options: StorageOptions = ...,\n) -> IOHandles[bytes]:\n ...\n\n\n@overload\ndef get_handle(\n path_or_buf: FilePath | BaseBuffer,\n mode: str,\n *,\n encoding: str | None = ...,\n compression: CompressionOptions = ...,\n memory_map: bool = ...,\n is_text: Literal[True] = ...,\n errors: str | None = ...,\n storage_options: StorageOptions = ...,\n) -> IOHandles[str]:\n ...\n\n\n@doc(compression_options=_shared_docs[\"compression_options\"] % \"path_or_buf\")\ndef get_handle(\n path_or_buf: FilePath | BaseBuffer,\n mode: str,\n *,\n encoding: str | None = None,\n compression: CompressionOptions = None,\n memory_map: bool = False,\n is_text: bool = True,\n errors: str | None = None,\n storage_options: StorageOptions = None,\n) -> IOHandles[str] | IOHandles[bytes]:\n \"\"\"\n Get file handle for given path/buffer and mode.\n\n Parameters\n ----------\n path_or_buf : str or file handle\n File path or object.\n mode : str\n Mode to open path_or_buf with.\n encoding : str or None\n Encoding to use.\n {compression_options}\n\n .. versionchanged:: 1.0.0\n May now be a dict with key 'method' as compression mode\n and other keys as compression options if compression\n mode is 'zip'.\n\n .. versionchanged:: 1.1.0\n Passing compression options as keys in dict is now\n supported for compression modes 'gzip', 'bz2', 'zstd' and 'zip'.\n\n .. versionchanged:: 1.4.0 Zstandard support.\n\n memory_map : bool, default False\n See parsers._parser_params for more information.\n is_text : bool, default True\n Whether the type of the content passed to the file/buffer is string or\n bytes. This is not the same as `\"b\" not in mode`. If a string content is\n passed to a binary file/buffer, a wrapper is inserted.\n errors : str, default 'strict'\n Specifies how encoding and decoding errors are to be handled.\n See the errors argument for :func:`open` for a full list\n of options.\n storage_options: StorageOptions = None\n Passed to _get_filepath_or_buffer\n\n .. versionchanged:: 1.2.0\n\n Returns the dataclass IOHandles\n \"\"\"\n # Windows does not default to utf-8. Set to utf-8 for a consistent behavior\n encoding = encoding or \"utf-8\"\n\n # read_csv does not know whether the buffer is opened in binary/text mode\n if _is_binary_mode(path_or_buf, mode) and \"b\" not in mode:\n mode += \"b\"\n\n # validate encoding and errors\n codecs.lookup(encoding)\n if isinstance(errors, str):\n codecs.lookup_error(errors)\n\n # open URLs\n ioargs = _get_filepath_or_buffer(\n path_or_buf,\n encoding=encoding,\n compression=compression,\n mode=mode,\n storage_options=storage_options,\n )\n\n handle = ioargs.filepath_or_buffer\n handles: list[BaseBuffer]\n\n # memory mapping needs to be the first step\n handle, memory_map, handles = _maybe_memory_map(\n handle,\n memory_map,\n ioargs.encoding,\n ioargs.mode,\n errors,\n ioargs.compression[\"method\"] not in _compression_to_extension,\n )\n\n is_path = isinstance(handle, str)\n compression_args = dict(ioargs.compression)\n compression = compression_args.pop(\"method\")\n\n # Only for write methods\n if \"r\" not in mode and is_path:\n check_parent_directory(str(handle))\n\n if compression:\n if compression != \"zstd\":\n # compression libraries do not like an explicit text-mode\n ioargs.mode = ioargs.mode.replace(\"t\", \"\")\n elif compression == \"zstd\" and \"b\" not in ioargs.mode:\n # python-zstandard defaults to text mode, but we always expect\n # compression libraries to use binary mode.\n ioargs.mode += \"b\"\n\n # GZ Compression\n if compression == \"gzip\":\n if is_path:\n assert isinstance(handle, str)\n # error: Incompatible types in assignment (expression has type\n # \"GzipFile\", variable has type \"Union[str, BaseBuffer]\")\n handle = gzip.GzipFile( # type: ignore[assignment]\n filename=handle,\n mode=ioargs.mode,\n **compression_args,\n )\n else:\n handle = gzip.GzipFile(\n # No overload variant of \"GzipFile\" matches argument types\n # \"Union[str, BaseBuffer]\", \"str\", \"Dict[str, Any]\"\n fileobj=handle, # type: ignore[call-overload]\n mode=ioargs.mode,\n **compression_args,\n )\n\n # BZ Compression\n elif compression == \"bz2\":\n # No overload variant of \"BZ2File\" matches argument types\n # \"Union[str, BaseBuffer]\", \"str\", \"Dict[str, Any]\"\n handle = bz2.BZ2File( # type: ignore[call-overload]\n handle,\n mode=ioargs.mode,\n **compression_args,\n )\n\n # ZIP Compression\n elif compression == \"zip\":\n # error: Argument 1 to \"_BytesZipFile\" has incompatible type \"Union[str,\n # BaseBuffer]\"; expected \"Union[Union[str, PathLike[str]],\n # ReadBuffer[bytes], WriteBuffer[bytes]]\"\n handle = _BytesZipFile(\n handle, ioargs.mode, **compression_args # type: ignore[arg-type]\n )\n if handle.mode == \"r\":\n handles.append(handle)\n zip_names = handle.namelist()\n if len(zip_names) == 1:\n handle = handle.open(zip_names.pop())\n elif len(zip_names) == 0:\n raise ValueError(f\"Zero files found in ZIP file {path_or_buf}\")\n else:\n raise ValueError(\n \"Multiple files found in ZIP file. \"\n f\"Only one file per ZIP: {zip_names}\"\n )\n\n # XZ Compression\n elif compression == \"xz\":\n handle = get_lzma_file()(handle, ioargs.mode)\n\n # Zstd Compression\n elif compression == \"zstd\":\n zstd = import_optional_dependency(\"zstandard\")\n if \"r\" in ioargs.mode:\n open_args = {\"dctx\": zstd.ZstdDecompressor(**compression_args)}\n else:\n open_args = {\"cctx\": zstd.ZstdCompressor(**compression_args)}\n handle = zstd.open(\n handle,\n mode=ioargs.mode,\n **open_args,\n )\n\n # Unrecognized Compression\n else:\n msg = f\"Unrecognized compression type: {compression}\"\n raise ValueError(msg)\n\n assert not isinstance(handle, str)\n handles.append(handle)\n\n elif isinstance(handle, str):\n # Check whether the filename is to be opened in binary mode.\n # Binary mode does not support 'encoding' and 'newline'.\n if ioargs.encoding and \"b\" not in ioargs.mode:\n # Encoding\n handle = open(\n handle,\n ioargs.mode,\n encoding=ioargs.encoding,\n errors=errors,\n newline=\"\",\n )\n else:\n # Binary mode\n handle = open(handle, ioargs.mode)\n handles.append(handle)\n\n # Convert BytesIO or file objects passed with an encoding\n is_wrapped = False\n if not is_text and ioargs.mode == \"rb\" and isinstance(handle, TextIOBase):\n # not added to handles as it does not open/buffer resources\n handle = _BytesIOWrapper(\n handle,\n encoding=ioargs.encoding,\n )\n elif is_text and (compression or _is_binary_mode(handle, ioargs.mode)):\n handle = TextIOWrapper(\n # error: Argument 1 to \"TextIOWrapper\" has incompatible type\n # \"Union[IO[bytes], IO[Any], RawIOBase, BufferedIOBase, TextIOBase, mmap]\";\n # expected \"IO[bytes]\"\n _IOWrapper(handle), # type: ignore[arg-type]\n encoding=ioargs.encoding,\n errors=errors,\n newline=\"\",\n )\n handles.append(handle)\n # only marked as wrapped when the caller provided a handle\n is_wrapped = not (\n isinstance(ioargs.filepath_or_buffer, str) or ioargs.should_close\n )\n\n if \"r\" in ioargs.mode and not hasattr(handle, \"read\"):\n raise TypeError(\n \"Expected file path name or file-like object, \"\n f\"got {type(ioargs.filepath_or_buffer)} type\"\n )\n\n handles.reverse() # close the most recently added buffer first\n if ioargs.should_close:\n assert not isinstance(ioargs.filepath_or_buffer, str)\n handles.append(ioargs.filepath_or_buffer)\n\n return IOHandles(\n # error: Argument \"handle\" to \"IOHandles\" has incompatible type\n # \"Union[TextIOWrapper, GzipFile, BaseBuffer, typing.IO[bytes],\n # typing.IO[Any]]\"; expected \"pandas._typing.IO[Any]\"\n handle=handle, # type: ignore[arg-type]\n # error: Argument \"created_handles\" to \"IOHandles\" has incompatible type\n # \"List[BaseBuffer]\"; expected \"List[Union[IO[bytes], IO[str]]]\"\n created_handles=handles, # type: ignore[arg-type]\n is_wrapped=is_wrapped,\n is_mmap=memory_map,\n compression=ioargs.compression,\n )\n\n\n# error: Definition of \"__exit__\" in base class \"ZipFile\" is incompatible with\n# definition in base class \"BytesIO\" [misc]\n# error: Definition of \"__enter__\" in base class \"ZipFile\" is incompatible with\n# definition in base class \"BytesIO\" [misc]\n# error: Definition of \"__enter__\" in base class \"ZipFile\" is incompatible with\n# definition in base class \"BinaryIO\" [misc]\n# error: Definition of \"__enter__\" in base class \"ZipFile\" is incompatible with\n# definition in base class \"IO\" [misc]\n# error: Definition of \"read\" in base class \"ZipFile\" is incompatible with\n# definition in base class \"BytesIO\" [misc]\n# error: Definition of \"read\" in base class \"ZipFile\" is incompatible with\n# definition in base class \"IO\" [misc]\nclass _BytesZipFile(zipfile.ZipFile, BytesIO): # type: ignore[misc]\n \"\"\"\n Wrapper for standard library class ZipFile and allow the returned file-like\n handle to accept byte strings via `write` method.\n\n BytesIO provides attributes of file-like object and ZipFile.writestr writes\n bytes strings into a member of the archive.\n \"\"\"\n\n # GH 17778\n def __init__(\n self,\n file: FilePath | ReadBuffer[bytes] | WriteBuffer[bytes],\n mode: str,\n archive_name: str | None = None,\n **kwargs,\n ):\n mode = mode.replace(\"b\", \"\")\n self.archive_name = archive_name\n self.multiple_write_buffer: StringIO | BytesIO | None = None\n\n kwargs_zip: dict[str, Any] = {\"compression\": zipfile.ZIP_DEFLATED}\n kwargs_zip.update(kwargs)\n\n # error: Argument 1 to \"__init__\" of \"ZipFile\" has incompatible type\n # \"Union[_PathLike[str], Union[str, Union[IO[Any], RawIOBase, BufferedIOBase,\n # TextIOBase, TextIOWrapper, mmap]]]\"; expected \"Union[Union[str,\n # _PathLike[str]], IO[bytes]]\"\n super().__init__(file, mode, **kwargs_zip) # type: ignore[arg-type]\n\n def infer_filename(self):\n \"\"\"\n If an explicit archive_name is not given, we still want the file inside the zip\n file not to be named something.zip, because that causes confusion (GH39465).\n \"\"\"\n if isinstance(self.filename, (os.PathLike, str)):\n filename = Path(self.filename)\n if filename.suffix == \".zip\":\n return filename.with_suffix(\"\").name\n return filename.name\n return None\n\n def write(self, data):\n # buffer multiple write calls, write on flush\n if self.multiple_write_buffer is None:\n self.multiple_write_buffer = (\n BytesIO() if isinstance(data, bytes) else StringIO()\n )\n self.multiple_write_buffer.write(data)\n\n def flush(self) -> None:\n # write to actual handle and close write buffer\n if self.multiple_write_buffer is None or self.multiple_write_buffer.closed:\n return\n\n # ZipFile needs a non-empty string\n archive_name = self.archive_name or self.infer_filename() or \"zip\"\n with self.multiple_write_buffer:\n super().writestr(archive_name, self.multiple_write_buffer.getvalue())\n\n def close(self):\n self.flush()\n super().close()\n\n @property\n def closed(self):\n return self.fp is None\n\n\nclass _MMapWrapper(abc.Iterator):\n \"\"\"\n Wrapper for the Python's mmap class so that it can be properly read in\n by Python's csv.reader class.\n\n Parameters\n ----------\n f : file object\n File object to be mapped onto memory. Must support the 'fileno'\n method or have an equivalent attribute\n\n \"\"\"\n\n def __init__(\n self,\n f: IO,\n encoding: str = \"utf-8\",\n errors: str = \"strict\",\n decode: bool = True,\n ):\n self.encoding = encoding\n self.errors = errors\n self.decoder = codecs.getincrementaldecoder(encoding)(errors=errors)\n self.decode = decode\n\n self.attributes = {}\n for attribute in (\"seekable\", \"readable\"):\n if not hasattr(f, attribute):\n continue\n self.attributes[attribute] = getattr(f, attribute)()\n self.mmap = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)\n\n def __getattr__(self, name: str):\n if name in self.attributes:\n return lambda: self.attributes[name]\n return getattr(self.mmap, name)\n\n def __iter__(self) -> _MMapWrapper:\n return self\n\n def read(self, size: int = -1) -> str | bytes:\n # CSV c-engine uses read instead of iterating\n content: bytes = self.mmap.read(size)\n if self.decode and self.encoding != \"utf-8\":\n # memory mapping is applied before compression. Encoding should\n # be applied to the de-compressed data.\n final = size == -1 or len(content) < size\n return self.decoder.decode(content, final=final)\n return content\n\n def __next__(self) -> str:\n newbytes = self.mmap.readline()\n\n # readline returns bytes, not str, but Python's CSV reader\n # expects str, so convert the output to str before continuing\n newline = self.decoder.decode(newbytes)\n\n # mmap doesn't raise if reading past the allocated\n # data but instead returns an empty string, so raise\n # if that is returned\n if newline == \"\":\n raise StopIteration\n\n # IncrementalDecoder seems to push newline to the next line\n return newline.lstrip(\"\\n\")\n\n\nclass _IOWrapper:\n # TextIOWrapper is overly strict: it request that the buffer has seekable, readable,\n # and writable. If we have a read-only buffer, we shouldn't need writable and vice\n # versa. Some buffers, are seek/read/writ-able but they do not have the \"-able\"\n # methods, e.g., tempfile.SpooledTemporaryFile.\n # If a buffer does not have the above \"-able\" methods, we simple assume they are\n # seek/read/writ-able.\n def __init__(self, buffer: BaseBuffer):\n self.buffer = buffer\n\n def __getattr__(self, name: str):\n return getattr(self.buffer, name)\n\n def readable(self) -> bool:\n if hasattr(self.buffer, \"readable\"):\n # error: \"BaseBuffer\" has no attribute \"readable\"\n return self.buffer.readable() # type: ignore[attr-defined]\n return True\n\n def seekable(self) -> bool:\n if hasattr(self.buffer, \"seekable\"):\n return self.buffer.seekable()\n return True\n\n def writable(self) -> bool:\n if hasattr(self.buffer, \"writable\"):\n # error: \"BaseBuffer\" has no attribute \"writable\"\n return self.buffer.writable() # type: ignore[attr-defined]\n return True\n\n\nclass _BytesIOWrapper:\n # Wrapper that wraps a StringIO buffer and reads bytes from it\n # Created for compat with pyarrow read_csv\n def __init__(self, buffer: StringIO | TextIOBase, encoding: str = \"utf-8\"):\n self.buffer = buffer\n self.encoding = encoding\n # Because a character can be represented by more than 1 byte,\n # it is possible that reading will produce more bytes than n\n # We store the extra bytes in this overflow variable, and append the\n # overflow to the front of the bytestring the next time reading is performed\n self.overflow = b\"\"\n\n def __getattr__(self, attr: str):\n return getattr(self.buffer, attr)\n\n def read(self, n: int | None = -1) -> bytes:\n assert self.buffer is not None\n bytestring = self.buffer.read(n).encode(self.encoding)\n # When n=-1/n greater than remaining bytes: Read entire file/rest of file\n combined_bytestring = self.overflow + bytestring\n if n is None or n < 0 or n >= len(combined_bytestring):\n self.overflow = b\"\"\n return combined_bytestring\n else:\n to_return = combined_bytestring[:n]\n self.overflow = combined_bytestring[n:]\n return to_return\n\n\ndef _maybe_memory_map(\n handle: str | BaseBuffer,\n memory_map: bool,\n encoding: str,\n mode: str,\n errors: str | None,\n decode: bool,\n) -> tuple[str | BaseBuffer, bool, list[BaseBuffer]]:\n \"\"\"Try to memory map file/buffer.\"\"\"\n handles: list[BaseBuffer] = []\n memory_map &= hasattr(handle, \"fileno\") or isinstance(handle, str)\n if not memory_map:\n return handle, memory_map, handles\n\n # need to open the file first\n if isinstance(handle, str):\n if encoding and \"b\" not in mode:\n # Encoding\n handle = open(handle, mode, encoding=encoding, errors=errors, newline=\"\")\n else:\n # Binary mode\n handle = open(handle, mode)\n handles.append(handle)\n\n # error: Argument 1 to \"_MMapWrapper\" has incompatible type \"Union[IO[Any],\n # RawIOBase, BufferedIOBase, TextIOBase, mmap]\"; expected \"IO[Any]\"\n try:\n wrapped = cast(\n BaseBuffer,\n _MMapWrapper(handle, encoding, errors, decode), # type: ignore[arg-type]\n )\n finally:\n for handle in reversed(handles):\n # error: \"BaseBuffer\" has no attribute \"close\"\n handle.close() # type: ignore[attr-defined]\n handles.append(wrapped)\n\n return wrapped, memory_map, handles\n\n\ndef file_exists(filepath_or_buffer: FilePath | BaseBuffer) -> bool:\n \"\"\"Test whether file exists.\"\"\"\n exists = False\n filepath_or_buffer = stringify_path(filepath_or_buffer)\n if not isinstance(filepath_or_buffer, str):\n return exists\n try:\n exists = os.path.exists(filepath_or_buffer)\n # gh-5874: if the filepath is too long will raise here\n except (TypeError, ValueError):\n pass\n return exists\n\n\ndef _is_binary_mode(handle: FilePath | BaseBuffer, mode: str) -> bool:\n \"\"\"Whether the handle is opened in binary mode\"\"\"\n # specified by user\n if \"t\" in mode or \"b\" in mode:\n return \"b\" in mode\n\n # exceptions\n text_classes = (\n # classes that expect string but have 'b' in mode\n codecs.StreamWriter,\n codecs.StreamReader,\n codecs.StreamReaderWriter,\n )\n if issubclass(type(handle), text_classes):\n return False\n\n return isinstance(handle, _get_binary_io_classes()) or \"b\" in getattr(\n handle, \"mode\", mode\n )\n\n\[email protected]_cache\ndef _get_binary_io_classes() -> tuple[type, ...]:\n \"\"\"IO classes that that expect bytes\"\"\"\n binary_classes: tuple[type, ...] = (BufferedIOBase, RawIOBase)\n\n # python-zstandard doesn't use any of the builtin base classes; instead we\n # have to use the `zstd.ZstdDecompressionReader` class for isinstance checks.\n # Unfortunately `zstd.ZstdDecompressionReader` isn't exposed by python-zstandard\n # so we have to get it from a `zstd.ZstdDecompressor` instance.\n # See also https://github.com/indygreg/python-zstandard/pull/165.\n zstd = import_optional_dependency(\"zstandard\", errors=\"ignore\")\n if zstd is not None:\n with zstd.ZstdDecompressor().stream_reader(b\"\") as reader:\n binary_classes += (type(reader),)\n\n return binary_classes\n", "import warnings\nimport numpy as np\nfrom numpy.testing import assert_allclose\nimport pytest\n\nfrom scipy.fft._fftlog import fht, ifht, fhtoffset\nfrom scipy.special import poch\n\n\ndef test_fht_agrees_with_fftlog():\n # check that fht numerically agrees with the output from Fortran FFTLog,\n # the results were generated with the provided `fftlogtest` program,\n # after fixing how the k array is generated (divide range by n-1, not n)\n\n # test function, analytical Hankel transform is of the same form\n def f(r, mu):\n return r**(mu+1)*np.exp(-r**2/2)\n\n r = np.logspace(-4, 4, 16)\n\n dln = np.log(r[1]/r[0])\n mu = 0.3\n offset = 0.0\n bias = 0.0\n\n a = f(r, mu)\n\n # test 1: compute as given\n ours = fht(a, dln, mu, offset=offset, bias=bias)\n theirs = [-0.1159922613593045E-02, +0.1625822618458832E-02,\n -0.1949518286432330E-02, +0.3789220182554077E-02,\n +0.5093959119952945E-03, +0.2785387803618774E-01,\n +0.9944952700848897E-01, +0.4599202164586588E+00,\n +0.3157462160881342E+00, -0.8201236844404755E-03,\n -0.7834031308271878E-03, +0.3931444945110708E-03,\n -0.2697710625194777E-03, +0.3568398050238820E-03,\n -0.5554454827797206E-03, +0.8286331026468585E-03]\n assert_allclose(ours, theirs)\n\n # test 2: change to optimal offset\n offset = fhtoffset(dln, mu, bias=bias)\n ours = fht(a, dln, mu, offset=offset, bias=bias)\n theirs = [+0.4353768523152057E-04, -0.9197045663594285E-05,\n +0.3150140927838524E-03, +0.9149121960963704E-03,\n +0.5808089753959363E-02, +0.2548065256377240E-01,\n +0.1339477692089897E+00, +0.4821530509479356E+00,\n +0.2659899781579785E+00, -0.1116475278448113E-01,\n +0.1791441617592385E-02, -0.4181810476548056E-03,\n +0.1314963536765343E-03, -0.5422057743066297E-04,\n +0.3208681804170443E-04, -0.2696849476008234E-04]\n assert_allclose(ours, theirs)\n\n # test 3: positive bias\n bias = 0.8\n offset = fhtoffset(dln, mu, bias=bias)\n ours = fht(a, dln, mu, offset=offset, bias=bias)\n theirs = [-7.3436673558316850E+00, +0.1710271207817100E+00,\n +0.1065374386206564E+00, -0.5121739602708132E-01,\n +0.2636649319269470E-01, +0.1697209218849693E-01,\n +0.1250215614723183E+00, +0.4739583261486729E+00,\n +0.2841149874912028E+00, -0.8312764741645729E-02,\n +0.1024233505508988E-02, -0.1644902767389120E-03,\n +0.3305775476926270E-04, -0.7786993194882709E-05,\n +0.1962258449520547E-05, -0.8977895734909250E-06]\n assert_allclose(ours, theirs)\n\n # test 4: negative bias\n bias = -0.8\n offset = fhtoffset(dln, mu, bias=bias)\n ours = fht(a, dln, mu, offset=offset, bias=bias)\n theirs = [+0.8985777068568745E-05, +0.4074898209936099E-04,\n +0.2123969254700955E-03, +0.1009558244834628E-02,\n +0.5131386375222176E-02, +0.2461678673516286E-01,\n +0.1235812845384476E+00, +0.4719570096404403E+00,\n +0.2893487490631317E+00, -0.1686570611318716E-01,\n +0.2231398155172505E-01, -0.1480742256379873E-01,\n +0.1692387813500801E+00, +0.3097490354365797E+00,\n +2.7593607182401860E+00, 10.5251075070045800E+00]\n assert_allclose(ours, theirs)\n\n\[email protected]('optimal', [True, False])\[email protected]('offset', [0.0, 1.0, -1.0])\[email protected]('bias', [0, 0.1, -0.1])\[email protected]('n', [64, 63])\ndef test_fht_identity(n, bias, offset, optimal):\n rng = np.random.RandomState(3491349965)\n\n a = rng.standard_normal(n)\n dln = rng.uniform(-1, 1)\n mu = rng.uniform(-2, 2)\n\n if optimal:\n offset = fhtoffset(dln, mu, initial=offset, bias=bias)\n\n A = fht(a, dln, mu, offset=offset, bias=bias)\n a_ = ifht(A, dln, mu, offset=offset, bias=bias)\n\n assert_allclose(a, a_)\n\n\ndef test_fht_special_cases():\n rng = np.random.RandomState(3491349965)\n\n a = rng.standard_normal(64)\n dln = rng.uniform(-1, 1)\n\n # let xp = (mu+1+q)/2, xm = (mu+1-q)/2, M = {0, -1, -2, ...}\n\n # case 1: xp in M, xm in M => well-defined transform\n mu, bias = -4.0, 1.0\n with warnings.catch_warnings(record=True) as record:\n fht(a, dln, mu, bias=bias)\n assert not record, 'fht warned about a well-defined transform'\n\n # case 2: xp not in M, xm in M => well-defined transform\n mu, bias = -2.5, 0.5\n with warnings.catch_warnings(record=True) as record:\n fht(a, dln, mu, bias=bias)\n assert not record, 'fht warned about a well-defined transform'\n\n # case 3: xp in M, xm not in M => singular transform\n mu, bias = -3.5, 0.5\n with pytest.warns(Warning) as record:\n fht(a, dln, mu, bias=bias)\n assert record, 'fht did not warn about a singular transform'\n\n # case 4: xp not in M, xm in M => singular inverse transform\n mu, bias = -2.5, 0.5\n with pytest.warns(Warning) as record:\n ifht(a, dln, mu, bias=bias)\n assert record, 'ifht did not warn about a singular transform'\n\n\[email protected]('n', [64, 63])\ndef test_fht_exact(n):\n rng = np.random.RandomState(3491349965)\n\n # for a(r) a power law r^\\gamma, the fast Hankel transform produces the\n # exact continuous Hankel transform if biased with q = \\gamma\n\n mu = rng.uniform(0, 3)\n\n # convergence of HT: -1-mu < gamma < 1/2\n gamma = rng.uniform(-1-mu, 1/2)\n\n r = np.logspace(-2, 2, n)\n a = r**gamma\n\n dln = np.log(r[1]/r[0])\n\n offset = fhtoffset(dln, mu, initial=0.0, bias=gamma)\n\n A = fht(a, dln, mu, offset=offset, bias=gamma)\n\n k = np.exp(offset)/r[::-1]\n\n # analytical result\n At = (2/k)**gamma * poch((mu+1-gamma)/2, gamma)\n\n assert_allclose(A, At)\n", "import numpy as np\nimport pytest\nimport pytz\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Index,\n Series,\n date_range,\n)\nimport pandas._testing as tm\n\n\nclass TestDataFrameAlign:\n def test_frame_align_aware(self):\n idx1 = date_range(\"2001\", periods=5, freq=\"H\", tz=\"US/Eastern\")\n idx2 = date_range(\"2001\", periods=5, freq=\"2H\", tz=\"US/Eastern\")\n df1 = DataFrame(np.random.randn(len(idx1), 3), idx1)\n df2 = DataFrame(np.random.randn(len(idx2), 3), idx2)\n new1, new2 = df1.align(df2)\n assert df1.index.tz == new1.index.tz\n assert df2.index.tz == new2.index.tz\n\n # different timezones convert to UTC\n\n # frame with frame\n df1_central = df1.tz_convert(\"US/Central\")\n new1, new2 = df1.align(df1_central)\n assert new1.index.tz == pytz.UTC\n assert new2.index.tz == pytz.UTC\n\n # frame with Series\n new1, new2 = df1.align(df1_central[0], axis=0)\n assert new1.index.tz == pytz.UTC\n assert new2.index.tz == pytz.UTC\n\n df1[0].align(df1_central, axis=0)\n assert new1.index.tz == pytz.UTC\n assert new2.index.tz == pytz.UTC\n\n def test_align_float(self, float_frame):\n af, bf = float_frame.align(float_frame)\n assert af._mgr is not float_frame._mgr\n\n af, bf = float_frame.align(float_frame, copy=False)\n assert af._mgr is float_frame._mgr\n\n # axis = 0\n other = float_frame.iloc[:-5, :3]\n af, bf = float_frame.align(other, axis=0, fill_value=-1)\n\n tm.assert_index_equal(bf.columns, other.columns)\n\n # test fill value\n join_idx = float_frame.index.join(other.index)\n diff_a = float_frame.index.difference(join_idx)\n diff_a_vals = af.reindex(diff_a).values\n assert (diff_a_vals == -1).all()\n\n af, bf = float_frame.align(other, join=\"right\", axis=0)\n tm.assert_index_equal(bf.columns, other.columns)\n tm.assert_index_equal(bf.index, other.index)\n tm.assert_index_equal(af.index, other.index)\n\n # axis = 1\n other = float_frame.iloc[:-5, :3].copy()\n af, bf = float_frame.align(other, axis=1)\n tm.assert_index_equal(bf.columns, float_frame.columns)\n tm.assert_index_equal(bf.index, other.index)\n\n # test fill value\n join_idx = float_frame.index.join(other.index)\n diff_a = float_frame.index.difference(join_idx)\n diff_a_vals = af.reindex(diff_a).values\n\n assert (diff_a_vals == -1).all()\n\n af, bf = float_frame.align(other, join=\"inner\", axis=1)\n tm.assert_index_equal(bf.columns, other.columns)\n\n af, bf = float_frame.align(other, join=\"inner\", axis=1, method=\"pad\")\n tm.assert_index_equal(bf.columns, other.columns)\n\n af, bf = float_frame.align(\n other.iloc[:, 0], join=\"inner\", axis=1, method=None, fill_value=None\n )\n tm.assert_index_equal(bf.index, Index([]))\n\n af, bf = float_frame.align(\n other.iloc[:, 0], join=\"inner\", axis=1, method=None, fill_value=0\n )\n tm.assert_index_equal(bf.index, Index([]))\n\n # Try to align DataFrame to Series along bad axis\n msg = \"No axis named 2 for object type DataFrame\"\n with pytest.raises(ValueError, match=msg):\n float_frame.align(af.iloc[0, :3], join=\"inner\", axis=2)\n\n # align dataframe to series with broadcast or not\n idx = float_frame.index\n s = Series(range(len(idx)), index=idx)\n\n left, right = float_frame.align(s, axis=0)\n tm.assert_index_equal(left.index, float_frame.index)\n tm.assert_index_equal(right.index, float_frame.index)\n assert isinstance(right, Series)\n\n left, right = float_frame.align(s, broadcast_axis=1)\n tm.assert_index_equal(left.index, float_frame.index)\n expected = {c: s for c in float_frame.columns}\n expected = DataFrame(\n expected, index=float_frame.index, columns=float_frame.columns\n )\n tm.assert_frame_equal(right, expected)\n\n # see gh-9558\n df = DataFrame({\"a\": [1, 2, 3], \"b\": [4, 5, 6]})\n result = df[df[\"a\"] == 2]\n expected = DataFrame([[2, 5]], index=[1], columns=[\"a\", \"b\"])\n tm.assert_frame_equal(result, expected)\n\n result = df.where(df[\"a\"] == 2, 0)\n expected = DataFrame({\"a\": [0, 2, 0], \"b\": [0, 5, 0]})\n tm.assert_frame_equal(result, expected)\n\n def test_align_int(self, int_frame):\n # test other non-float types\n other = DataFrame(index=range(5), columns=[\"A\", \"B\", \"C\"])\n\n af, bf = int_frame.align(other, join=\"inner\", axis=1, method=\"pad\")\n tm.assert_index_equal(bf.columns, other.columns)\n\n def test_align_mixed_type(self, float_string_frame):\n\n af, bf = float_string_frame.align(\n float_string_frame, join=\"inner\", axis=1, method=\"pad\"\n )\n tm.assert_index_equal(bf.columns, float_string_frame.columns)\n\n def test_align_mixed_float(self, mixed_float_frame):\n # mixed floats/ints\n other = DataFrame(index=range(5), columns=[\"A\", \"B\", \"C\"])\n\n af, bf = mixed_float_frame.align(\n other.iloc[:, 0], join=\"inner\", axis=1, method=None, fill_value=0\n )\n tm.assert_index_equal(bf.index, Index([]))\n\n def test_align_mixed_int(self, mixed_int_frame):\n other = DataFrame(index=range(5), columns=[\"A\", \"B\", \"C\"])\n\n af, bf = mixed_int_frame.align(\n other.iloc[:, 0], join=\"inner\", axis=1, method=None, fill_value=0\n )\n tm.assert_index_equal(bf.index, Index([]))\n\n @pytest.mark.parametrize(\n \"l_ordered,r_ordered,expected\",\n [\n [True, True, pd.CategoricalIndex],\n [True, False, Index],\n [False, True, Index],\n [False, False, pd.CategoricalIndex],\n ],\n )\n def test_align_categorical(self, l_ordered, r_ordered, expected):\n # GH-28397\n df_1 = DataFrame(\n {\n \"A\": np.arange(6, dtype=\"int64\"),\n \"B\": Series(list(\"aabbca\")).astype(\n pd.CategoricalDtype(list(\"cab\"), ordered=l_ordered)\n ),\n }\n ).set_index(\"B\")\n df_2 = DataFrame(\n {\n \"A\": np.arange(5, dtype=\"int64\"),\n \"B\": Series(list(\"babca\")).astype(\n pd.CategoricalDtype(list(\"cab\"), ordered=r_ordered)\n ),\n }\n ).set_index(\"B\")\n\n aligned_1, aligned_2 = df_1.align(df_2)\n assert isinstance(aligned_1.index, expected)\n assert isinstance(aligned_2.index, expected)\n tm.assert_index_equal(aligned_1.index, aligned_2.index)\n\n def test_align_multiindex(self):\n # GH#10665\n # same test cases as test_align_multiindex in test_series.py\n\n midx = pd.MultiIndex.from_product(\n [range(2), range(3), range(2)], names=(\"a\", \"b\", \"c\")\n )\n idx = Index(range(2), name=\"b\")\n df1 = DataFrame(np.arange(12, dtype=\"int64\"), index=midx)\n df2 = DataFrame(np.arange(2, dtype=\"int64\"), index=idx)\n\n # these must be the same results (but flipped)\n res1l, res1r = df1.align(df2, join=\"left\")\n res2l, res2r = df2.align(df1, join=\"right\")\n\n expl = df1\n tm.assert_frame_equal(expl, res1l)\n tm.assert_frame_equal(expl, res2r)\n expr = DataFrame([0, 0, 1, 1, np.nan, np.nan] * 2, index=midx)\n tm.assert_frame_equal(expr, res1r)\n tm.assert_frame_equal(expr, res2l)\n\n res1l, res1r = df1.align(df2, join=\"right\")\n res2l, res2r = df2.align(df1, join=\"left\")\n\n exp_idx = pd.MultiIndex.from_product(\n [range(2), range(2), range(2)], names=(\"a\", \"b\", \"c\")\n )\n expl = DataFrame([0, 1, 2, 3, 6, 7, 8, 9], index=exp_idx)\n tm.assert_frame_equal(expl, res1l)\n tm.assert_frame_equal(expl, res2r)\n expr = DataFrame([0, 0, 1, 1] * 2, index=exp_idx)\n tm.assert_frame_equal(expr, res1r)\n tm.assert_frame_equal(expr, res2l)\n\n def test_align_series_combinations(self):\n df = DataFrame({\"a\": [1, 3, 5], \"b\": [1, 3, 5]}, index=list(\"ACE\"))\n s = Series([1, 2, 4], index=list(\"ABD\"), name=\"x\")\n\n # frame + series\n res1, res2 = df.align(s, axis=0)\n exp1 = DataFrame(\n {\"a\": [1, np.nan, 3, np.nan, 5], \"b\": [1, np.nan, 3, np.nan, 5]},\n index=list(\"ABCDE\"),\n )\n exp2 = Series([1, 2, np.nan, 4, np.nan], index=list(\"ABCDE\"), name=\"x\")\n\n tm.assert_frame_equal(res1, exp1)\n tm.assert_series_equal(res2, exp2)\n\n # series + frame\n res1, res2 = s.align(df)\n tm.assert_series_equal(res1, exp2)\n tm.assert_frame_equal(res2, exp1)\n\n def _check_align(self, a, b, axis, fill_axis, how, method, limit=None):\n aa, ab = a.align(\n b, axis=axis, join=how, method=method, limit=limit, fill_axis=fill_axis\n )\n\n join_index, join_columns = None, None\n\n ea, eb = a, b\n if axis is None or axis == 0:\n join_index = a.index.join(b.index, how=how)\n ea = ea.reindex(index=join_index)\n eb = eb.reindex(index=join_index)\n\n if axis is None or axis == 1:\n join_columns = a.columns.join(b.columns, how=how)\n ea = ea.reindex(columns=join_columns)\n eb = eb.reindex(columns=join_columns)\n\n ea = ea.fillna(axis=fill_axis, method=method, limit=limit)\n eb = eb.fillna(axis=fill_axis, method=method, limit=limit)\n\n tm.assert_frame_equal(aa, ea)\n tm.assert_frame_equal(ab, eb)\n\n @pytest.mark.parametrize(\"meth\", [\"pad\", \"bfill\"])\n @pytest.mark.parametrize(\"ax\", [0, 1, None])\n @pytest.mark.parametrize(\"fax\", [0, 1])\n @pytest.mark.parametrize(\"how\", [\"inner\", \"outer\", \"left\", \"right\"])\n def test_align_fill_method(self, how, meth, ax, fax, float_frame):\n df = float_frame\n self._check_align_fill(df, how, meth, ax, fax)\n\n def _check_align_fill(self, frame, kind, meth, ax, fax):\n left = frame.iloc[0:4, :10]\n right = frame.iloc[2:, 6:]\n empty = frame.iloc[:0, :0]\n\n self._check_align(left, right, axis=ax, fill_axis=fax, how=kind, method=meth)\n self._check_align(\n left, right, axis=ax, fill_axis=fax, how=kind, method=meth, limit=1\n )\n\n # empty left\n self._check_align(empty, right, axis=ax, fill_axis=fax, how=kind, method=meth)\n self._check_align(\n empty, right, axis=ax, fill_axis=fax, how=kind, method=meth, limit=1\n )\n\n # empty right\n self._check_align(left, empty, axis=ax, fill_axis=fax, how=kind, method=meth)\n self._check_align(\n left, empty, axis=ax, fill_axis=fax, how=kind, method=meth, limit=1\n )\n\n # both empty\n self._check_align(empty, empty, axis=ax, fill_axis=fax, how=kind, method=meth)\n self._check_align(\n empty, empty, axis=ax, fill_axis=fax, how=kind, method=meth, limit=1\n )\n", "\"\"\"\nTests for scalar Timedelta arithmetic ops\n\"\"\"\nfrom datetime import (\n datetime,\n timedelta,\n)\nimport operator\n\nimport numpy as np\nimport pytest\n\nfrom pandas.errors import OutOfBoundsTimedelta\n\nimport pandas as pd\nfrom pandas import (\n NaT,\n Timedelta,\n Timestamp,\n offsets,\n)\nimport pandas._testing as tm\nfrom pandas.core import ops\n\n\nclass TestTimedeltaAdditionSubtraction:\n \"\"\"\n Tests for Timedelta methods:\n\n __add__, __radd__,\n __sub__, __rsub__\n \"\"\"\n\n @pytest.mark.parametrize(\n \"ten_seconds\",\n [\n Timedelta(10, unit=\"s\"),\n timedelta(seconds=10),\n np.timedelta64(10, \"s\"),\n np.timedelta64(10000000000, \"ns\"),\n offsets.Second(10),\n ],\n )\n def test_td_add_sub_ten_seconds(self, ten_seconds):\n # GH#6808\n base = Timestamp(\"20130101 09:01:12.123456\")\n expected_add = Timestamp(\"20130101 09:01:22.123456\")\n expected_sub = Timestamp(\"20130101 09:01:02.123456\")\n\n result = base + ten_seconds\n assert result == expected_add\n\n result = base - ten_seconds\n assert result == expected_sub\n\n @pytest.mark.parametrize(\n \"one_day_ten_secs\",\n [\n Timedelta(\"1 day, 00:00:10\"),\n Timedelta(\"1 days, 00:00:10\"),\n timedelta(days=1, seconds=10),\n np.timedelta64(1, \"D\") + np.timedelta64(10, \"s\"),\n offsets.Day() + offsets.Second(10),\n ],\n )\n def test_td_add_sub_one_day_ten_seconds(self, one_day_ten_secs):\n # GH#6808\n base = Timestamp(\"20130102 09:01:12.123456\")\n expected_add = Timestamp(\"20130103 09:01:22.123456\")\n expected_sub = Timestamp(\"20130101 09:01:02.123456\")\n\n result = base + one_day_ten_secs\n assert result == expected_add\n\n result = base - one_day_ten_secs\n assert result == expected_sub\n\n @pytest.mark.parametrize(\"op\", [operator.add, ops.radd])\n def test_td_add_datetimelike_scalar(self, op):\n # GH#19738\n td = Timedelta(10, unit=\"d\")\n\n result = op(td, datetime(2016, 1, 1))\n if op is operator.add:\n # datetime + Timedelta does _not_ call Timedelta.__radd__,\n # so we get a datetime back instead of a Timestamp\n assert isinstance(result, Timestamp)\n assert result == Timestamp(2016, 1, 11)\n\n result = op(td, Timestamp(\"2018-01-12 18:09\"))\n assert isinstance(result, Timestamp)\n assert result == Timestamp(\"2018-01-22 18:09\")\n\n result = op(td, np.datetime64(\"2018-01-12\"))\n assert isinstance(result, Timestamp)\n assert result == Timestamp(\"2018-01-22\")\n\n result = op(td, NaT)\n assert result is NaT\n\n def test_td_add_timestamp_overflow(self):\n msg = \"int too (large|big) to convert\"\n with pytest.raises(OverflowError, match=msg):\n Timestamp(\"1700-01-01\") + Timedelta(13 * 19999, unit=\"D\")\n\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n Timestamp(\"1700-01-01\") + timedelta(days=13 * 19999)\n\n @pytest.mark.parametrize(\"op\", [operator.add, ops.radd])\n def test_td_add_td(self, op):\n td = Timedelta(10, unit=\"d\")\n\n result = op(td, Timedelta(days=10))\n assert isinstance(result, Timedelta)\n assert result == Timedelta(days=20)\n\n @pytest.mark.parametrize(\"op\", [operator.add, ops.radd])\n def test_td_add_pytimedelta(self, op):\n td = Timedelta(10, unit=\"d\")\n result = op(td, timedelta(days=9))\n assert isinstance(result, Timedelta)\n assert result == Timedelta(days=19)\n\n @pytest.mark.parametrize(\"op\", [operator.add, ops.radd])\n def test_td_add_timedelta64(self, op):\n td = Timedelta(10, unit=\"d\")\n result = op(td, np.timedelta64(-4, \"D\"))\n assert isinstance(result, Timedelta)\n assert result == Timedelta(days=6)\n\n @pytest.mark.parametrize(\"op\", [operator.add, ops.radd])\n def test_td_add_offset(self, op):\n td = Timedelta(10, unit=\"d\")\n\n result = op(td, offsets.Hour(6))\n assert isinstance(result, Timedelta)\n assert result == Timedelta(days=10, hours=6)\n\n def test_td_sub_td(self):\n td = Timedelta(10, unit=\"d\")\n expected = Timedelta(0, unit=\"ns\")\n result = td - td\n assert isinstance(result, Timedelta)\n assert result == expected\n\n def test_td_sub_pytimedelta(self):\n td = Timedelta(10, unit=\"d\")\n expected = Timedelta(0, unit=\"ns\")\n\n result = td - td.to_pytimedelta()\n assert isinstance(result, Timedelta)\n assert result == expected\n\n result = td.to_pytimedelta() - td\n assert isinstance(result, Timedelta)\n assert result == expected\n\n def test_td_sub_timedelta64(self):\n td = Timedelta(10, unit=\"d\")\n expected = Timedelta(0, unit=\"ns\")\n\n result = td - td.to_timedelta64()\n assert isinstance(result, Timedelta)\n assert result == expected\n\n result = td.to_timedelta64() - td\n assert isinstance(result, Timedelta)\n assert result == expected\n\n def test_td_sub_nat(self):\n # In this context pd.NaT is treated as timedelta-like\n td = Timedelta(10, unit=\"d\")\n result = td - NaT\n assert result is NaT\n\n def test_td_sub_td64_nat(self):\n td = Timedelta(10, unit=\"d\")\n td_nat = np.timedelta64(\"NaT\")\n\n result = td - td_nat\n assert result is NaT\n\n result = td_nat - td\n assert result is NaT\n\n def test_td_sub_offset(self):\n td = Timedelta(10, unit=\"d\")\n result = td - offsets.Hour(1)\n assert isinstance(result, Timedelta)\n assert result == Timedelta(239, unit=\"h\")\n\n def test_td_add_sub_numeric_raises(self):\n td = Timedelta(10, unit=\"d\")\n msg = \"unsupported operand type\"\n for other in [2, 2.0, np.int64(2), np.float64(2)]:\n with pytest.raises(TypeError, match=msg):\n td + other\n with pytest.raises(TypeError, match=msg):\n other + td\n with pytest.raises(TypeError, match=msg):\n td - other\n with pytest.raises(TypeError, match=msg):\n other - td\n\n def test_td_add_sub_int_ndarray(self):\n td = Timedelta(\"1 day\")\n other = np.array([1])\n\n msg = r\"unsupported operand type\\(s\\) for \\+: 'Timedelta' and 'int'\"\n with pytest.raises(TypeError, match=msg):\n td + np.array([1])\n\n msg = \"|\".join(\n [\n (\n r\"unsupported operand type\\(s\\) for \\+: 'numpy.ndarray' \"\n \"and 'Timedelta'\"\n ),\n # This message goes on to say \"Please do not rely on this error;\n # it may not be given on all Python implementations\"\n \"Concatenation operation is not implemented for NumPy arrays\",\n ]\n )\n with pytest.raises(TypeError, match=msg):\n other + td\n msg = r\"unsupported operand type\\(s\\) for -: 'Timedelta' and 'int'\"\n with pytest.raises(TypeError, match=msg):\n td - other\n msg = r\"unsupported operand type\\(s\\) for -: 'numpy.ndarray' and 'Timedelta'\"\n with pytest.raises(TypeError, match=msg):\n other - td\n\n def test_td_rsub_nat(self):\n td = Timedelta(10, unit=\"d\")\n result = NaT - td\n assert result is NaT\n\n result = np.datetime64(\"NaT\") - td\n assert result is NaT\n\n def test_td_rsub_offset(self):\n result = offsets.Hour(1) - Timedelta(10, unit=\"d\")\n assert isinstance(result, Timedelta)\n assert result == Timedelta(-239, unit=\"h\")\n\n def test_td_sub_timedeltalike_object_dtype_array(self):\n # GH#21980\n arr = np.array([Timestamp(\"20130101 9:01\"), Timestamp(\"20121230 9:02\")])\n exp = np.array([Timestamp(\"20121231 9:01\"), Timestamp(\"20121229 9:02\")])\n res = arr - Timedelta(\"1D\")\n tm.assert_numpy_array_equal(res, exp)\n\n def test_td_sub_mixed_most_timedeltalike_object_dtype_array(self):\n # GH#21980\n now = Timestamp(\"2021-11-09 09:54:00\")\n arr = np.array([now, Timedelta(\"1D\"), np.timedelta64(2, \"h\")])\n exp = np.array(\n [\n now - Timedelta(\"1D\"),\n Timedelta(\"0D\"),\n np.timedelta64(2, \"h\") - Timedelta(\"1D\"),\n ]\n )\n res = arr - Timedelta(\"1D\")\n tm.assert_numpy_array_equal(res, exp)\n\n def test_td_rsub_mixed_most_timedeltalike_object_dtype_array(self):\n # GH#21980\n now = Timestamp(\"2021-11-09 09:54:00\")\n arr = np.array([now, Timedelta(\"1D\"), np.timedelta64(2, \"h\")])\n msg = r\"unsupported operand type\\(s\\) for \\-: 'Timedelta' and 'Timestamp'\"\n with pytest.raises(TypeError, match=msg):\n Timedelta(\"1D\") - arr\n\n @pytest.mark.parametrize(\"op\", [operator.add, ops.radd])\n def test_td_add_timedeltalike_object_dtype_array(self, op):\n # GH#21980\n arr = np.array([Timestamp(\"20130101 9:01\"), Timestamp(\"20121230 9:02\")])\n exp = np.array([Timestamp(\"20130102 9:01\"), Timestamp(\"20121231 9:02\")])\n res = op(arr, Timedelta(\"1D\"))\n tm.assert_numpy_array_equal(res, exp)\n\n @pytest.mark.parametrize(\"op\", [operator.add, ops.radd])\n def test_td_add_mixed_timedeltalike_object_dtype_array(self, op):\n # GH#21980\n now = Timestamp(\"2021-11-09 09:54:00\")\n arr = np.array([now, Timedelta(\"1D\")])\n exp = np.array([now + Timedelta(\"1D\"), Timedelta(\"2D\")])\n res = op(arr, Timedelta(\"1D\"))\n tm.assert_numpy_array_equal(res, exp)\n\n def test_td_add_sub_td64_ndarray(self):\n td = Timedelta(\"1 day\")\n\n other = np.array([td.to_timedelta64()])\n expected = np.array([Timedelta(\"2 Days\").to_timedelta64()])\n\n result = td + other\n tm.assert_numpy_array_equal(result, expected)\n result = other + td\n tm.assert_numpy_array_equal(result, expected)\n\n result = td - other\n tm.assert_numpy_array_equal(result, expected * 0)\n result = other - td\n tm.assert_numpy_array_equal(result, expected * 0)\n\n def test_td_add_sub_dt64_ndarray(self):\n td = Timedelta(\"1 day\")\n other = pd.to_datetime([\"2000-01-01\"]).values\n\n expected = pd.to_datetime([\"2000-01-02\"]).values\n tm.assert_numpy_array_equal(td + other, expected)\n tm.assert_numpy_array_equal(other + td, expected)\n\n expected = pd.to_datetime([\"1999-12-31\"]).values\n tm.assert_numpy_array_equal(-td + other, expected)\n tm.assert_numpy_array_equal(other - td, expected)\n\n\nclass TestTimedeltaMultiplicationDivision:\n \"\"\"\n Tests for Timedelta methods:\n\n __mul__, __rmul__,\n __div__, __rdiv__,\n __truediv__, __rtruediv__,\n __floordiv__, __rfloordiv__,\n __mod__, __rmod__,\n __divmod__, __rdivmod__\n \"\"\"\n\n # ---------------------------------------------------------------\n # Timedelta.__mul__, __rmul__\n\n @pytest.mark.parametrize(\n \"td_nat\", [NaT, np.timedelta64(\"NaT\", \"ns\"), np.timedelta64(\"NaT\")]\n )\n @pytest.mark.parametrize(\"op\", [operator.mul, ops.rmul])\n def test_td_mul_nat(self, op, td_nat):\n # GH#19819\n td = Timedelta(10, unit=\"d\")\n typs = \"|\".join([\"numpy.timedelta64\", \"NaTType\", \"Timedelta\"])\n msg = \"|\".join(\n [\n rf\"unsupported operand type\\(s\\) for \\*: '{typs}' and '{typs}'\",\n r\"ufunc '?multiply'? cannot use operands with types\",\n ]\n )\n with pytest.raises(TypeError, match=msg):\n op(td, td_nat)\n\n @pytest.mark.parametrize(\"nan\", [np.nan, np.float64(\"NaN\"), float(\"nan\")])\n @pytest.mark.parametrize(\"op\", [operator.mul, ops.rmul])\n def test_td_mul_nan(self, op, nan):\n # np.float64('NaN') has a 'dtype' attr, avoid treating as array\n td = Timedelta(10, unit=\"d\")\n result = op(td, nan)\n assert result is NaT\n\n @pytest.mark.parametrize(\"op\", [operator.mul, ops.rmul])\n def test_td_mul_scalar(self, op):\n # GH#19738\n td = Timedelta(minutes=3)\n\n result = op(td, 2)\n assert result == Timedelta(minutes=6)\n\n result = op(td, 1.5)\n assert result == Timedelta(minutes=4, seconds=30)\n\n assert op(td, np.nan) is NaT\n\n assert op(-1, td).value == -1 * td.value\n assert op(-1.0, td).value == -1.0 * td.value\n\n msg = \"unsupported operand type\"\n with pytest.raises(TypeError, match=msg):\n # timedelta * datetime is gibberish\n op(td, Timestamp(2016, 1, 2))\n\n with pytest.raises(TypeError, match=msg):\n # invalid multiply with another timedelta\n op(td, td)\n\n def test_td_mul_numeric_ndarray(self):\n td = Timedelta(\"1 day\")\n other = np.array([2])\n expected = np.array([Timedelta(\"2 Days\").to_timedelta64()])\n\n result = td * other\n tm.assert_numpy_array_equal(result, expected)\n\n result = other * td\n tm.assert_numpy_array_equal(result, expected)\n\n def test_td_mul_td64_ndarray_invalid(self):\n td = Timedelta(\"1 day\")\n other = np.array([Timedelta(\"2 Days\").to_timedelta64()])\n\n msg = (\n \"ufunc '?multiply'? cannot use operands with types \"\n r\"dtype\\('<m8\\[ns\\]'\\) and dtype\\('<m8\\[ns\\]'\\)\"\n )\n with pytest.raises(TypeError, match=msg):\n td * other\n with pytest.raises(TypeError, match=msg):\n other * td\n\n # ---------------------------------------------------------------\n # Timedelta.__div__, __truediv__\n\n def test_td_div_timedeltalike_scalar(self):\n # GH#19738\n td = Timedelta(10, unit=\"d\")\n\n result = td / offsets.Hour(1)\n assert result == 240\n\n assert td / td == 1\n assert td / np.timedelta64(60, \"h\") == 4\n\n assert np.isnan(td / NaT)\n\n def test_td_div_td64_non_nano(self):\n\n # truediv\n td = Timedelta(\"1 days 2 hours 3 ns\")\n result = td / np.timedelta64(1, \"D\")\n assert result == td.value / (86400 * 10**9)\n result = td / np.timedelta64(1, \"s\")\n assert result == td.value / 10**9\n result = td / np.timedelta64(1, \"ns\")\n assert result == td.value\n\n # floordiv\n td = Timedelta(\"1 days 2 hours 3 ns\")\n result = td // np.timedelta64(1, \"D\")\n assert result == 1\n result = td // np.timedelta64(1, \"s\")\n assert result == 93600\n result = td // np.timedelta64(1, \"ns\")\n assert result == td.value\n\n def test_td_div_numeric_scalar(self):\n # GH#19738\n td = Timedelta(10, unit=\"d\")\n\n result = td / 2\n assert isinstance(result, Timedelta)\n assert result == Timedelta(days=5)\n\n result = td / 5\n assert isinstance(result, Timedelta)\n assert result == Timedelta(days=2)\n\n @pytest.mark.parametrize(\n \"nan\",\n [\n np.nan,\n np.float64(\"NaN\"),\n float(\"nan\"),\n ],\n )\n def test_td_div_nan(self, nan):\n # np.float64('NaN') has a 'dtype' attr, avoid treating as array\n td = Timedelta(10, unit=\"d\")\n result = td / nan\n assert result is NaT\n\n result = td // nan\n assert result is NaT\n\n def test_td_div_td64_ndarray(self):\n td = Timedelta(\"1 day\")\n\n other = np.array([Timedelta(\"2 Days\").to_timedelta64()])\n expected = np.array([0.5])\n\n result = td / other\n tm.assert_numpy_array_equal(result, expected)\n\n result = other / td\n tm.assert_numpy_array_equal(result, expected * 4)\n\n # ---------------------------------------------------------------\n # Timedelta.__rdiv__\n\n def test_td_rdiv_timedeltalike_scalar(self):\n # GH#19738\n td = Timedelta(10, unit=\"d\")\n result = offsets.Hour(1) / td\n assert result == 1 / 240.0\n\n assert np.timedelta64(60, \"h\") / td == 0.25\n\n def test_td_rdiv_na_scalar(self):\n # GH#31869 None gets cast to NaT\n td = Timedelta(10, unit=\"d\")\n\n result = NaT / td\n assert np.isnan(result)\n\n result = None / td\n assert np.isnan(result)\n\n result = np.timedelta64(\"NaT\") / td\n assert np.isnan(result)\n\n msg = r\"unsupported operand type\\(s\\) for /: 'numpy.datetime64' and 'Timedelta'\"\n with pytest.raises(TypeError, match=msg):\n np.datetime64(\"NaT\") / td\n\n msg = r\"unsupported operand type\\(s\\) for /: 'float' and 'Timedelta'\"\n with pytest.raises(TypeError, match=msg):\n np.nan / td\n\n def test_td_rdiv_ndarray(self):\n td = Timedelta(10, unit=\"d\")\n\n arr = np.array([td], dtype=object)\n result = arr / td\n expected = np.array([1], dtype=np.float64)\n tm.assert_numpy_array_equal(result, expected)\n\n arr = np.array([None])\n result = arr / td\n expected = np.array([np.nan])\n tm.assert_numpy_array_equal(result, expected)\n\n arr = np.array([np.nan], dtype=object)\n msg = r\"unsupported operand type\\(s\\) for /: 'float' and 'Timedelta'\"\n with pytest.raises(TypeError, match=msg):\n arr / td\n\n arr = np.array([np.nan], dtype=np.float64)\n msg = \"cannot use operands with types dtype\"\n with pytest.raises(TypeError, match=msg):\n arr / td\n\n # ---------------------------------------------------------------\n # Timedelta.__floordiv__\n\n def test_td_floordiv_timedeltalike_scalar(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=4)\n scalar = Timedelta(hours=3, minutes=3)\n\n assert td // scalar == 1\n assert -td // scalar.to_pytimedelta() == -2\n assert (2 * td) // scalar.to_timedelta64() == 2\n\n def test_td_floordiv_null_scalar(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=4)\n\n assert td // np.nan is NaT\n assert np.isnan(td // NaT)\n assert np.isnan(td // np.timedelta64(\"NaT\"))\n\n def test_td_floordiv_offsets(self):\n # GH#19738\n td = Timedelta(hours=3, minutes=4)\n assert td // offsets.Hour(1) == 3\n assert td // offsets.Minute(2) == 92\n\n def test_td_floordiv_invalid_scalar(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=4)\n\n msg = \"|\".join(\n [\n r\"Invalid dtype datetime64\\[D\\] for __floordiv__\",\n \"'dtype' is an invalid keyword argument for this function\",\n r\"ufunc '?floor_divide'? cannot use operands with types\",\n ]\n )\n with pytest.raises(TypeError, match=msg):\n td // np.datetime64(\"2016-01-01\", dtype=\"datetime64[us]\")\n\n def test_td_floordiv_numeric_scalar(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=4)\n\n expected = Timedelta(hours=1, minutes=32)\n assert td // 2 == expected\n assert td // 2.0 == expected\n assert td // np.float64(2.0) == expected\n assert td // np.int32(2.0) == expected\n assert td // np.uint8(2.0) == expected\n\n def test_td_floordiv_timedeltalike_array(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=4)\n scalar = Timedelta(hours=3, minutes=3)\n\n # Array-like others\n assert td // np.array(scalar.to_timedelta64()) == 1\n\n res = (3 * td) // np.array([scalar.to_timedelta64()])\n expected = np.array([3], dtype=np.int64)\n tm.assert_numpy_array_equal(res, expected)\n\n res = (10 * td) // np.array([scalar.to_timedelta64(), np.timedelta64(\"NaT\")])\n expected = np.array([10, np.nan])\n tm.assert_numpy_array_equal(res, expected)\n\n def test_td_floordiv_numeric_series(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=4)\n ser = pd.Series([1], dtype=np.int64)\n res = td // ser\n assert res.dtype.kind == \"m\"\n\n # ---------------------------------------------------------------\n # Timedelta.__rfloordiv__\n\n def test_td_rfloordiv_timedeltalike_scalar(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=3)\n scalar = Timedelta(hours=3, minutes=4)\n\n # scalar others\n # x // Timedelta is defined only for timedelta-like x. int-like,\n # float-like, and date-like, in particular, should all either\n # a) raise TypeError directly or\n # b) return NotImplemented, following which the reversed\n # operation will raise TypeError.\n assert td.__rfloordiv__(scalar) == 1\n assert (-td).__rfloordiv__(scalar.to_pytimedelta()) == -2\n assert (2 * td).__rfloordiv__(scalar.to_timedelta64()) == 0\n\n def test_td_rfloordiv_null_scalar(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=3)\n\n assert np.isnan(td.__rfloordiv__(NaT))\n assert np.isnan(td.__rfloordiv__(np.timedelta64(\"NaT\")))\n\n def test_td_rfloordiv_offsets(self):\n # GH#19738\n assert offsets.Hour(1) // Timedelta(minutes=25) == 2\n\n def test_td_rfloordiv_invalid_scalar(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=3)\n\n dt64 = np.datetime64(\"2016-01-01\", \"us\")\n\n assert td.__rfloordiv__(dt64) is NotImplemented\n\n msg = (\n r\"unsupported operand type\\(s\\) for //: 'numpy.datetime64' and 'Timedelta'\"\n )\n with pytest.raises(TypeError, match=msg):\n dt64 // td\n\n def test_td_rfloordiv_numeric_scalar(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=3)\n\n assert td.__rfloordiv__(np.nan) is NotImplemented\n assert td.__rfloordiv__(3.5) is NotImplemented\n assert td.__rfloordiv__(2) is NotImplemented\n assert td.__rfloordiv__(np.float64(2.0)) is NotImplemented\n assert td.__rfloordiv__(np.uint8(9)) is NotImplemented\n assert td.__rfloordiv__(np.int32(2.0)) is NotImplemented\n\n msg = r\"unsupported operand type\\(s\\) for //: '.*' and 'Timedelta\"\n with pytest.raises(TypeError, match=msg):\n np.float64(2.0) // td\n with pytest.raises(TypeError, match=msg):\n np.uint8(9) // td\n with pytest.raises(TypeError, match=msg):\n # deprecated GH#19761, enforced GH#29797\n np.int32(2.0) // td\n\n def test_td_rfloordiv_timedeltalike_array(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=3)\n scalar = Timedelta(hours=3, minutes=4)\n\n # Array-like others\n assert td.__rfloordiv__(np.array(scalar.to_timedelta64())) == 1\n\n res = td.__rfloordiv__(np.array([(3 * scalar).to_timedelta64()]))\n expected = np.array([3], dtype=np.int64)\n tm.assert_numpy_array_equal(res, expected)\n\n arr = np.array([(10 * scalar).to_timedelta64(), np.timedelta64(\"NaT\")])\n res = td.__rfloordiv__(arr)\n expected = np.array([10, np.nan])\n tm.assert_numpy_array_equal(res, expected)\n\n def test_td_rfloordiv_intarray(self):\n # deprecated GH#19761, enforced GH#29797\n ints = np.array([1349654400, 1349740800, 1349827200, 1349913600]) * 10**9\n\n msg = \"Invalid dtype\"\n with pytest.raises(TypeError, match=msg):\n ints // Timedelta(1, unit=\"s\")\n\n def test_td_rfloordiv_numeric_series(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=3)\n ser = pd.Series([1], dtype=np.int64)\n res = td.__rfloordiv__(ser)\n assert res is NotImplemented\n\n msg = \"Invalid dtype\"\n with pytest.raises(TypeError, match=msg):\n # Deprecated GH#19761, enforced GH#29797\n ser // td\n\n # ----------------------------------------------------------------\n # Timedelta.__mod__, __rmod__\n\n def test_mod_timedeltalike(self):\n # GH#19365\n td = Timedelta(hours=37)\n\n # Timedelta-like others\n result = td % Timedelta(hours=6)\n assert isinstance(result, Timedelta)\n assert result == Timedelta(hours=1)\n\n result = td % timedelta(minutes=60)\n assert isinstance(result, Timedelta)\n assert result == Timedelta(0)\n\n result = td % NaT\n assert result is NaT\n\n def test_mod_timedelta64_nat(self):\n # GH#19365\n td = Timedelta(hours=37)\n\n result = td % np.timedelta64(\"NaT\", \"ns\")\n assert result is NaT\n\n def test_mod_timedelta64(self):\n # GH#19365\n td = Timedelta(hours=37)\n\n result = td % np.timedelta64(2, \"h\")\n assert isinstance(result, Timedelta)\n assert result == Timedelta(hours=1)\n\n def test_mod_offset(self):\n # GH#19365\n td = Timedelta(hours=37)\n\n result = td % offsets.Hour(5)\n assert isinstance(result, Timedelta)\n assert result == Timedelta(hours=2)\n\n def test_mod_numeric(self):\n # GH#19365\n td = Timedelta(hours=37)\n\n # Numeric Others\n result = td % 2\n assert isinstance(result, Timedelta)\n assert result == Timedelta(0)\n\n result = td % 1e12\n assert isinstance(result, Timedelta)\n assert result == Timedelta(minutes=3, seconds=20)\n\n result = td % int(1e12)\n assert isinstance(result, Timedelta)\n assert result == Timedelta(minutes=3, seconds=20)\n\n def test_mod_invalid(self):\n # GH#19365\n td = Timedelta(hours=37)\n msg = \"unsupported operand type\"\n with pytest.raises(TypeError, match=msg):\n td % Timestamp(\"2018-01-22\")\n\n with pytest.raises(TypeError, match=msg):\n td % []\n\n def test_rmod_pytimedelta(self):\n # GH#19365\n td = Timedelta(minutes=3)\n\n result = timedelta(minutes=4) % td\n assert isinstance(result, Timedelta)\n assert result == Timedelta(minutes=1)\n\n def test_rmod_timedelta64(self):\n # GH#19365\n td = Timedelta(minutes=3)\n result = np.timedelta64(5, \"m\") % td\n assert isinstance(result, Timedelta)\n assert result == Timedelta(minutes=2)\n\n def test_rmod_invalid(self):\n # GH#19365\n td = Timedelta(minutes=3)\n\n msg = \"unsupported operand\"\n with pytest.raises(TypeError, match=msg):\n Timestamp(\"2018-01-22\") % td\n\n with pytest.raises(TypeError, match=msg):\n 15 % td\n\n with pytest.raises(TypeError, match=msg):\n 16.0 % td\n\n msg = \"Invalid dtype int\"\n with pytest.raises(TypeError, match=msg):\n np.array([22, 24]) % td\n\n # ----------------------------------------------------------------\n # Timedelta.__divmod__, __rdivmod__\n\n def test_divmod_numeric(self):\n # GH#19365\n td = Timedelta(days=2, hours=6)\n\n result = divmod(td, 53 * 3600 * 1e9)\n assert result[0] == Timedelta(1, unit=\"ns\")\n assert isinstance(result[1], Timedelta)\n assert result[1] == Timedelta(hours=1)\n\n assert result\n result = divmod(td, np.nan)\n assert result[0] is NaT\n assert result[1] is NaT\n\n def test_divmod(self):\n # GH#19365\n td = Timedelta(days=2, hours=6)\n\n result = divmod(td, timedelta(days=1))\n assert result[0] == 2\n assert isinstance(result[1], Timedelta)\n assert result[1] == Timedelta(hours=6)\n\n result = divmod(td, 54)\n assert result[0] == Timedelta(hours=1)\n assert isinstance(result[1], Timedelta)\n assert result[1] == Timedelta(0)\n\n result = divmod(td, NaT)\n assert np.isnan(result[0])\n assert result[1] is NaT\n\n def test_divmod_offset(self):\n # GH#19365\n td = Timedelta(days=2, hours=6)\n\n result = divmod(td, offsets.Hour(-4))\n assert result[0] == -14\n assert isinstance(result[1], Timedelta)\n assert result[1] == Timedelta(hours=-2)\n\n def test_divmod_invalid(self):\n # GH#19365\n td = Timedelta(days=2, hours=6)\n\n msg = r\"unsupported operand type\\(s\\) for //: 'Timedelta' and 'Timestamp'\"\n with pytest.raises(TypeError, match=msg):\n divmod(td, Timestamp(\"2018-01-22\"))\n\n def test_rdivmod_pytimedelta(self):\n # GH#19365\n result = divmod(timedelta(days=2, hours=6), Timedelta(days=1))\n assert result[0] == 2\n assert isinstance(result[1], Timedelta)\n assert result[1] == Timedelta(hours=6)\n\n def test_rdivmod_offset(self):\n result = divmod(offsets.Hour(54), Timedelta(hours=-4))\n assert result[0] == -14\n assert isinstance(result[1], Timedelta)\n assert result[1] == Timedelta(hours=-2)\n\n def test_rdivmod_invalid(self):\n # GH#19365\n td = Timedelta(minutes=3)\n msg = \"unsupported operand type\"\n\n with pytest.raises(TypeError, match=msg):\n divmod(Timestamp(\"2018-01-22\"), td)\n\n with pytest.raises(TypeError, match=msg):\n divmod(15, td)\n\n with pytest.raises(TypeError, match=msg):\n divmod(16.0, td)\n\n msg = \"Invalid dtype int\"\n with pytest.raises(TypeError, match=msg):\n divmod(np.array([22, 24]), td)\n\n # ----------------------------------------------------------------\n\n @pytest.mark.parametrize(\n \"op\", [operator.mul, ops.rmul, operator.truediv, ops.rdiv, ops.rsub]\n )\n @pytest.mark.parametrize(\n \"arr\",\n [\n np.array([Timestamp(\"20130101 9:01\"), Timestamp(\"20121230 9:02\")]),\n np.array([Timestamp(\"2021-11-09 09:54:00\"), Timedelta(\"1D\")]),\n ],\n )\n def test_td_op_timedelta_timedeltalike_array(self, op, arr):\n msg = \"unsupported operand type|cannot use operands with types\"\n with pytest.raises(TypeError, match=msg):\n op(arr, Timedelta(\"1D\"))\n\n\nclass TestTimedeltaComparison:\n def test_compare_tick(self, tick_classes):\n cls = tick_classes\n\n off = cls(4)\n td = off.delta\n assert isinstance(td, Timedelta)\n\n assert td == off\n assert not td != off\n assert td <= off\n assert td >= off\n assert not td < off\n assert not td > off\n\n assert not td == 2 * off\n assert td != 2 * off\n assert td <= 2 * off\n assert td < 2 * off\n assert not td >= 2 * off\n assert not td > 2 * off\n\n def test_comparison_object_array(self):\n # analogous to GH#15183\n td = Timedelta(\"2 days\")\n other = Timedelta(\"3 hours\")\n\n arr = np.array([other, td], dtype=object)\n res = arr == td\n expected = np.array([False, True], dtype=bool)\n assert (res == expected).all()\n\n # 2D case\n arr = np.array([[other, td], [td, other]], dtype=object)\n res = arr != td\n expected = np.array([[True, False], [False, True]], dtype=bool)\n assert res.shape == expected.shape\n assert (res == expected).all()\n\n def test_compare_timedelta_ndarray(self):\n # GH#11835\n periods = [Timedelta(\"0 days 01:00:00\"), Timedelta(\"0 days 01:00:00\")]\n arr = np.array(periods)\n result = arr[0] > arr\n expected = np.array([False, False])\n tm.assert_numpy_array_equal(result, expected)\n\n def test_compare_td64_ndarray(self):\n # GG#33441\n arr = np.arange(5).astype(\"timedelta64[ns]\")\n td = Timedelta(arr[1])\n\n expected = np.array([False, True, False, False, False], dtype=bool)\n\n result = td == arr\n tm.assert_numpy_array_equal(result, expected)\n\n result = arr == td\n tm.assert_numpy_array_equal(result, expected)\n\n result = td != arr\n tm.assert_numpy_array_equal(result, ~expected)\n\n result = arr != td\n tm.assert_numpy_array_equal(result, ~expected)\n\n def test_compare_custom_object(self):\n \"\"\"\n Make sure non supported operations on Timedelta returns NonImplemented\n and yields to other operand (GH#20829).\n \"\"\"\n\n class CustomClass:\n def __init__(self, cmp_result=None):\n self.cmp_result = cmp_result\n\n def generic_result(self):\n if self.cmp_result is None:\n return NotImplemented\n else:\n return self.cmp_result\n\n def __eq__(self, other):\n return self.generic_result()\n\n def __gt__(self, other):\n return self.generic_result()\n\n t = Timedelta(\"1s\")\n\n assert not (t == \"string\")\n assert not (t == 1)\n assert not (t == CustomClass())\n assert not (t == CustomClass(cmp_result=False))\n\n assert t < CustomClass(cmp_result=True)\n assert not (t < CustomClass(cmp_result=False))\n\n assert t == CustomClass(cmp_result=True)\n\n @pytest.mark.parametrize(\"val\", [\"string\", 1])\n def test_compare_unknown_type(self, val):\n # GH#20829\n t = Timedelta(\"1s\")\n msg = \"not supported between instances of 'Timedelta' and '(int|str)'\"\n with pytest.raises(TypeError, match=msg):\n t >= val\n with pytest.raises(TypeError, match=msg):\n t > val\n with pytest.raises(TypeError, match=msg):\n t <= val\n with pytest.raises(TypeError, match=msg):\n t < val\n\n\ndef test_ops_notimplemented():\n class Other:\n pass\n\n other = Other()\n\n td = Timedelta(\"1 day\")\n assert td.__add__(other) is NotImplemented\n assert td.__sub__(other) is NotImplemented\n assert td.__truediv__(other) is NotImplemented\n assert td.__mul__(other) is NotImplemented\n assert td.__floordiv__(other) is NotImplemented\n\n\ndef test_ops_error_str():\n # GH#13624\n td = Timedelta(\"1 day\")\n\n for left, right in [(td, \"a\"), (\"a\", td)]:\n\n msg = \"|\".join(\n [\n \"unsupported operand type\",\n r'can only concatenate str \\(not \"Timedelta\"\\) to str',\n \"must be str, not Timedelta\",\n ]\n )\n with pytest.raises(TypeError, match=msg):\n left + right\n\n msg = \"not supported between instances of\"\n with pytest.raises(TypeError, match=msg):\n left > right\n\n assert not left == right\n assert left != right\n", "import os\nimport shlex\nimport subprocess\nimport time\n\nimport pytest\n\nfrom pandas.compat import (\n is_ci_environment,\n is_platform_arm,\n is_platform_mac,\n is_platform_windows,\n)\nimport pandas.util._test_decorators as td\n\nimport pandas._testing as tm\n\nfrom pandas.io.parsers import read_csv\n\n\[email protected]\ndef tips_file(datapath):\n \"\"\"Path to the tips dataset\"\"\"\n return datapath(\"io\", \"data\", \"csv\", \"tips.csv\")\n\n\[email protected]\ndef jsonl_file(datapath):\n \"\"\"Path to a JSONL dataset\"\"\"\n return datapath(\"io\", \"parser\", \"data\", \"items.jsonl\")\n\n\[email protected]\ndef salaries_table(datapath):\n \"\"\"DataFrame with the salaries dataset\"\"\"\n return read_csv(datapath(\"io\", \"parser\", \"data\", \"salaries.csv\"), sep=\"\\t\")\n\n\[email protected]\ndef feather_file(datapath):\n return datapath(\"io\", \"data\", \"feather\", \"feather-0_3_1.feather\")\n\n\[email protected]\ndef s3so(worker_id):\n if is_ci_environment():\n url = \"http://localhost:5000/\"\n else:\n worker_id = \"5\" if worker_id == \"master\" else worker_id.lstrip(\"gw\")\n url = f\"http://127.0.0.1:555{worker_id}/\"\n return {\"client_kwargs\": {\"endpoint_url\": url}}\n\n\[email protected](scope=\"session\")\ndef s3_base(worker_id):\n \"\"\"\n Fixture for mocking S3 interaction.\n\n Sets up moto server in separate process locally\n Return url for motoserver/moto CI service\n \"\"\"\n pytest.importorskip(\"s3fs\")\n pytest.importorskip(\"boto3\")\n\n with tm.ensure_safe_environment_variables():\n # temporary workaround as moto fails for botocore >= 1.11 otherwise,\n # see https://github.com/spulec/moto/issues/1924 & 1952\n os.environ.setdefault(\"AWS_ACCESS_KEY_ID\", \"foobar_key\")\n os.environ.setdefault(\"AWS_SECRET_ACCESS_KEY\", \"foobar_secret\")\n if is_ci_environment():\n if is_platform_arm() or is_platform_mac() or is_platform_windows():\n # NOT RUN on Windows/MacOS/ARM, only Ubuntu\n # - subprocess in CI can cause timeouts\n # - Azure pipelines/Github Actions do not support\n # container services for the above OSs\n # - CircleCI will probably hit the Docker rate pull limit\n pytest.skip(\n \"S3 tests do not have a corresponding service in \"\n \"Windows, MacOS or ARM platforms\"\n )\n else:\n yield \"http://localhost:5000\"\n else:\n requests = pytest.importorskip(\"requests\")\n pytest.importorskip(\"moto\", minversion=\"1.3.14\")\n pytest.importorskip(\"flask\") # server mode needs flask too\n\n # Launching moto in server mode, i.e., as a separate process\n # with an S3 endpoint on localhost\n\n worker_id = \"5\" if worker_id == \"master\" else worker_id.lstrip(\"gw\")\n endpoint_port = f\"555{worker_id}\"\n endpoint_uri = f\"http://127.0.0.1:{endpoint_port}/\"\n\n # pipe to null to avoid logging in terminal\n with subprocess.Popen(\n shlex.split(f\"moto_server s3 -p {endpoint_port}\"),\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL,\n ) as proc:\n\n timeout = 5\n while timeout > 0:\n try:\n # OK to go once server is accepting connections\n r = requests.get(endpoint_uri)\n if r.ok:\n break\n except Exception:\n pass\n timeout -= 0.1\n time.sleep(0.1)\n yield endpoint_uri\n\n proc.terminate()\n\n\[email protected]\ndef s3_resource(s3_base, tips_file, jsonl_file, feather_file):\n \"\"\"\n Sets up S3 bucket with contents\n\n The primary bucket name is \"pandas-test\". The following datasets\n are loaded.\n\n - tips.csv\n - tips.csv.gz\n - tips.csv.bz2\n - items.jsonl\n\n A private bucket \"cant_get_it\" is also created. The boto3 s3 resource\n is yielded by the fixture.\n \"\"\"\n import boto3\n import s3fs\n\n test_s3_files = [\n (\"tips#1.csv\", tips_file),\n (\"tips.csv\", tips_file),\n (\"tips.csv.gz\", tips_file + \".gz\"),\n (\"tips.csv.bz2\", tips_file + \".bz2\"),\n (\"items.jsonl\", jsonl_file),\n (\"simple_dataset.feather\", feather_file),\n ]\n\n def add_tips_files(bucket_name):\n for s3_key, file_name in test_s3_files:\n with open(file_name, \"rb\") as f:\n cli.put_object(Bucket=bucket_name, Key=s3_key, Body=f)\n\n bucket = \"pandas-test\"\n conn = boto3.resource(\"s3\", endpoint_url=s3_base)\n cli = boto3.client(\"s3\", endpoint_url=s3_base)\n\n try:\n cli.create_bucket(Bucket=bucket)\n except Exception:\n # OK is bucket already exists\n pass\n try:\n cli.create_bucket(Bucket=\"cant_get_it\", ACL=\"private\")\n except Exception:\n # OK is bucket already exists\n pass\n timeout = 2\n while not cli.list_buckets()[\"Buckets\"] and timeout > 0:\n time.sleep(0.1)\n timeout -= 0.1\n\n add_tips_files(bucket)\n add_tips_files(\"cant_get_it\")\n s3fs.S3FileSystem.clear_instance_cache()\n yield conn\n\n s3 = s3fs.S3FileSystem(client_kwargs={\"endpoint_url\": s3_base})\n\n try:\n s3.rm(bucket, recursive=True)\n except Exception:\n pass\n try:\n s3.rm(\"cant_get_it\", recursive=True)\n except Exception:\n pass\n timeout = 2\n while cli.list_buckets()[\"Buckets\"] and timeout > 0:\n time.sleep(0.1)\n timeout -= 0.1\n\n\n_compression_formats_params = [\n (\".no_compress\", None),\n (\"\", None),\n (\".gz\", \"gzip\"),\n (\".GZ\", \"gzip\"),\n (\".bz2\", \"bz2\"),\n (\".BZ2\", \"bz2\"),\n (\".zip\", \"zip\"),\n (\".ZIP\", \"zip\"),\n (\".xz\", \"xz\"),\n (\".XZ\", \"xz\"),\n pytest.param((\".zst\", \"zstd\"), marks=td.skip_if_no(\"zstandard\")),\n pytest.param((\".ZST\", \"zstd\"), marks=td.skip_if_no(\"zstandard\")),\n]\n\n\[email protected](params=_compression_formats_params[1:])\ndef compression_format(request):\n return request.param\n\n\[email protected](params=_compression_formats_params)\ndef compression_ext(request):\n return request.param[0]\n", "import numpy as np\nimport warnings\n\nfrom ._base import _fit_liblinear, BaseSVC, BaseLibSVM\nfrom ..base import BaseEstimator, RegressorMixin, OutlierMixin\nfrom ..linear_model._base import LinearClassifierMixin, SparseCoefMixin, LinearModel\nfrom ..utils.validation import _num_samples\nfrom ..utils.multiclass import check_classification_targets\n\n\nclass LinearSVC(LinearClassifierMixin, SparseCoefMixin, BaseEstimator):\n \"\"\"Linear Support Vector Classification.\n\n Similar to SVC with parameter kernel='linear', but implemented in terms of\n liblinear rather than libsvm, so it has more flexibility in the choice of\n penalties and loss functions and should scale better to large numbers of\n samples.\n\n This class supports both dense and sparse input and the multiclass support\n is handled according to a one-vs-the-rest scheme.\n\n Read more in the :ref:`User Guide <svm_classification>`.\n\n Parameters\n ----------\n penalty : {'l1', 'l2'}, default='l2'\n Specifies the norm used in the penalization. The 'l2'\n penalty is the standard used in SVC. The 'l1' leads to ``coef_``\n vectors that are sparse.\n\n loss : {'hinge', 'squared_hinge'}, default='squared_hinge'\n Specifies the loss function. 'hinge' is the standard SVM loss\n (used e.g. by the SVC class) while 'squared_hinge' is the\n square of the hinge loss. The combination of ``penalty='l1'``\n and ``loss='hinge'`` is not supported.\n\n dual : bool, default=True\n Select the algorithm to either solve the dual or primal\n optimization problem. Prefer dual=False when n_samples > n_features.\n\n tol : float, default=1e-4\n Tolerance for stopping criteria.\n\n C : float, default=1.0\n Regularization parameter. The strength of the regularization is\n inversely proportional to C. Must be strictly positive.\n\n multi_class : {'ovr', 'crammer_singer'}, default='ovr'\n Determines the multi-class strategy if `y` contains more than\n two classes.\n ``\"ovr\"`` trains n_classes one-vs-rest classifiers, while\n ``\"crammer_singer\"`` optimizes a joint objective over all classes.\n While `crammer_singer` is interesting from a theoretical perspective\n as it is consistent, it is seldom used in practice as it rarely leads\n to better accuracy and is more expensive to compute.\n If ``\"crammer_singer\"`` is chosen, the options loss, penalty and dual\n will be ignored.\n\n fit_intercept : bool, default=True\n Whether to calculate the intercept for this model. If set\n to false, no intercept will be used in calculations\n (i.e. data is expected to be already centered).\n\n intercept_scaling : float, default=1\n When self.fit_intercept is True, instance vector x becomes\n ``[x, self.intercept_scaling]``,\n i.e. a \"synthetic\" feature with constant value equals to\n intercept_scaling is appended to the instance vector.\n The intercept becomes intercept_scaling * synthetic feature weight\n Note! the synthetic feature weight is subject to l1/l2 regularization\n as all other features.\n To lessen the effect of regularization on synthetic feature weight\n (and therefore on the intercept) intercept_scaling has to be increased.\n\n class_weight : dict or 'balanced', default=None\n Set the parameter C of class i to ``class_weight[i]*C`` for\n SVC. If not given, all classes are supposed to have\n weight one.\n The \"balanced\" mode uses the values of y to automatically adjust\n weights inversely proportional to class frequencies in the input data\n as ``n_samples / (n_classes * np.bincount(y))``.\n\n verbose : int, default=0\n Enable verbose output. Note that this setting takes advantage of a\n per-process runtime setting in liblinear that, if enabled, may not work\n properly in a multithreaded context.\n\n random_state : int, RandomState instance or None, default=None\n Controls the pseudo random number generation for shuffling the data for\n the dual coordinate descent (if ``dual=True``). When ``dual=False`` the\n underlying implementation of :class:`LinearSVC` is not random and\n ``random_state`` has no effect on the results.\n Pass an int for reproducible output across multiple function calls.\n See :term:`Glossary <random_state>`.\n\n max_iter : int, default=1000\n The maximum number of iterations to be run.\n\n Attributes\n ----------\n coef_ : ndarray of shape (1, n_features) if n_classes == 2 \\\n else (n_classes, n_features)\n Weights assigned to the features (coefficients in the primal\n problem).\n\n ``coef_`` is a readonly property derived from ``raw_coef_`` that\n follows the internal memory layout of liblinear.\n\n intercept_ : ndarray of shape (1,) if n_classes == 2 else (n_classes,)\n Constants in decision function.\n\n classes_ : ndarray of shape (n_classes,)\n The unique classes labels.\n\n n_features_in_ : int\n Number of features seen during :term:`fit`.\n\n .. versionadded:: 0.24\n\n feature_names_in_ : ndarray of shape (`n_features_in_`,)\n Names of features seen during :term:`fit`. Defined only when `X`\n has feature names that are all strings.\n\n .. versionadded:: 1.0\n\n n_iter_ : int\n Maximum number of iterations run across all classes.\n\n See Also\n --------\n SVC : Implementation of Support Vector Machine classifier using libsvm:\n the kernel can be non-linear but its SMO algorithm does not\n scale to large number of samples as LinearSVC does.\n\n Furthermore SVC multi-class mode is implemented using one\n vs one scheme while LinearSVC uses one vs the rest. It is\n possible to implement one vs the rest with SVC by using the\n :class:`~sklearn.multiclass.OneVsRestClassifier` wrapper.\n\n Finally SVC can fit dense data without memory copy if the input\n is C-contiguous. Sparse data will still incur memory copy though.\n\n sklearn.linear_model.SGDClassifier : SGDClassifier can optimize the same\n cost function as LinearSVC\n by adjusting the penalty and loss parameters. In addition it requires\n less memory, allows incremental (online) learning, and implements\n various loss functions and regularization regimes.\n\n Notes\n -----\n The underlying C implementation uses a random number generator to\n select features when fitting the model. It is thus not uncommon\n to have slightly different results for the same input data. If\n that happens, try with a smaller ``tol`` parameter.\n\n The underlying implementation, liblinear, uses a sparse internal\n representation for the data that will incur a memory copy.\n\n Predict output may not match that of standalone liblinear in certain\n cases. See :ref:`differences from liblinear <liblinear_differences>`\n in the narrative documentation.\n\n References\n ----------\n `LIBLINEAR: A Library for Large Linear Classification\n <https://www.csie.ntu.edu.tw/~cjlin/liblinear/>`__\n\n Examples\n --------\n >>> from sklearn.svm import LinearSVC\n >>> from sklearn.pipeline import make_pipeline\n >>> from sklearn.preprocessing import StandardScaler\n >>> from sklearn.datasets import make_classification\n >>> X, y = make_classification(n_features=4, random_state=0)\n >>> clf = make_pipeline(StandardScaler(),\n ... LinearSVC(random_state=0, tol=1e-5))\n >>> clf.fit(X, y)\n Pipeline(steps=[('standardscaler', StandardScaler()),\n ('linearsvc', LinearSVC(random_state=0, tol=1e-05))])\n\n >>> print(clf.named_steps['linearsvc'].coef_)\n [[0.141... 0.526... 0.679... 0.493...]]\n\n >>> print(clf.named_steps['linearsvc'].intercept_)\n [0.1693...]\n >>> print(clf.predict([[0, 0, 0, 0]]))\n [1]\n \"\"\"\n\n def __init__(\n self,\n penalty=\"l2\",\n loss=\"squared_hinge\",\n *,\n dual=True,\n tol=1e-4,\n C=1.0,\n multi_class=\"ovr\",\n fit_intercept=True,\n intercept_scaling=1,\n class_weight=None,\n verbose=0,\n random_state=None,\n max_iter=1000,\n ):\n self.dual = dual\n self.tol = tol\n self.C = C\n self.multi_class = multi_class\n self.fit_intercept = fit_intercept\n self.intercept_scaling = intercept_scaling\n self.class_weight = class_weight\n self.verbose = verbose\n self.random_state = random_state\n self.max_iter = max_iter\n self.penalty = penalty\n self.loss = loss\n\n def fit(self, X, y, sample_weight=None):\n \"\"\"Fit the model according to the given training data.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Training vector, where `n_samples` is the number of samples and\n `n_features` is the number of features.\n\n y : array-like of shape (n_samples,)\n Target vector relative to X.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Array of weights that are assigned to individual\n samples. If not provided,\n then each sample is given unit weight.\n\n .. versionadded:: 0.18\n\n Returns\n -------\n self : object\n An instance of the estimator.\n \"\"\"\n if self.C < 0:\n raise ValueError(\"Penalty term must be positive; got (C=%r)\" % self.C)\n\n X, y = self._validate_data(\n X,\n y,\n accept_sparse=\"csr\",\n dtype=np.float64,\n order=\"C\",\n accept_large_sparse=False,\n )\n check_classification_targets(y)\n self.classes_ = np.unique(y)\n\n self.coef_, self.intercept_, self.n_iter_ = _fit_liblinear(\n X,\n y,\n self.C,\n self.fit_intercept,\n self.intercept_scaling,\n self.class_weight,\n self.penalty,\n self.dual,\n self.verbose,\n self.max_iter,\n self.tol,\n self.random_state,\n self.multi_class,\n self.loss,\n sample_weight=sample_weight,\n )\n\n if self.multi_class == \"crammer_singer\" and len(self.classes_) == 2:\n self.coef_ = (self.coef_[1] - self.coef_[0]).reshape(1, -1)\n if self.fit_intercept:\n intercept = self.intercept_[1] - self.intercept_[0]\n self.intercept_ = np.array([intercept])\n\n return self\n\n def _more_tags(self):\n return {\n \"_xfail_checks\": {\n \"check_sample_weights_invariance\": (\n \"zero sample_weight is not equivalent to removing samples\"\n ),\n }\n }\n\n\nclass LinearSVR(RegressorMixin, LinearModel):\n \"\"\"Linear Support Vector Regression.\n\n Similar to SVR with parameter kernel='linear', but implemented in terms of\n liblinear rather than libsvm, so it has more flexibility in the choice of\n penalties and loss functions and should scale better to large numbers of\n samples.\n\n This class supports both dense and sparse input.\n\n Read more in the :ref:`User Guide <svm_regression>`.\n\n .. versionadded:: 0.16\n\n Parameters\n ----------\n epsilon : float, default=0.0\n Epsilon parameter in the epsilon-insensitive loss function. Note\n that the value of this parameter depends on the scale of the target\n variable y. If unsure, set ``epsilon=0``.\n\n tol : float, default=1e-4\n Tolerance for stopping criteria.\n\n C : float, default=1.0\n Regularization parameter. The strength of the regularization is\n inversely proportional to C. Must be strictly positive.\n\n loss : {'epsilon_insensitive', 'squared_epsilon_insensitive'}, \\\n default='epsilon_insensitive'\n Specifies the loss function. The epsilon-insensitive loss\n (standard SVR) is the L1 loss, while the squared epsilon-insensitive\n loss ('squared_epsilon_insensitive') is the L2 loss.\n\n fit_intercept : bool, default=True\n Whether to calculate the intercept for this model. If set\n to false, no intercept will be used in calculations\n (i.e. data is expected to be already centered).\n\n intercept_scaling : float, default=1.0\n When self.fit_intercept is True, instance vector x becomes\n [x, self.intercept_scaling],\n i.e. a \"synthetic\" feature with constant value equals to\n intercept_scaling is appended to the instance vector.\n The intercept becomes intercept_scaling * synthetic feature weight\n Note! the synthetic feature weight is subject to l1/l2 regularization\n as all other features.\n To lessen the effect of regularization on synthetic feature weight\n (and therefore on the intercept) intercept_scaling has to be increased.\n\n dual : bool, default=True\n Select the algorithm to either solve the dual or primal\n optimization problem. Prefer dual=False when n_samples > n_features.\n\n verbose : int, default=0\n Enable verbose output. Note that this setting takes advantage of a\n per-process runtime setting in liblinear that, if enabled, may not work\n properly in a multithreaded context.\n\n random_state : int, RandomState instance or None, default=None\n Controls the pseudo random number generation for shuffling the data.\n Pass an int for reproducible output across multiple function calls.\n See :term:`Glossary <random_state>`.\n\n max_iter : int, default=1000\n The maximum number of iterations to be run.\n\n Attributes\n ----------\n coef_ : ndarray of shape (n_features) if n_classes == 2 \\\n else (n_classes, n_features)\n Weights assigned to the features (coefficients in the primal\n problem).\n\n `coef_` is a readonly property derived from `raw_coef_` that\n follows the internal memory layout of liblinear.\n\n intercept_ : ndarray of shape (1) if n_classes == 2 else (n_classes)\n Constants in decision function.\n\n n_features_in_ : int\n Number of features seen during :term:`fit`.\n\n .. versionadded:: 0.24\n\n feature_names_in_ : ndarray of shape (`n_features_in_`,)\n Names of features seen during :term:`fit`. Defined only when `X`\n has feature names that are all strings.\n\n .. versionadded:: 1.0\n\n n_iter_ : int\n Maximum number of iterations run across all classes.\n\n See Also\n --------\n LinearSVC : Implementation of Support Vector Machine classifier using the\n same library as this class (liblinear).\n\n SVR : Implementation of Support Vector Machine regression using libsvm:\n the kernel can be non-linear but its SMO algorithm does not\n scale to large number of samples as LinearSVC does.\n\n sklearn.linear_model.SGDRegressor : SGDRegressor can optimize the same cost\n function as LinearSVR\n by adjusting the penalty and loss parameters. In addition it requires\n less memory, allows incremental (online) learning, and implements\n various loss functions and regularization regimes.\n\n Examples\n --------\n >>> from sklearn.svm import LinearSVR\n >>> from sklearn.pipeline import make_pipeline\n >>> from sklearn.preprocessing import StandardScaler\n >>> from sklearn.datasets import make_regression\n >>> X, y = make_regression(n_features=4, random_state=0)\n >>> regr = make_pipeline(StandardScaler(),\n ... LinearSVR(random_state=0, tol=1e-5))\n >>> regr.fit(X, y)\n Pipeline(steps=[('standardscaler', StandardScaler()),\n ('linearsvr', LinearSVR(random_state=0, tol=1e-05))])\n\n >>> print(regr.named_steps['linearsvr'].coef_)\n [18.582... 27.023... 44.357... 64.522...]\n >>> print(regr.named_steps['linearsvr'].intercept_)\n [-4...]\n >>> print(regr.predict([[0, 0, 0, 0]]))\n [-2.384...]\n \"\"\"\n\n def __init__(\n self,\n *,\n epsilon=0.0,\n tol=1e-4,\n C=1.0,\n loss=\"epsilon_insensitive\",\n fit_intercept=True,\n intercept_scaling=1.0,\n dual=True,\n verbose=0,\n random_state=None,\n max_iter=1000,\n ):\n self.tol = tol\n self.C = C\n self.epsilon = epsilon\n self.fit_intercept = fit_intercept\n self.intercept_scaling = intercept_scaling\n self.verbose = verbose\n self.random_state = random_state\n self.max_iter = max_iter\n self.dual = dual\n self.loss = loss\n\n def fit(self, X, y, sample_weight=None):\n \"\"\"Fit the model according to the given training data.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Training vector, where `n_samples` is the number of samples and\n `n_features` is the number of features.\n\n y : array-like of shape (n_samples,)\n Target vector relative to X.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Array of weights that are assigned to individual\n samples. If not provided,\n then each sample is given unit weight.\n\n .. versionadded:: 0.18\n\n Returns\n -------\n self : object\n An instance of the estimator.\n \"\"\"\n if self.C < 0:\n raise ValueError(\"Penalty term must be positive; got (C=%r)\" % self.C)\n\n X, y = self._validate_data(\n X,\n y,\n accept_sparse=\"csr\",\n dtype=np.float64,\n order=\"C\",\n accept_large_sparse=False,\n )\n penalty = \"l2\" # SVR only accepts l2 penalty\n self.coef_, self.intercept_, self.n_iter_ = _fit_liblinear(\n X,\n y,\n self.C,\n self.fit_intercept,\n self.intercept_scaling,\n None,\n penalty,\n self.dual,\n self.verbose,\n self.max_iter,\n self.tol,\n self.random_state,\n loss=self.loss,\n epsilon=self.epsilon,\n sample_weight=sample_weight,\n )\n self.coef_ = self.coef_.ravel()\n\n return self\n\n def _more_tags(self):\n return {\n \"_xfail_checks\": {\n \"check_sample_weights_invariance\": (\n \"zero sample_weight is not equivalent to removing samples\"\n ),\n }\n }\n\n\nclass SVC(BaseSVC):\n \"\"\"C-Support Vector Classification.\n\n The implementation is based on libsvm. The fit time scales at least\n quadratically with the number of samples and may be impractical\n beyond tens of thousands of samples. For large datasets\n consider using :class:`~sklearn.svm.LinearSVC` or\n :class:`~sklearn.linear_model.SGDClassifier` instead, possibly after a\n :class:`~sklearn.kernel_approximation.Nystroem` transformer.\n\n The multiclass support is handled according to a one-vs-one scheme.\n\n For details on the precise mathematical formulation of the provided\n kernel functions and how `gamma`, `coef0` and `degree` affect each\n other, see the corresponding section in the narrative documentation:\n :ref:`svm_kernels`.\n\n Read more in the :ref:`User Guide <svm_classification>`.\n\n Parameters\n ----------\n C : float, default=1.0\n Regularization parameter. The strength of the regularization is\n inversely proportional to C. Must be strictly positive. The penalty\n is a squared l2 penalty.\n\n kernel : {'linear', 'poly', 'rbf', 'sigmoid', 'precomputed'} or callable, \\\n default='rbf'\n Specifies the kernel type to be used in the algorithm.\n If none is given, 'rbf' will be used. If a callable is given it is\n used to pre-compute the kernel matrix from data matrices; that matrix\n should be an array of shape ``(n_samples, n_samples)``.\n\n degree : int, default=3\n Degree of the polynomial kernel function ('poly').\n Ignored by all other kernels.\n\n gamma : {'scale', 'auto'} or float, default='scale'\n Kernel coefficient for 'rbf', 'poly' and 'sigmoid'.\n\n - if ``gamma='scale'`` (default) is passed then it uses\n 1 / (n_features * X.var()) as value of gamma,\n - if 'auto', uses 1 / n_features.\n\n .. versionchanged:: 0.22\n The default value of ``gamma`` changed from 'auto' to 'scale'.\n\n coef0 : float, default=0.0\n Independent term in kernel function.\n It is only significant in 'poly' and 'sigmoid'.\n\n shrinking : bool, default=True\n Whether to use the shrinking heuristic.\n See the :ref:`User Guide <shrinking_svm>`.\n\n probability : bool, default=False\n Whether to enable probability estimates. This must be enabled prior\n to calling `fit`, will slow down that method as it internally uses\n 5-fold cross-validation, and `predict_proba` may be inconsistent with\n `predict`. Read more in the :ref:`User Guide <scores_probabilities>`.\n\n tol : float, default=1e-3\n Tolerance for stopping criterion.\n\n cache_size : float, default=200\n Specify the size of the kernel cache (in MB).\n\n class_weight : dict or 'balanced', default=None\n Set the parameter C of class i to class_weight[i]*C for\n SVC. If not given, all classes are supposed to have\n weight one.\n The \"balanced\" mode uses the values of y to automatically adjust\n weights inversely proportional to class frequencies in the input data\n as ``n_samples / (n_classes * np.bincount(y))``.\n\n verbose : bool, default=False\n Enable verbose output. Note that this setting takes advantage of a\n per-process runtime setting in libsvm that, if enabled, may not work\n properly in a multithreaded context.\n\n max_iter : int, default=-1\n Hard limit on iterations within solver, or -1 for no limit.\n\n decision_function_shape : {'ovo', 'ovr'}, default='ovr'\n Whether to return a one-vs-rest ('ovr') decision function of shape\n (n_samples, n_classes) as all other classifiers, or the original\n one-vs-one ('ovo') decision function of libsvm which has shape\n (n_samples, n_classes * (n_classes - 1) / 2). However, one-vs-one\n ('ovo') is always used as multi-class strategy. The parameter is\n ignored for binary classification.\n\n .. versionchanged:: 0.19\n decision_function_shape is 'ovr' by default.\n\n .. versionadded:: 0.17\n *decision_function_shape='ovr'* is recommended.\n\n .. versionchanged:: 0.17\n Deprecated *decision_function_shape='ovo' and None*.\n\n break_ties : bool, default=False\n If true, ``decision_function_shape='ovr'``, and number of classes > 2,\n :term:`predict` will break ties according to the confidence values of\n :term:`decision_function`; otherwise the first class among the tied\n classes is returned. Please note that breaking ties comes at a\n relatively high computational cost compared to a simple predict.\n\n .. versionadded:: 0.22\n\n random_state : int, RandomState instance or None, default=None\n Controls the pseudo random number generation for shuffling the data for\n probability estimates. Ignored when `probability` is False.\n Pass an int for reproducible output across multiple function calls.\n See :term:`Glossary <random_state>`.\n\n Attributes\n ----------\n class_weight_ : ndarray of shape (n_classes,)\n Multipliers of parameter C for each class.\n Computed based on the ``class_weight`` parameter.\n\n classes_ : ndarray of shape (n_classes,)\n The classes labels.\n\n coef_ : ndarray of shape (n_classes * (n_classes - 1) / 2, n_features)\n Weights assigned to the features (coefficients in the primal\n problem). This is only available in the case of a linear kernel.\n\n `coef_` is a readonly property derived from `dual_coef_` and\n `support_vectors_`.\n\n dual_coef_ : ndarray of shape (n_classes -1, n_SV)\n Dual coefficients of the support vector in the decision\n function (see :ref:`sgd_mathematical_formulation`), multiplied by\n their targets.\n For multiclass, coefficient for all 1-vs-1 classifiers.\n The layout of the coefficients in the multiclass case is somewhat\n non-trivial. See the :ref:`multi-class section of the User Guide\n <svm_multi_class>` for details.\n\n fit_status_ : int\n 0 if correctly fitted, 1 otherwise (will raise warning)\n\n intercept_ : ndarray of shape (n_classes * (n_classes - 1) / 2,)\n Constants in decision function.\n\n n_features_in_ : int\n Number of features seen during :term:`fit`.\n\n .. versionadded:: 0.24\n\n feature_names_in_ : ndarray of shape (`n_features_in_`,)\n Names of features seen during :term:`fit`. Defined only when `X`\n has feature names that are all strings.\n\n .. versionadded:: 1.0\n\n support_ : ndarray of shape (n_SV)\n Indices of support vectors.\n\n support_vectors_ : ndarray of shape (n_SV, n_features)\n Support vectors.\n\n n_support_ : ndarray of shape (n_classes,), dtype=int32\n Number of support vectors for each class.\n\n probA_ : ndarray of shape (n_classes * (n_classes - 1) / 2)\n probB_ : ndarray of shape (n_classes * (n_classes - 1) / 2)\n If `probability=True`, it corresponds to the parameters learned in\n Platt scaling to produce probability estimates from decision values.\n If `probability=False`, it's an empty array. Platt scaling uses the\n logistic function\n ``1 / (1 + exp(decision_value * probA_ + probB_))``\n where ``probA_`` and ``probB_`` are learned from the dataset [2]_. For\n more information on the multiclass case and training procedure see\n section 8 of [1]_.\n\n shape_fit_ : tuple of int of shape (n_dimensions_of_X,)\n Array dimensions of training vector ``X``.\n\n See Also\n --------\n SVR : Support Vector Machine for Regression implemented using libsvm.\n\n LinearSVC : Scalable Linear Support Vector Machine for classification\n implemented using liblinear. Check the See Also section of\n LinearSVC for more comparison element.\n\n References\n ----------\n .. [1] `LIBSVM: A Library for Support Vector Machines\n <http://www.csie.ntu.edu.tw/~cjlin/papers/libsvm.pdf>`_\n\n .. [2] `Platt, John (1999). \"Probabilistic outputs for support vector\n machines and comparison to regularizedlikelihood methods.\"\n <http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.41.1639>`_\n\n Examples\n --------\n >>> import numpy as np\n >>> from sklearn.pipeline import make_pipeline\n >>> from sklearn.preprocessing import StandardScaler\n >>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])\n >>> y = np.array([1, 1, 2, 2])\n >>> from sklearn.svm import SVC\n >>> clf = make_pipeline(StandardScaler(), SVC(gamma='auto'))\n >>> clf.fit(X, y)\n Pipeline(steps=[('standardscaler', StandardScaler()),\n ('svc', SVC(gamma='auto'))])\n\n >>> print(clf.predict([[-0.8, -1]]))\n [1]\n \"\"\"\n\n _impl = \"c_svc\"\n\n def __init__(\n self,\n *,\n C=1.0,\n kernel=\"rbf\",\n degree=3,\n gamma=\"scale\",\n coef0=0.0,\n shrinking=True,\n probability=False,\n tol=1e-3,\n cache_size=200,\n class_weight=None,\n verbose=False,\n max_iter=-1,\n decision_function_shape=\"ovr\",\n break_ties=False,\n random_state=None,\n ):\n\n super().__init__(\n kernel=kernel,\n degree=degree,\n gamma=gamma,\n coef0=coef0,\n tol=tol,\n C=C,\n nu=0.0,\n shrinking=shrinking,\n probability=probability,\n cache_size=cache_size,\n class_weight=class_weight,\n verbose=verbose,\n max_iter=max_iter,\n decision_function_shape=decision_function_shape,\n break_ties=break_ties,\n random_state=random_state,\n )\n\n def _more_tags(self):\n return {\n \"_xfail_checks\": {\n \"check_sample_weights_invariance\": (\n \"zero sample_weight is not equivalent to removing samples\"\n ),\n }\n }\n\n\nclass NuSVC(BaseSVC):\n \"\"\"Nu-Support Vector Classification.\n\n Similar to SVC but uses a parameter to control the number of support\n vectors.\n\n The implementation is based on libsvm.\n\n Read more in the :ref:`User Guide <svm_classification>`.\n\n Parameters\n ----------\n nu : float, default=0.5\n An upper bound on the fraction of margin errors (see :ref:`User Guide\n <nu_svc>`) and a lower bound of the fraction of support vectors.\n Should be in the interval (0, 1].\n\n kernel : {'linear', 'poly', 'rbf', 'sigmoid', 'precomputed'} or callable, \\\n default='rbf'\n Specifies the kernel type to be used in the algorithm.\n If none is given, 'rbf' will be used. If a callable is given it is\n used to precompute the kernel matrix.\n\n degree : int, default=3\n Degree of the polynomial kernel function ('poly').\n Ignored by all other kernels.\n\n gamma : {'scale', 'auto'} or float, default='scale'\n Kernel coefficient for 'rbf', 'poly' and 'sigmoid'.\n\n - if ``gamma='scale'`` (default) is passed then it uses\n 1 / (n_features * X.var()) as value of gamma,\n - if 'auto', uses 1 / n_features.\n\n .. versionchanged:: 0.22\n The default value of ``gamma`` changed from 'auto' to 'scale'.\n\n coef0 : float, default=0.0\n Independent term in kernel function.\n It is only significant in 'poly' and 'sigmoid'.\n\n shrinking : bool, default=True\n Whether to use the shrinking heuristic.\n See the :ref:`User Guide <shrinking_svm>`.\n\n probability : bool, default=False\n Whether to enable probability estimates. This must be enabled prior\n to calling `fit`, will slow down that method as it internally uses\n 5-fold cross-validation, and `predict_proba` may be inconsistent with\n `predict`. Read more in the :ref:`User Guide <scores_probabilities>`.\n\n tol : float, default=1e-3\n Tolerance for stopping criterion.\n\n cache_size : float, default=200\n Specify the size of the kernel cache (in MB).\n\n class_weight : {dict, 'balanced'}, default=None\n Set the parameter C of class i to class_weight[i]*C for\n SVC. If not given, all classes are supposed to have\n weight one. The \"balanced\" mode uses the values of y to automatically\n adjust weights inversely proportional to class frequencies as\n ``n_samples / (n_classes * np.bincount(y))``.\n\n verbose : bool, default=False\n Enable verbose output. Note that this setting takes advantage of a\n per-process runtime setting in libsvm that, if enabled, may not work\n properly in a multithreaded context.\n\n max_iter : int, default=-1\n Hard limit on iterations within solver, or -1 for no limit.\n\n decision_function_shape : {'ovo', 'ovr'}, default='ovr'\n Whether to return a one-vs-rest ('ovr') decision function of shape\n (n_samples, n_classes) as all other classifiers, or the original\n one-vs-one ('ovo') decision function of libsvm which has shape\n (n_samples, n_classes * (n_classes - 1) / 2). However, one-vs-one\n ('ovo') is always used as multi-class strategy. The parameter is\n ignored for binary classification.\n\n .. versionchanged:: 0.19\n decision_function_shape is 'ovr' by default.\n\n .. versionadded:: 0.17\n *decision_function_shape='ovr'* is recommended.\n\n .. versionchanged:: 0.17\n Deprecated *decision_function_shape='ovo' and None*.\n\n break_ties : bool, default=False\n If true, ``decision_function_shape='ovr'``, and number of classes > 2,\n :term:`predict` will break ties according to the confidence values of\n :term:`decision_function`; otherwise the first class among the tied\n classes is returned. Please note that breaking ties comes at a\n relatively high computational cost compared to a simple predict.\n\n .. versionadded:: 0.22\n\n random_state : int, RandomState instance or None, default=None\n Controls the pseudo random number generation for shuffling the data for\n probability estimates. Ignored when `probability` is False.\n Pass an int for reproducible output across multiple function calls.\n See :term:`Glossary <random_state>`.\n\n Attributes\n ----------\n class_weight_ : ndarray of shape (n_classes,)\n Multipliers of parameter C of each class.\n Computed based on the ``class_weight`` parameter.\n\n classes_ : ndarray of shape (n_classes,)\n The unique classes labels.\n\n coef_ : ndarray of shape (n_classes * (n_classes -1) / 2, n_features)\n Weights assigned to the features (coefficients in the primal\n problem). This is only available in the case of a linear kernel.\n\n `coef_` is readonly property derived from `dual_coef_` and\n `support_vectors_`.\n\n dual_coef_ : ndarray of shape (n_classes - 1, n_SV)\n Dual coefficients of the support vector in the decision\n function (see :ref:`sgd_mathematical_formulation`), multiplied by\n their targets.\n For multiclass, coefficient for all 1-vs-1 classifiers.\n The layout of the coefficients in the multiclass case is somewhat\n non-trivial. See the :ref:`multi-class section of the User Guide\n <svm_multi_class>` for details.\n\n fit_status_ : int\n 0 if correctly fitted, 1 if the algorithm did not converge.\n\n intercept_ : ndarray of shape (n_classes * (n_classes - 1) / 2,)\n Constants in decision function.\n\n n_features_in_ : int\n Number of features seen during :term:`fit`.\n\n .. versionadded:: 0.24\n\n feature_names_in_ : ndarray of shape (`n_features_in_`,)\n Names of features seen during :term:`fit`. Defined only when `X`\n has feature names that are all strings.\n\n .. versionadded:: 1.0\n\n support_ : ndarray of shape (n_SV,)\n Indices of support vectors.\n\n support_vectors_ : ndarray of shape (n_SV, n_features)\n Support vectors.\n\n n_support_ : ndarray of shape (n_classes,), dtype=int32\n Number of support vectors for each class.\n\n fit_status_ : int\n 0 if correctly fitted, 1 if the algorithm did not converge.\n\n probA_ : ndarray of shape (n_classes * (n_classes - 1) / 2,)\n probB_ : ndarray of shape (n_classes * (n_classes - 1) / 2,)\n If `probability=True`, it corresponds to the parameters learned in\n Platt scaling to produce probability estimates from decision values.\n If `probability=False`, it's an empty array. Platt scaling uses the\n logistic function\n ``1 / (1 + exp(decision_value * probA_ + probB_))``\n where ``probA_`` and ``probB_`` are learned from the dataset [2]_. For\n more information on the multiclass case and training procedure see\n section 8 of [1]_.\n\n shape_fit_ : tuple of int of shape (n_dimensions_of_X,)\n Array dimensions of training vector ``X``.\n\n See Also\n --------\n SVC : Support Vector Machine for classification using libsvm.\n\n LinearSVC : Scalable linear Support Vector Machine for classification using\n liblinear.\n\n References\n ----------\n .. [1] `LIBSVM: A Library for Support Vector Machines\n <http://www.csie.ntu.edu.tw/~cjlin/papers/libsvm.pdf>`_\n\n .. [2] `Platt, John (1999). \"Probabilistic outputs for support vector\n machines and comparison to regularizedlikelihood methods.\"\n <http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.41.1639>`_\n\n Examples\n --------\n >>> import numpy as np\n >>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])\n >>> y = np.array([1, 1, 2, 2])\n >>> from sklearn.pipeline import make_pipeline\n >>> from sklearn.preprocessing import StandardScaler\n >>> from sklearn.svm import NuSVC\n >>> clf = make_pipeline(StandardScaler(), NuSVC())\n >>> clf.fit(X, y)\n Pipeline(steps=[('standardscaler', StandardScaler()), ('nusvc', NuSVC())])\n >>> print(clf.predict([[-0.8, -1]]))\n [1]\n \"\"\"\n\n _impl = \"nu_svc\"\n\n def __init__(\n self,\n *,\n nu=0.5,\n kernel=\"rbf\",\n degree=3,\n gamma=\"scale\",\n coef0=0.0,\n shrinking=True,\n probability=False,\n tol=1e-3,\n cache_size=200,\n class_weight=None,\n verbose=False,\n max_iter=-1,\n decision_function_shape=\"ovr\",\n break_ties=False,\n random_state=None,\n ):\n\n super().__init__(\n kernel=kernel,\n degree=degree,\n gamma=gamma,\n coef0=coef0,\n tol=tol,\n C=0.0,\n nu=nu,\n shrinking=shrinking,\n probability=probability,\n cache_size=cache_size,\n class_weight=class_weight,\n verbose=verbose,\n max_iter=max_iter,\n decision_function_shape=decision_function_shape,\n break_ties=break_ties,\n random_state=random_state,\n )\n\n def _more_tags(self):\n return {\n \"_xfail_checks\": {\n \"check_methods_subset_invariance\": (\n \"fails for the decision_function method\"\n ),\n \"check_class_weight_classifiers\": \"class_weight is ignored.\",\n \"check_sample_weights_invariance\": (\n \"zero sample_weight is not equivalent to removing samples\"\n ),\n }\n }\n\n\nclass SVR(RegressorMixin, BaseLibSVM):\n \"\"\"Epsilon-Support Vector Regression.\n\n The free parameters in the model are C and epsilon.\n\n The implementation is based on libsvm. The fit time complexity\n is more than quadratic with the number of samples which makes it hard\n to scale to datasets with more than a couple of 10000 samples. For large\n datasets consider using :class:`~sklearn.svm.LinearSVR` or\n :class:`~sklearn.linear_model.SGDRegressor` instead, possibly after a\n :class:`~sklearn.kernel_approximation.Nystroem` transformer.\n\n Read more in the :ref:`User Guide <svm_regression>`.\n\n Parameters\n ----------\n kernel : {'linear', 'poly', 'rbf', 'sigmoid', 'precomputed'} or callable, \\\n default='rbf'\n Specifies the kernel type to be used in the algorithm.\n If none is given, 'rbf' will be used. If a callable is given it is\n used to precompute the kernel matrix.\n\n degree : int, default=3\n Degree of the polynomial kernel function ('poly').\n Ignored by all other kernels.\n\n gamma : {'scale', 'auto'} or float, default='scale'\n Kernel coefficient for 'rbf', 'poly' and 'sigmoid'.\n\n - if ``gamma='scale'`` (default) is passed then it uses\n 1 / (n_features * X.var()) as value of gamma,\n - if 'auto', uses 1 / n_features.\n\n .. versionchanged:: 0.22\n The default value of ``gamma`` changed from 'auto' to 'scale'.\n\n coef0 : float, default=0.0\n Independent term in kernel function.\n It is only significant in 'poly' and 'sigmoid'.\n\n tol : float, default=1e-3\n Tolerance for stopping criterion.\n\n C : float, default=1.0\n Regularization parameter. The strength of the regularization is\n inversely proportional to C. Must be strictly positive.\n The penalty is a squared l2 penalty.\n\n epsilon : float, default=0.1\n Epsilon in the epsilon-SVR model. It specifies the epsilon-tube\n within which no penalty is associated in the training loss function\n with points predicted within a distance epsilon from the actual\n value.\n\n shrinking : bool, default=True\n Whether to use the shrinking heuristic.\n See the :ref:`User Guide <shrinking_svm>`.\n\n cache_size : float, default=200\n Specify the size of the kernel cache (in MB).\n\n verbose : bool, default=False\n Enable verbose output. Note that this setting takes advantage of a\n per-process runtime setting in libsvm that, if enabled, may not work\n properly in a multithreaded context.\n\n max_iter : int, default=-1\n Hard limit on iterations within solver, or -1 for no limit.\n\n Attributes\n ----------\n class_weight_ : ndarray of shape (n_classes,)\n Multipliers of parameter C for each class.\n Computed based on the ``class_weight`` parameter.\n\n coef_ : ndarray of shape (1, n_features)\n Weights assigned to the features (coefficients in the primal\n problem). This is only available in the case of a linear kernel.\n\n `coef_` is readonly property derived from `dual_coef_` and\n `support_vectors_`.\n\n dual_coef_ : ndarray of shape (1, n_SV)\n Coefficients of the support vector in the decision function.\n\n fit_status_ : int\n 0 if correctly fitted, 1 otherwise (will raise warning)\n\n intercept_ : ndarray of shape (1,)\n Constants in decision function.\n\n n_features_in_ : int\n Number of features seen during :term:`fit`.\n\n .. versionadded:: 0.24\n\n feature_names_in_ : ndarray of shape (`n_features_in_`,)\n Names of features seen during :term:`fit`. Defined only when `X`\n has feature names that are all strings.\n\n .. versionadded:: 1.0\n\n n_support_ : ndarray of shape (n_classes,), dtype=int32\n Number of support vectors for each class.\n\n shape_fit_ : tuple of int of shape (n_dimensions_of_X,)\n Array dimensions of training vector ``X``.\n\n support_ : ndarray of shape (n_SV,)\n Indices of support vectors.\n\n support_vectors_ : ndarray of shape (n_SV, n_features)\n Support vectors.\n\n See Also\n --------\n NuSVR : Support Vector Machine for regression implemented using libsvm\n using a parameter to control the number of support vectors.\n\n LinearSVR : Scalable Linear Support Vector Machine for regression\n implemented using liblinear.\n\n References\n ----------\n .. [1] `LIBSVM: A Library for Support Vector Machines\n <http://www.csie.ntu.edu.tw/~cjlin/papers/libsvm.pdf>`_\n\n .. [2] `Platt, John (1999). \"Probabilistic outputs for support vector\n machines and comparison to regularizedlikelihood methods.\"\n <http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.41.1639>`_\n\n Examples\n --------\n >>> from sklearn.svm import SVR\n >>> from sklearn.pipeline import make_pipeline\n >>> from sklearn.preprocessing import StandardScaler\n >>> import numpy as np\n >>> n_samples, n_features = 10, 5\n >>> rng = np.random.RandomState(0)\n >>> y = rng.randn(n_samples)\n >>> X = rng.randn(n_samples, n_features)\n >>> regr = make_pipeline(StandardScaler(), SVR(C=1.0, epsilon=0.2))\n >>> regr.fit(X, y)\n Pipeline(steps=[('standardscaler', StandardScaler()),\n ('svr', SVR(epsilon=0.2))])\n \"\"\"\n\n _impl = \"epsilon_svr\"\n\n def __init__(\n self,\n *,\n kernel=\"rbf\",\n degree=3,\n gamma=\"scale\",\n coef0=0.0,\n tol=1e-3,\n C=1.0,\n epsilon=0.1,\n shrinking=True,\n cache_size=200,\n verbose=False,\n max_iter=-1,\n ):\n\n super().__init__(\n kernel=kernel,\n degree=degree,\n gamma=gamma,\n coef0=coef0,\n tol=tol,\n C=C,\n nu=0.0,\n epsilon=epsilon,\n verbose=verbose,\n shrinking=shrinking,\n probability=False,\n cache_size=cache_size,\n class_weight=None,\n max_iter=max_iter,\n random_state=None,\n )\n\n def _more_tags(self):\n return {\n \"_xfail_checks\": {\n \"check_sample_weights_invariance\": (\n \"zero sample_weight is not equivalent to removing samples\"\n ),\n }\n }\n\n\nclass NuSVR(RegressorMixin, BaseLibSVM):\n \"\"\"Nu Support Vector Regression.\n\n Similar to NuSVC, for regression, uses a parameter nu to control\n the number of support vectors. However, unlike NuSVC, where nu\n replaces C, here nu replaces the parameter epsilon of epsilon-SVR.\n\n The implementation is based on libsvm.\n\n Read more in the :ref:`User Guide <svm_regression>`.\n\n Parameters\n ----------\n nu : float, default=0.5\n An upper bound on the fraction of training errors and a lower bound of\n the fraction of support vectors. Should be in the interval (0, 1]. By\n default 0.5 will be taken.\n\n C : float, default=1.0\n Penalty parameter C of the error term.\n\n kernel : {'linear', 'poly', 'rbf', 'sigmoid', 'precomputed'} or callable, \\\n default='rbf'\n Specifies the kernel type to be used in the algorithm.\n If none is given, 'rbf' will be used. If a callable is given it is\n used to precompute the kernel matrix.\n\n degree : int, default=3\n Degree of the polynomial kernel function ('poly').\n Ignored by all other kernels.\n\n gamma : {'scale', 'auto'} or float, default='scale'\n Kernel coefficient for 'rbf', 'poly' and 'sigmoid'.\n\n - if ``gamma='scale'`` (default) is passed then it uses\n 1 / (n_features * X.var()) as value of gamma,\n - if 'auto', uses 1 / n_features.\n\n .. versionchanged:: 0.22\n The default value of ``gamma`` changed from 'auto' to 'scale'.\n\n coef0 : float, default=0.0\n Independent term in kernel function.\n It is only significant in 'poly' and 'sigmoid'.\n\n shrinking : bool, default=True\n Whether to use the shrinking heuristic.\n See the :ref:`User Guide <shrinking_svm>`.\n\n tol : float, default=1e-3\n Tolerance for stopping criterion.\n\n cache_size : float, default=200\n Specify the size of the kernel cache (in MB).\n\n verbose : bool, default=False\n Enable verbose output. Note that this setting takes advantage of a\n per-process runtime setting in libsvm that, if enabled, may not work\n properly in a multithreaded context.\n\n max_iter : int, default=-1\n Hard limit on iterations within solver, or -1 for no limit.\n\n Attributes\n ----------\n class_weight_ : ndarray of shape (n_classes,)\n Multipliers of parameter C for each class.\n Computed based on the ``class_weight`` parameter.\n\n coef_ : ndarray of shape (1, n_features)\n Weights assigned to the features (coefficients in the primal\n problem). This is only available in the case of a linear kernel.\n\n `coef_` is readonly property derived from `dual_coef_` and\n `support_vectors_`.\n\n dual_coef_ : ndarray of shape (1, n_SV)\n Coefficients of the support vector in the decision function.\n\n fit_status_ : int\n 0 if correctly fitted, 1 otherwise (will raise warning)\n\n intercept_ : ndarray of shape (1,)\n Constants in decision function.\n\n n_features_in_ : int\n Number of features seen during :term:`fit`.\n\n .. versionadded:: 0.24\n\n feature_names_in_ : ndarray of shape (`n_features_in_`,)\n Names of features seen during :term:`fit`. Defined only when `X`\n has feature names that are all strings.\n\n .. versionadded:: 1.0\n\n n_support_ : ndarray of shape (n_classes,), dtype=int32\n Number of support vectors for each class.\n\n shape_fit_ : tuple of int of shape (n_dimensions_of_X,)\n Array dimensions of training vector ``X``.\n\n support_ : ndarray of shape (n_SV,)\n Indices of support vectors.\n\n support_vectors_ : ndarray of shape (n_SV, n_features)\n Support vectors.\n\n See Also\n --------\n NuSVC : Support Vector Machine for classification implemented with libsvm\n with a parameter to control the number of support vectors.\n\n SVR : Epsilon Support Vector Machine for regression implemented with\n libsvm.\n\n References\n ----------\n .. [1] `LIBSVM: A Library for Support Vector Machines\n <http://www.csie.ntu.edu.tw/~cjlin/papers/libsvm.pdf>`_\n\n .. [2] `Platt, John (1999). \"Probabilistic outputs for support vector\n machines and comparison to regularizedlikelihood methods.\"\n <http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.41.1639>`_\n\n Examples\n --------\n >>> from sklearn.svm import NuSVR\n >>> from sklearn.pipeline import make_pipeline\n >>> from sklearn.preprocessing import StandardScaler\n >>> import numpy as np\n >>> n_samples, n_features = 10, 5\n >>> np.random.seed(0)\n >>> y = np.random.randn(n_samples)\n >>> X = np.random.randn(n_samples, n_features)\n >>> regr = make_pipeline(StandardScaler(), NuSVR(C=1.0, nu=0.1))\n >>> regr.fit(X, y)\n Pipeline(steps=[('standardscaler', StandardScaler()),\n ('nusvr', NuSVR(nu=0.1))])\n \"\"\"\n\n _impl = \"nu_svr\"\n\n def __init__(\n self,\n *,\n nu=0.5,\n C=1.0,\n kernel=\"rbf\",\n degree=3,\n gamma=\"scale\",\n coef0=0.0,\n shrinking=True,\n tol=1e-3,\n cache_size=200,\n verbose=False,\n max_iter=-1,\n ):\n\n super().__init__(\n kernel=kernel,\n degree=degree,\n gamma=gamma,\n coef0=coef0,\n tol=tol,\n C=C,\n nu=nu,\n epsilon=0.0,\n shrinking=shrinking,\n probability=False,\n cache_size=cache_size,\n class_weight=None,\n verbose=verbose,\n max_iter=max_iter,\n random_state=None,\n )\n\n def _more_tags(self):\n return {\n \"_xfail_checks\": {\n \"check_sample_weights_invariance\": (\n \"zero sample_weight is not equivalent to removing samples\"\n ),\n }\n }\n\n\nclass OneClassSVM(OutlierMixin, BaseLibSVM):\n \"\"\"Unsupervised Outlier Detection.\n\n Estimate the support of a high-dimensional distribution.\n\n The implementation is based on libsvm.\n\n Read more in the :ref:`User Guide <outlier_detection>`.\n\n Parameters\n ----------\n kernel : {'linear', 'poly', 'rbf', 'sigmoid', 'precomputed'} or callable, \\\n default='rbf'\n Specifies the kernel type to be used in the algorithm.\n If none is given, 'rbf' will be used. If a callable is given it is\n used to precompute the kernel matrix.\n\n degree : int, default=3\n Degree of the polynomial kernel function ('poly').\n Ignored by all other kernels.\n\n gamma : {'scale', 'auto'} or float, default='scale'\n Kernel coefficient for 'rbf', 'poly' and 'sigmoid'.\n\n - if ``gamma='scale'`` (default) is passed then it uses\n 1 / (n_features * X.var()) as value of gamma,\n - if 'auto', uses 1 / n_features.\n\n .. versionchanged:: 0.22\n The default value of ``gamma`` changed from 'auto' to 'scale'.\n\n coef0 : float, default=0.0\n Independent term in kernel function.\n It is only significant in 'poly' and 'sigmoid'.\n\n tol : float, default=1e-3\n Tolerance for stopping criterion.\n\n nu : float, default=0.5\n An upper bound on the fraction of training\n errors and a lower bound of the fraction of support\n vectors. Should be in the interval (0, 1]. By default 0.5\n will be taken.\n\n shrinking : bool, default=True\n Whether to use the shrinking heuristic.\n See the :ref:`User Guide <shrinking_svm>`.\n\n cache_size : float, default=200\n Specify the size of the kernel cache (in MB).\n\n verbose : bool, default=False\n Enable verbose output. Note that this setting takes advantage of a\n per-process runtime setting in libsvm that, if enabled, may not work\n properly in a multithreaded context.\n\n max_iter : int, default=-1\n Hard limit on iterations within solver, or -1 for no limit.\n\n Attributes\n ----------\n class_weight_ : ndarray of shape (n_classes,)\n Multipliers of parameter C for each class.\n Computed based on the ``class_weight`` parameter.\n\n coef_ : ndarray of shape (1, n_features)\n Weights assigned to the features (coefficients in the primal\n problem). This is only available in the case of a linear kernel.\n\n `coef_` is readonly property derived from `dual_coef_` and\n `support_vectors_`.\n\n dual_coef_ : ndarray of shape (1, n_SV)\n Coefficients of the support vectors in the decision function.\n\n fit_status_ : int\n 0 if correctly fitted, 1 otherwise (will raise warning)\n\n intercept_ : ndarray of shape (1,)\n Constant in the decision function.\n\n n_features_in_ : int\n Number of features seen during :term:`fit`.\n\n .. versionadded:: 0.24\n\n feature_names_in_ : ndarray of shape (`n_features_in_`,)\n Names of features seen during :term:`fit`. Defined only when `X`\n has feature names that are all strings.\n\n .. versionadded:: 1.0\n\n n_support_ : ndarray of shape (n_classes,), dtype=int32\n Number of support vectors for each class.\n\n offset_ : float\n Offset used to define the decision function from the raw scores.\n We have the relation: decision_function = score_samples - `offset_`.\n The offset is the opposite of `intercept_` and is provided for\n consistency with other outlier detection algorithms.\n\n .. versionadded:: 0.20\n\n shape_fit_ : tuple of int of shape (n_dimensions_of_X,)\n Array dimensions of training vector ``X``.\n\n support_ : ndarray of shape (n_SV,)\n Indices of support vectors.\n\n support_vectors_ : ndarray of shape (n_SV, n_features)\n Support vectors.\n\n See Also\n --------\n sklearn.linear_model.SGDOneClassSVM : Solves linear One-Class SVM using\n Stochastic Gradient Descent.\n sklearn.neighbors.LocalOutlierFactor : Unsupervised Outlier Detection using\n Local Outlier Factor (LOF).\n sklearn.ensemble.IsolationForest : Isolation Forest Algorithm.\n\n Examples\n --------\n >>> from sklearn.svm import OneClassSVM\n >>> X = [[0], [0.44], [0.45], [0.46], [1]]\n >>> clf = OneClassSVM(gamma='auto').fit(X)\n >>> clf.predict(X)\n array([-1, 1, 1, 1, -1])\n >>> clf.score_samples(X)\n array([1.7798..., 2.0547..., 2.0556..., 2.0561..., 1.7332...])\n \"\"\"\n\n _impl = \"one_class\"\n\n def __init__(\n self,\n *,\n kernel=\"rbf\",\n degree=3,\n gamma=\"scale\",\n coef0=0.0,\n tol=1e-3,\n nu=0.5,\n shrinking=True,\n cache_size=200,\n verbose=False,\n max_iter=-1,\n ):\n\n super().__init__(\n kernel,\n degree,\n gamma,\n coef0,\n tol,\n 0.0,\n nu,\n 0.0,\n shrinking,\n False,\n cache_size,\n None,\n verbose,\n max_iter,\n random_state=None,\n )\n\n def fit(self, X, y=None, sample_weight=None, **params):\n \"\"\"Detect the soft boundary of the set of samples X.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Set of samples, where `n_samples` is the number of samples and\n `n_features` is the number of features.\n\n y : Ignored\n Not used, present for API consistency by convention.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Per-sample weights. Rescale C per sample. Higher weights\n force the classifier to put more emphasis on these points.\n\n **params : dict\n Additional fit parameters.\n\n .. deprecated:: 1.0\n The `fit` method will not longer accept extra keyword\n parameters in 1.2. These keyword parameters were\n already discarded.\n\n Returns\n -------\n self : object\n Fitted estimator.\n\n Notes\n -----\n If X is not a C-ordered contiguous array it is copied.\n \"\"\"\n # TODO: Remove in v1.2\n if len(params) > 0:\n warnings.warn(\n \"Passing additional keyword parameters has no effect and is \"\n \"deprecated in 1.0. An error will be raised from 1.2 and \"\n \"beyond. The ignored keyword parameter(s) are: \"\n f\"{params.keys()}.\",\n FutureWarning,\n )\n super().fit(X, np.ones(_num_samples(X)), sample_weight=sample_weight)\n self.offset_ = -self._intercept_\n return self\n\n def decision_function(self, X):\n \"\"\"Signed distance to the separating hyperplane.\n\n Signed distance is positive for an inlier and negative for an outlier.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n The data matrix.\n\n Returns\n -------\n dec : ndarray of shape (n_samples,)\n Returns the decision function of the samples.\n \"\"\"\n dec = self._decision_function(X).ravel()\n return dec\n\n def score_samples(self, X):\n \"\"\"Raw scoring function of the samples.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n The data matrix.\n\n Returns\n -------\n score_samples : ndarray of shape (n_samples,)\n Returns the (unshifted) scoring function of the samples.\n \"\"\"\n return self.decision_function(X) + self.offset_\n\n def predict(self, X):\n \"\"\"Perform classification on samples in X.\n\n For a one-class model, +1 or -1 is returned.\n\n Parameters\n ----------\n X : {array-like, sparse matrix} of shape (n_samples, n_features) or \\\n (n_samples_test, n_samples_train)\n For kernel=\"precomputed\", the expected shape of X is\n (n_samples_test, n_samples_train).\n\n Returns\n -------\n y_pred : ndarray of shape (n_samples,)\n Class labels for samples in X.\n \"\"\"\n y = super().predict(X)\n return np.asarray(y, dtype=np.intp)\n\n def _more_tags(self):\n return {\n \"_xfail_checks\": {\n \"check_sample_weights_invariance\": (\n \"zero sample_weight is not equivalent to removing samples\"\n ),\n }\n }\n", "\"\"\"Metrics to assess performance on regression task.\n\nFunctions named as ``*_score`` return a scalar value to maximize: the higher\nthe better.\n\nFunction named as ``*_error`` or ``*_loss`` return a scalar value to minimize:\nthe lower the better.\n\"\"\"\n\n# Authors: Alexandre Gramfort <[email protected]>\n# Mathieu Blondel <[email protected]>\n# Olivier Grisel <[email protected]>\n# Arnaud Joly <[email protected]>\n# Jochen Wersdorfer <[email protected]>\n# Lars Buitinck\n# Joel Nothman <[email protected]>\n# Karan Desai <[email protected]>\n# Noel Dawe <[email protected]>\n# Manoj Kumar <[email protected]>\n# Michael Eickenberg <[email protected]>\n# Konstantin Shmelkov <[email protected]>\n# Christian Lorentzen <[email protected]>\n# Ashutosh Hathidara <[email protected]>\n# Uttam kumar <[email protected]>\n# License: BSD 3 clause\n\nimport warnings\n\nimport numpy as np\n\nfrom .._loss.glm_distribution import TweedieDistribution\nfrom ..exceptions import UndefinedMetricWarning\nfrom ..utils.validation import (\n check_array,\n check_consistent_length,\n _num_samples,\n column_or_1d,\n _check_sample_weight,\n _deprecate_positional_args,\n)\nfrom ..utils.stats import _weighted_percentile\n\n\n__ALL__ = [\n \"max_error\",\n \"mean_absolute_error\",\n \"mean_squared_error\",\n \"mean_squared_log_error\",\n \"median_absolute_error\",\n \"mean_absolute_percentage_error\",\n \"mean_pinball_loss\",\n \"r2_score\",\n \"explained_variance_score\",\n \"mean_tweedie_deviance\",\n \"mean_poisson_deviance\",\n \"mean_gamma_deviance\",\n]\n\n\ndef _check_reg_targets(y_true, y_pred, multioutput, dtype=\"numeric\"):\n \"\"\"Check that y_true and y_pred belong to the same regression task.\n\n Parameters\n ----------\n y_true : array-like\n\n y_pred : array-like\n\n multioutput : array-like or string in ['raw_values', uniform_average',\n 'variance_weighted'] or None\n None is accepted due to backward compatibility of r2_score().\n\n Returns\n -------\n type_true : one of {'continuous', continuous-multioutput'}\n The type of the true target data, as output by\n 'utils.multiclass.type_of_target'.\n\n y_true : array-like of shape (n_samples, n_outputs)\n Ground truth (correct) target values.\n\n y_pred : array-like of shape (n_samples, n_outputs)\n Estimated target values.\n\n multioutput : array-like of shape (n_outputs) or string in ['raw_values',\n uniform_average', 'variance_weighted'] or None\n Custom output weights if ``multioutput`` is array-like or\n just the corresponding argument if ``multioutput`` is a\n correct keyword.\n\n dtype : str or list, default=\"numeric\"\n the dtype argument passed to check_array.\n \"\"\"\n check_consistent_length(y_true, y_pred)\n y_true = check_array(y_true, ensure_2d=False, dtype=dtype)\n y_pred = check_array(y_pred, ensure_2d=False, dtype=dtype)\n\n if y_true.ndim == 1:\n y_true = y_true.reshape((-1, 1))\n\n if y_pred.ndim == 1:\n y_pred = y_pred.reshape((-1, 1))\n\n if y_true.shape[1] != y_pred.shape[1]:\n raise ValueError(\n \"y_true and y_pred have different number of output ({0}!={1})\".format(\n y_true.shape[1], y_pred.shape[1]\n )\n )\n\n n_outputs = y_true.shape[1]\n allowed_multioutput_str = (\"raw_values\", \"uniform_average\", \"variance_weighted\")\n if isinstance(multioutput, str):\n if multioutput not in allowed_multioutput_str:\n raise ValueError(\n \"Allowed 'multioutput' string values are {}. \"\n \"You provided multioutput={!r}\".format(\n allowed_multioutput_str, multioutput\n )\n )\n elif multioutput is not None:\n multioutput = check_array(multioutput, ensure_2d=False)\n if n_outputs == 1:\n raise ValueError(\"Custom weights are useful only in multi-output cases.\")\n elif n_outputs != len(multioutput):\n raise ValueError(\n \"There must be equally many custom weights (%d) as outputs (%d).\"\n % (len(multioutput), n_outputs)\n )\n y_type = \"continuous\" if n_outputs == 1 else \"continuous-multioutput\"\n\n return y_type, y_true, y_pred, multioutput\n\n\ndef mean_absolute_error(\n y_true, y_pred, *, sample_weight=None, multioutput=\"uniform_average\"\n):\n \"\"\"Mean absolute error regression loss.\n\n Read more in the :ref:`User Guide <mean_absolute_error>`.\n\n Parameters\n ----------\n y_true : array-like of shape (n_samples,) or (n_samples, n_outputs)\n Ground truth (correct) target values.\n\n y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs)\n Estimated target values.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights.\n\n multioutput : {'raw_values', 'uniform_average'} or array-like of shape \\\n (n_outputs,), default='uniform_average'\n Defines aggregating of multiple output values.\n Array-like value defines weights used to average errors.\n\n 'raw_values' :\n Returns a full set of errors in case of multioutput input.\n\n 'uniform_average' :\n Errors of all outputs are averaged with uniform weight.\n\n\n Returns\n -------\n loss : float or ndarray of floats\n If multioutput is 'raw_values', then mean absolute error is returned\n for each output separately.\n If multioutput is 'uniform_average' or an ndarray of weights, then the\n weighted average of all output errors is returned.\n\n MAE output is non-negative floating point. The best value is 0.0.\n\n Examples\n --------\n >>> from sklearn.metrics import mean_absolute_error\n >>> y_true = [3, -0.5, 2, 7]\n >>> y_pred = [2.5, 0.0, 2, 8]\n >>> mean_absolute_error(y_true, y_pred)\n 0.5\n >>> y_true = [[0.5, 1], [-1, 1], [7, -6]]\n >>> y_pred = [[0, 2], [-1, 2], [8, -5]]\n >>> mean_absolute_error(y_true, y_pred)\n 0.75\n >>> mean_absolute_error(y_true, y_pred, multioutput='raw_values')\n array([0.5, 1. ])\n >>> mean_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7])\n 0.85...\n \"\"\"\n y_type, y_true, y_pred, multioutput = _check_reg_targets(\n y_true, y_pred, multioutput\n )\n check_consistent_length(y_true, y_pred, sample_weight)\n output_errors = np.average(np.abs(y_pred - y_true), weights=sample_weight, axis=0)\n if isinstance(multioutput, str):\n if multioutput == \"raw_values\":\n return output_errors\n elif multioutput == \"uniform_average\":\n # pass None as weights to np.average: uniform mean\n multioutput = None\n\n return np.average(output_errors, weights=multioutput)\n\n\ndef mean_pinball_loss(\n y_true, y_pred, *, sample_weight=None, alpha=0.5, multioutput=\"uniform_average\"\n):\n \"\"\"Pinball loss for quantile regression.\n\n Read more in the :ref:`User Guide <pinball_loss>`.\n\n Parameters\n ----------\n y_true : array-like of shape (n_samples,) or (n_samples, n_outputs)\n Ground truth (correct) target values.\n\n y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs)\n Estimated target values.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights.\n\n alpha: float, slope of the pinball loss, default=0.5,\n this loss is equivalent to :ref:`mean_absolute_error` when `alpha=0.5`,\n `alpha=0.95` is minimized by estimators of the 95th percentile.\n\n multioutput : {'raw_values', 'uniform_average'} or array-like of shape \\\n (n_outputs,), default='uniform_average'\n Defines aggregating of multiple output values.\n Array-like value defines weights used to average errors.\n\n 'raw_values' :\n Returns a full set of errors in case of multioutput input.\n\n 'uniform_average' :\n Errors of all outputs are averaged with uniform weight.\n\n Returns\n -------\n loss : float or ndarray of floats\n If multioutput is 'raw_values', then mean absolute error is returned\n for each output separately.\n If multioutput is 'uniform_average' or an ndarray of weights, then the\n weighted average of all output errors is returned.\n\n The pinball loss output is a non-negative floating point. The best\n value is 0.0.\n\n Examples\n --------\n >>> from sklearn.metrics import mean_pinball_loss\n >>> y_true = [1, 2, 3]\n >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.1)\n 0.03...\n >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.1)\n 0.3...\n >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.9)\n 0.3...\n >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.9)\n 0.03...\n >>> mean_pinball_loss(y_true, y_true, alpha=0.1)\n 0.0\n >>> mean_pinball_loss(y_true, y_true, alpha=0.9)\n 0.0\n \"\"\"\n y_type, y_true, y_pred, multioutput = _check_reg_targets(\n y_true, y_pred, multioutput\n )\n check_consistent_length(y_true, y_pred, sample_weight)\n diff = y_true - y_pred\n sign = (diff >= 0).astype(diff.dtype)\n loss = alpha * sign * diff - (1 - alpha) * (1 - sign) * diff\n output_errors = np.average(loss, weights=sample_weight, axis=0)\n if isinstance(multioutput, str):\n if multioutput == \"raw_values\":\n return output_errors\n elif multioutput == \"uniform_average\":\n # pass None as weights to np.average: uniform mean\n multioutput = None\n else:\n raise ValueError(\n \"multioutput is expected to be 'raw_values' \"\n \"or 'uniform_average' but we got %r\"\n \" instead.\" % multioutput\n )\n\n return np.average(output_errors, weights=multioutput)\n\n\n@_deprecate_positional_args(version=\"1.1\")\ndef mean_absolute_percentage_error(\n y_true, y_pred, *, sample_weight=None, multioutput=\"uniform_average\"\n):\n \"\"\"Mean absolute percentage error (MAPE) regression loss.\n\n Note here that the output is not a percentage in the range [0, 100]\n and a value of 100 does not mean 100% but 1e2. Furthermore, the output\n can be arbitrarily high when `y_true` is small (which is specific to the\n metric) or when `abs(y_true - y_pred)` is large (which is common for most\n regression metrics). Read more in the\n :ref:`User Guide <mean_absolute_percentage_error>`.\n\n .. versionadded:: 0.24\n\n Parameters\n ----------\n y_true : array-like of shape (n_samples,) or (n_samples, n_outputs)\n Ground truth (correct) target values.\n\n y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs)\n Estimated target values.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights.\n\n multioutput : {'raw_values', 'uniform_average'} or array-like\n Defines aggregating of multiple output values.\n Array-like value defines weights used to average errors.\n If input is list then the shape must be (n_outputs,).\n\n 'raw_values' :\n Returns a full set of errors in case of multioutput input.\n\n 'uniform_average' :\n Errors of all outputs are averaged with uniform weight.\n\n Returns\n -------\n loss : float or ndarray of floats\n If multioutput is 'raw_values', then mean absolute percentage error\n is returned for each output separately.\n If multioutput is 'uniform_average' or an ndarray of weights, then the\n weighted average of all output errors is returned.\n\n MAPE output is non-negative floating point. The best value is 0.0.\n But note that bad predictions can lead to arbitrarily large\n MAPE values, especially if some `y_true` values are very close to zero.\n Note that we return a large value instead of `inf` when `y_true` is zero.\n\n Examples\n --------\n >>> from sklearn.metrics import mean_absolute_percentage_error\n >>> y_true = [3, -0.5, 2, 7]\n >>> y_pred = [2.5, 0.0, 2, 8]\n >>> mean_absolute_percentage_error(y_true, y_pred)\n 0.3273...\n >>> y_true = [[0.5, 1], [-1, 1], [7, -6]]\n >>> y_pred = [[0, 2], [-1, 2], [8, -5]]\n >>> mean_absolute_percentage_error(y_true, y_pred)\n 0.5515...\n >>> mean_absolute_percentage_error(y_true, y_pred, multioutput=[0.3, 0.7])\n 0.6198...\n >>> # the value when some element of the y_true is zero is arbitrarily high because\n >>> # of the division by epsilon\n >>> y_true = [1., 0., 2.4, 7.]\n >>> y_pred = [1.2, 0.1, 2.4, 8.]\n >>> mean_absolute_percentage_error(y_true, y_pred)\n 112589990684262.48\n \"\"\"\n y_type, y_true, y_pred, multioutput = _check_reg_targets(\n y_true, y_pred, multioutput\n )\n check_consistent_length(y_true, y_pred, sample_weight)\n epsilon = np.finfo(np.float64).eps\n mape = np.abs(y_pred - y_true) / np.maximum(np.abs(y_true), epsilon)\n output_errors = np.average(mape, weights=sample_weight, axis=0)\n if isinstance(multioutput, str):\n if multioutput == \"raw_values\":\n return output_errors\n elif multioutput == \"uniform_average\":\n # pass None as weights to np.average: uniform mean\n multioutput = None\n\n return np.average(output_errors, weights=multioutput)\n\n\ndef mean_squared_error(\n y_true, y_pred, *, sample_weight=None, multioutput=\"uniform_average\", squared=True\n):\n \"\"\"Mean squared error regression loss.\n\n Read more in the :ref:`User Guide <mean_squared_error>`.\n\n Parameters\n ----------\n y_true : array-like of shape (n_samples,) or (n_samples, n_outputs)\n Ground truth (correct) target values.\n\n y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs)\n Estimated target values.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights.\n\n multioutput : {'raw_values', 'uniform_average'} or array-like of shape \\\n (n_outputs,), default='uniform_average'\n Defines aggregating of multiple output values.\n Array-like value defines weights used to average errors.\n\n 'raw_values' :\n Returns a full set of errors in case of multioutput input.\n\n 'uniform_average' :\n Errors of all outputs are averaged with uniform weight.\n\n squared : bool, default=True\n If True returns MSE value, if False returns RMSE value.\n\n Returns\n -------\n loss : float or ndarray of floats\n A non-negative floating point value (the best value is 0.0), or an\n array of floating point values, one for each individual target.\n\n Examples\n --------\n >>> from sklearn.metrics import mean_squared_error\n >>> y_true = [3, -0.5, 2, 7]\n >>> y_pred = [2.5, 0.0, 2, 8]\n >>> mean_squared_error(y_true, y_pred)\n 0.375\n >>> y_true = [3, -0.5, 2, 7]\n >>> y_pred = [2.5, 0.0, 2, 8]\n >>> mean_squared_error(y_true, y_pred, squared=False)\n 0.612...\n >>> y_true = [[0.5, 1],[-1, 1],[7, -6]]\n >>> y_pred = [[0, 2],[-1, 2],[8, -5]]\n >>> mean_squared_error(y_true, y_pred)\n 0.708...\n >>> mean_squared_error(y_true, y_pred, squared=False)\n 0.822...\n >>> mean_squared_error(y_true, y_pred, multioutput='raw_values')\n array([0.41666667, 1. ])\n >>> mean_squared_error(y_true, y_pred, multioutput=[0.3, 0.7])\n 0.825...\n \"\"\"\n y_type, y_true, y_pred, multioutput = _check_reg_targets(\n y_true, y_pred, multioutput\n )\n check_consistent_length(y_true, y_pred, sample_weight)\n output_errors = np.average((y_true - y_pred) ** 2, axis=0, weights=sample_weight)\n\n if not squared:\n output_errors = np.sqrt(output_errors)\n\n if isinstance(multioutput, str):\n if multioutput == \"raw_values\":\n return output_errors\n elif multioutput == \"uniform_average\":\n # pass None as weights to np.average: uniform mean\n multioutput = None\n\n return np.average(output_errors, weights=multioutput)\n\n\ndef mean_squared_log_error(\n y_true, y_pred, *, sample_weight=None, multioutput=\"uniform_average\", squared=True\n):\n \"\"\"Mean squared logarithmic error regression loss.\n\n Read more in the :ref:`User Guide <mean_squared_log_error>`.\n\n Parameters\n ----------\n y_true : array-like of shape (n_samples,) or (n_samples, n_outputs)\n Ground truth (correct) target values.\n\n y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs)\n Estimated target values.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights.\n\n multioutput : {'raw_values', 'uniform_average'} or array-like of shape \\\n (n_outputs,), default='uniform_average'\n\n Defines aggregating of multiple output values.\n Array-like value defines weights used to average errors.\n\n 'raw_values' :\n Returns a full set of errors when the input is of multioutput\n format.\n\n 'uniform_average' :\n Errors of all outputs are averaged with uniform weight.\n squared : bool, default=True\n If True returns MSLE (mean squared log error) value.\n If False returns RMSLE (root mean squared log error) value.\n\n Returns\n -------\n loss : float or ndarray of floats\n A non-negative floating point value (the best value is 0.0), or an\n array of floating point values, one for each individual target.\n\n Examples\n --------\n >>> from sklearn.metrics import mean_squared_log_error\n >>> y_true = [3, 5, 2.5, 7]\n >>> y_pred = [2.5, 5, 4, 8]\n >>> mean_squared_log_error(y_true, y_pred)\n 0.039...\n >>> mean_squared_log_error(y_true, y_pred, squared=False)\n 0.199...\n >>> y_true = [[0.5, 1], [1, 2], [7, 6]]\n >>> y_pred = [[0.5, 2], [1, 2.5], [8, 8]]\n >>> mean_squared_log_error(y_true, y_pred)\n 0.044...\n >>> mean_squared_log_error(y_true, y_pred, multioutput='raw_values')\n array([0.00462428, 0.08377444])\n >>> mean_squared_log_error(y_true, y_pred, multioutput=[0.3, 0.7])\n 0.060...\n \"\"\"\n y_type, y_true, y_pred, multioutput = _check_reg_targets(\n y_true, y_pred, multioutput\n )\n check_consistent_length(y_true, y_pred, sample_weight)\n\n if (y_true < 0).any() or (y_pred < 0).any():\n raise ValueError(\n \"Mean Squared Logarithmic Error cannot be used when \"\n \"targets contain negative values.\"\n )\n\n return mean_squared_error(\n np.log1p(y_true),\n np.log1p(y_pred),\n sample_weight=sample_weight,\n multioutput=multioutput,\n squared=squared,\n )\n\n\ndef median_absolute_error(\n y_true, y_pred, *, multioutput=\"uniform_average\", sample_weight=None\n):\n \"\"\"Median absolute error regression loss.\n\n Median absolute error output is non-negative floating point. The best value\n is 0.0. Read more in the :ref:`User Guide <median_absolute_error>`.\n\n Parameters\n ----------\n y_true : array-like of shape = (n_samples) or (n_samples, n_outputs)\n Ground truth (correct) target values.\n\n y_pred : array-like of shape = (n_samples) or (n_samples, n_outputs)\n Estimated target values.\n\n multioutput : {'raw_values', 'uniform_average'} or array-like of shape \\\n (n_outputs,), default='uniform_average'\n Defines aggregating of multiple output values. Array-like value defines\n weights used to average errors.\n\n 'raw_values' :\n Returns a full set of errors in case of multioutput input.\n\n 'uniform_average' :\n Errors of all outputs are averaged with uniform weight.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights.\n\n .. versionadded:: 0.24\n\n Returns\n -------\n loss : float or ndarray of floats\n If multioutput is 'raw_values', then mean absolute error is returned\n for each output separately.\n If multioutput is 'uniform_average' or an ndarray of weights, then the\n weighted average of all output errors is returned.\n\n Examples\n --------\n >>> from sklearn.metrics import median_absolute_error\n >>> y_true = [3, -0.5, 2, 7]\n >>> y_pred = [2.5, 0.0, 2, 8]\n >>> median_absolute_error(y_true, y_pred)\n 0.5\n >>> y_true = [[0.5, 1], [-1, 1], [7, -6]]\n >>> y_pred = [[0, 2], [-1, 2], [8, -5]]\n >>> median_absolute_error(y_true, y_pred)\n 0.75\n >>> median_absolute_error(y_true, y_pred, multioutput='raw_values')\n array([0.5, 1. ])\n >>> median_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7])\n 0.85\n \"\"\"\n y_type, y_true, y_pred, multioutput = _check_reg_targets(\n y_true, y_pred, multioutput\n )\n if sample_weight is None:\n output_errors = np.median(np.abs(y_pred - y_true), axis=0)\n else:\n sample_weight = _check_sample_weight(sample_weight, y_pred)\n output_errors = _weighted_percentile(\n np.abs(y_pred - y_true), sample_weight=sample_weight\n )\n if isinstance(multioutput, str):\n if multioutput == \"raw_values\":\n return output_errors\n elif multioutput == \"uniform_average\":\n # pass None as weights to np.average: uniform mean\n multioutput = None\n\n return np.average(output_errors, weights=multioutput)\n\n\ndef explained_variance_score(\n y_true, y_pred, *, sample_weight=None, multioutput=\"uniform_average\"\n):\n \"\"\"Explained variance regression score function.\n\n Best possible score is 1.0, lower values are worse.\n\n Read more in the :ref:`User Guide <explained_variance_score>`.\n\n Parameters\n ----------\n y_true : array-like of shape (n_samples,) or (n_samples, n_outputs)\n Ground truth (correct) target values.\n\n y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs)\n Estimated target values.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights.\n\n multioutput : {'raw_values', 'uniform_average', 'variance_weighted'} or \\\n array-like of shape (n_outputs,), default='uniform_average'\n Defines aggregating of multiple output scores.\n Array-like value defines weights used to average scores.\n\n 'raw_values' :\n Returns a full set of scores in case of multioutput input.\n\n 'uniform_average' :\n Scores of all outputs are averaged with uniform weight.\n\n 'variance_weighted' :\n Scores of all outputs are averaged, weighted by the variances\n of each individual output.\n\n Returns\n -------\n score : float or ndarray of floats\n The explained variance or ndarray if 'multioutput' is 'raw_values'.\n\n Notes\n -----\n This is not a symmetric function.\n\n Examples\n --------\n >>> from sklearn.metrics import explained_variance_score\n >>> y_true = [3, -0.5, 2, 7]\n >>> y_pred = [2.5, 0.0, 2, 8]\n >>> explained_variance_score(y_true, y_pred)\n 0.957...\n >>> y_true = [[0.5, 1], [-1, 1], [7, -6]]\n >>> y_pred = [[0, 2], [-1, 2], [8, -5]]\n >>> explained_variance_score(y_true, y_pred, multioutput='uniform_average')\n 0.983...\n \"\"\"\n y_type, y_true, y_pred, multioutput = _check_reg_targets(\n y_true, y_pred, multioutput\n )\n check_consistent_length(y_true, y_pred, sample_weight)\n\n y_diff_avg = np.average(y_true - y_pred, weights=sample_weight, axis=0)\n numerator = np.average(\n (y_true - y_pred - y_diff_avg) ** 2, weights=sample_weight, axis=0\n )\n\n y_true_avg = np.average(y_true, weights=sample_weight, axis=0)\n denominator = np.average((y_true - y_true_avg) ** 2, weights=sample_weight, axis=0)\n\n nonzero_numerator = numerator != 0\n nonzero_denominator = denominator != 0\n valid_score = nonzero_numerator & nonzero_denominator\n output_scores = np.ones(y_true.shape[1])\n\n output_scores[valid_score] = 1 - (numerator[valid_score] / denominator[valid_score])\n output_scores[nonzero_numerator & ~nonzero_denominator] = 0.0\n if isinstance(multioutput, str):\n if multioutput == \"raw_values\":\n # return scores individually\n return output_scores\n elif multioutput == \"uniform_average\":\n # passing to np.average() None as weights results is uniform mean\n avg_weights = None\n elif multioutput == \"variance_weighted\":\n avg_weights = denominator\n else:\n avg_weights = multioutput\n\n return np.average(output_scores, weights=avg_weights)\n\n\ndef r2_score(y_true, y_pred, *, sample_weight=None, multioutput=\"uniform_average\"):\n \"\"\":math:`R^2` (coefficient of determination) regression score function.\n\n Best possible score is 1.0 and it can be negative (because the\n model can be arbitrarily worse). A constant model that always\n predicts the expected value of y, disregarding the input features,\n would get a :math:`R^2` score of 0.0.\n\n Read more in the :ref:`User Guide <r2_score>`.\n\n Parameters\n ----------\n y_true : array-like of shape (n_samples,) or (n_samples, n_outputs)\n Ground truth (correct) target values.\n\n y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs)\n Estimated target values.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights.\n\n multioutput : {'raw_values', 'uniform_average', 'variance_weighted'}, \\\n array-like of shape (n_outputs,) or None, default='uniform_average'\n\n Defines aggregating of multiple output scores.\n Array-like value defines weights used to average scores.\n Default is \"uniform_average\".\n\n 'raw_values' :\n Returns a full set of scores in case of multioutput input.\n\n 'uniform_average' :\n Scores of all outputs are averaged with uniform weight.\n\n 'variance_weighted' :\n Scores of all outputs are averaged, weighted by the variances\n of each individual output.\n\n .. versionchanged:: 0.19\n Default value of multioutput is 'uniform_average'.\n\n Returns\n -------\n z : float or ndarray of floats\n The :math:`R^2` score or ndarray of scores if 'multioutput' is\n 'raw_values'.\n\n Notes\n -----\n This is not a symmetric function.\n\n Unlike most other scores, :math:`R^2` score may be negative (it need not\n actually be the square of a quantity R).\n\n This metric is not well-defined for single samples and will return a NaN\n value if n_samples is less than two.\n\n References\n ----------\n .. [1] `Wikipedia entry on the Coefficient of determination\n <https://en.wikipedia.org/wiki/Coefficient_of_determination>`_\n\n Examples\n --------\n >>> from sklearn.metrics import r2_score\n >>> y_true = [3, -0.5, 2, 7]\n >>> y_pred = [2.5, 0.0, 2, 8]\n >>> r2_score(y_true, y_pred)\n 0.948...\n >>> y_true = [[0.5, 1], [-1, 1], [7, -6]]\n >>> y_pred = [[0, 2], [-1, 2], [8, -5]]\n >>> r2_score(y_true, y_pred,\n ... multioutput='variance_weighted')\n 0.938...\n >>> y_true = [1, 2, 3]\n >>> y_pred = [1, 2, 3]\n >>> r2_score(y_true, y_pred)\n 1.0\n >>> y_true = [1, 2, 3]\n >>> y_pred = [2, 2, 2]\n >>> r2_score(y_true, y_pred)\n 0.0\n >>> y_true = [1, 2, 3]\n >>> y_pred = [3, 2, 1]\n >>> r2_score(y_true, y_pred)\n -3.0\n \"\"\"\n y_type, y_true, y_pred, multioutput = _check_reg_targets(\n y_true, y_pred, multioutput\n )\n check_consistent_length(y_true, y_pred, sample_weight)\n\n if _num_samples(y_pred) < 2:\n msg = \"R^2 score is not well-defined with less than two samples.\"\n warnings.warn(msg, UndefinedMetricWarning)\n return float(\"nan\")\n\n if sample_weight is not None:\n sample_weight = column_or_1d(sample_weight)\n weight = sample_weight[:, np.newaxis]\n else:\n weight = 1.0\n\n numerator = (weight * (y_true - y_pred) ** 2).sum(axis=0, dtype=np.float64)\n denominator = (\n weight * (y_true - np.average(y_true, axis=0, weights=sample_weight)) ** 2\n ).sum(axis=0, dtype=np.float64)\n nonzero_denominator = denominator != 0\n nonzero_numerator = numerator != 0\n valid_score = nonzero_denominator & nonzero_numerator\n output_scores = np.ones([y_true.shape[1]])\n output_scores[valid_score] = 1 - (numerator[valid_score] / denominator[valid_score])\n # arbitrary set to zero to avoid -inf scores, having a constant\n # y_true is not interesting for scoring a regression anyway\n output_scores[nonzero_numerator & ~nonzero_denominator] = 0.0\n if isinstance(multioutput, str):\n if multioutput == \"raw_values\":\n # return scores individually\n return output_scores\n elif multioutput == \"uniform_average\":\n # passing None as weights results is uniform mean\n avg_weights = None\n elif multioutput == \"variance_weighted\":\n avg_weights = denominator\n # avoid fail on constant y or one-element arrays\n if not np.any(nonzero_denominator):\n if not np.any(nonzero_numerator):\n return 1.0\n else:\n return 0.0\n else:\n avg_weights = multioutput\n\n return np.average(output_scores, weights=avg_weights)\n\n\ndef max_error(y_true, y_pred):\n \"\"\"\n The max_error metric calculates the maximum residual error.\n\n Read more in the :ref:`User Guide <max_error>`.\n\n Parameters\n ----------\n y_true : array-like of shape (n_samples,)\n Ground truth (correct) target values.\n\n y_pred : array-like of shape (n_samples,)\n Estimated target values.\n\n Returns\n -------\n max_error : float\n A positive floating point value (the best value is 0.0).\n\n Examples\n --------\n >>> from sklearn.metrics import max_error\n >>> y_true = [3, 2, 7, 1]\n >>> y_pred = [4, 2, 7, 1]\n >>> max_error(y_true, y_pred)\n 1\n \"\"\"\n y_type, y_true, y_pred, _ = _check_reg_targets(y_true, y_pred, None)\n if y_type == \"continuous-multioutput\":\n raise ValueError(\"Multioutput not supported in max_error\")\n return np.max(np.abs(y_true - y_pred))\n\n\ndef mean_tweedie_deviance(y_true, y_pred, *, sample_weight=None, power=0):\n \"\"\"Mean Tweedie deviance regression loss.\n\n Read more in the :ref:`User Guide <mean_tweedie_deviance>`.\n\n Parameters\n ----------\n y_true : array-like of shape (n_samples,)\n Ground truth (correct) target values.\n\n y_pred : array-like of shape (n_samples,)\n Estimated target values.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights.\n\n power : float, default=0\n Tweedie power parameter. Either power <= 0 or power >= 1.\n\n The higher `p` the less weight is given to extreme\n deviations between true and predicted targets.\n\n - power < 0: Extreme stable distribution. Requires: y_pred > 0.\n - power = 0 : Normal distribution, output corresponds to\n mean_squared_error. y_true and y_pred can be any real numbers.\n - power = 1 : Poisson distribution. Requires: y_true >= 0 and\n y_pred > 0.\n - 1 < p < 2 : Compound Poisson distribution. Requires: y_true >= 0\n and y_pred > 0.\n - power = 2 : Gamma distribution. Requires: y_true > 0 and y_pred > 0.\n - power = 3 : Inverse Gaussian distribution. Requires: y_true > 0\n and y_pred > 0.\n - otherwise : Positive stable distribution. Requires: y_true > 0\n and y_pred > 0.\n\n Returns\n -------\n loss : float\n A non-negative floating point value (the best value is 0.0).\n\n Examples\n --------\n >>> from sklearn.metrics import mean_tweedie_deviance\n >>> y_true = [2, 0, 1, 4]\n >>> y_pred = [0.5, 0.5, 2., 2.]\n >>> mean_tweedie_deviance(y_true, y_pred, power=1)\n 1.4260...\n \"\"\"\n y_type, y_true, y_pred, _ = _check_reg_targets(\n y_true, y_pred, None, dtype=[np.float64, np.float32]\n )\n if y_type == \"continuous-multioutput\":\n raise ValueError(\"Multioutput not supported in mean_tweedie_deviance\")\n check_consistent_length(y_true, y_pred, sample_weight)\n\n if sample_weight is not None:\n sample_weight = column_or_1d(sample_weight)\n sample_weight = sample_weight[:, np.newaxis]\n\n dist = TweedieDistribution(power=power)\n dev = dist.unit_deviance(y_true, y_pred, check_input=True)\n\n return np.average(dev, weights=sample_weight)\n\n\ndef mean_poisson_deviance(y_true, y_pred, *, sample_weight=None):\n \"\"\"Mean Poisson deviance regression loss.\n\n Poisson deviance is equivalent to the Tweedie deviance with\n the power parameter `power=1`.\n\n Read more in the :ref:`User Guide <mean_tweedie_deviance>`.\n\n Parameters\n ----------\n y_true : array-like of shape (n_samples,)\n Ground truth (correct) target values. Requires y_true >= 0.\n\n y_pred : array-like of shape (n_samples,)\n Estimated target values. Requires y_pred > 0.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights.\n\n Returns\n -------\n loss : float\n A non-negative floating point value (the best value is 0.0).\n\n Examples\n --------\n >>> from sklearn.metrics import mean_poisson_deviance\n >>> y_true = [2, 0, 1, 4]\n >>> y_pred = [0.5, 0.5, 2., 2.]\n >>> mean_poisson_deviance(y_true, y_pred)\n 1.4260...\n \"\"\"\n return mean_tweedie_deviance(y_true, y_pred, sample_weight=sample_weight, power=1)\n\n\ndef mean_gamma_deviance(y_true, y_pred, *, sample_weight=None):\n \"\"\"Mean Gamma deviance regression loss.\n\n Gamma deviance is equivalent to the Tweedie deviance with\n the power parameter `power=2`. It is invariant to scaling of\n the target variable, and measures relative errors.\n\n Read more in the :ref:`User Guide <mean_tweedie_deviance>`.\n\n Parameters\n ----------\n y_true : array-like of shape (n_samples,)\n Ground truth (correct) target values. Requires y_true > 0.\n\n y_pred : array-like of shape (n_samples,)\n Estimated target values. Requires y_pred > 0.\n\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights.\n\n Returns\n -------\n loss : float\n A non-negative floating point value (the best value is 0.0).\n\n Examples\n --------\n >>> from sklearn.metrics import mean_gamma_deviance\n >>> y_true = [2, 0.5, 1, 4]\n >>> y_pred = [0.5, 0.5, 2., 2.]\n >>> mean_gamma_deviance(y_true, y_pred)\n 1.0568...\n \"\"\"\n return mean_tweedie_deviance(y_true, y_pred, sample_weight=sample_weight, power=2)\n\n\ndef d2_tweedie_score(y_true, y_pred, *, sample_weight=None, power=0):\n \"\"\"D^2 regression score function, percentage of Tweedie deviance explained.\n\n Best possible score is 1.0 and it can be negative (because the model can be\n arbitrarily worse). A model that always uses the empirical mean of `y_true` as\n constant prediction, disregarding the input features, gets a D^2 score of 0.0.\n\n Read more in the :ref:`User Guide <d2_tweedie_score>`.\n\n .. versionadded:: 1.0\n\n Parameters\n ----------\n y_true : array-like of shape (n_samples,)\n Ground truth (correct) target values.\n\n y_pred : array-like of shape (n_samples,)\n Estimated target values.\n\n sample_weight : array-like of shape (n_samples,), optional\n Sample weights.\n\n power : float, default=0\n Tweedie power parameter. Either power <= 0 or power >= 1.\n\n The higher `p` the less weight is given to extreme\n deviations between true and predicted targets.\n\n - power < 0: Extreme stable distribution. Requires: y_pred > 0.\n - power = 0 : Normal distribution, output corresponds to r2_score.\n y_true and y_pred can be any real numbers.\n - power = 1 : Poisson distribution. Requires: y_true >= 0 and\n y_pred > 0.\n - 1 < p < 2 : Compound Poisson distribution. Requires: y_true >= 0\n and y_pred > 0.\n - power = 2 : Gamma distribution. Requires: y_true > 0 and y_pred > 0.\n - power = 3 : Inverse Gaussian distribution. Requires: y_true > 0\n and y_pred > 0.\n - otherwise : Positive stable distribution. Requires: y_true > 0\n and y_pred > 0.\n\n Returns\n -------\n z : float or ndarray of floats\n The D^2 score.\n\n Notes\n -----\n This is not a symmetric function.\n\n Like R^2, D^2 score may be negative (it need not actually be the square of\n a quantity D).\n\n This metric is not well-defined for single samples and will return a NaN\n value if n_samples is less than two.\n\n References\n ----------\n .. [1] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J.\n Wainwright. \"Statistical Learning with Sparsity: The Lasso and\n Generalizations.\" (2015). https://trevorhastie.github.io\n\n Examples\n --------\n >>> from sklearn.metrics import d2_tweedie_score\n >>> y_true = [0.5, 1, 2.5, 7]\n >>> y_pred = [1, 1, 5, 3.5]\n >>> d2_tweedie_score(y_true, y_pred)\n 0.285...\n >>> d2_tweedie_score(y_true, y_pred, power=1)\n 0.487...\n >>> d2_tweedie_score(y_true, y_pred, power=2)\n 0.630...\n >>> d2_tweedie_score(y_true, y_true, power=2)\n 1.0\n \"\"\"\n y_type, y_true, y_pred, _ = _check_reg_targets(\n y_true, y_pred, None, dtype=[np.float64, np.float32]\n )\n if y_type == \"continuous-multioutput\":\n raise ValueError(\"Multioutput not supported in d2_tweedie_score\")\n check_consistent_length(y_true, y_pred, sample_weight)\n\n if _num_samples(y_pred) < 2:\n msg = \"D^2 score is not well-defined with less than two samples.\"\n warnings.warn(msg, UndefinedMetricWarning)\n return float(\"nan\")\n\n if sample_weight is not None:\n sample_weight = column_or_1d(sample_weight)\n sample_weight = sample_weight[:, np.newaxis]\n\n dist = TweedieDistribution(power=power)\n\n dev = dist.unit_deviance(y_true, y_pred, check_input=True)\n numerator = np.average(dev, weights=sample_weight)\n\n y_avg = np.average(y_true, weights=sample_weight)\n dev = dist.unit_deviance(y_true, y_avg, check_input=True)\n denominator = np.average(dev, weights=sample_weight)\n\n return 1 - numerator / denominator\n", "from numpy.testing import assert_\n\nimport numpy.distutils.fcompiler\n\ng77_version_strings = [\n ('GNU Fortran 0.5.25 20010319 (prerelease)', '0.5.25'),\n ('GNU Fortran (GCC 3.2) 3.2 20020814 (release)', '3.2'),\n ('GNU Fortran (GCC) 3.3.3 20040110 (prerelease) (Debian)', '3.3.3'),\n ('GNU Fortran (GCC) 3.3.3 (Debian 20040401)', '3.3.3'),\n ('GNU Fortran (GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)) 3.2.2'\n ' 20030222 (Red Hat Linux 3.2.2-5)', '3.2.2'),\n]\n\ngfortran_version_strings = [\n ('GNU Fortran 95 (GCC 4.0.3 20051023 (prerelease) (Debian 4.0.2-3))',\n '4.0.3'),\n ('GNU Fortran 95 (GCC) 4.1.0', '4.1.0'),\n ('GNU Fortran 95 (GCC) 4.2.0 20060218 (experimental)', '4.2.0'),\n ('GNU Fortran (GCC) 4.3.0 20070316 (experimental)', '4.3.0'),\n ('GNU Fortran (rubenvb-4.8.0) 4.8.0', '4.8.0'),\n ('4.8.0', '4.8.0'),\n ('4.0.3-7', '4.0.3'),\n (\"gfortran: warning: couldn't understand kern.osversion '14.1.0\\n4.9.1\",\n '4.9.1'),\n (\"gfortran: warning: couldn't understand kern.osversion '14.1.0\\n\"\n \"gfortran: warning: yet another warning\\n4.9.1\",\n '4.9.1'),\n ('GNU Fortran (crosstool-NG 8a21ab48) 7.2.0', '7.2.0')\n]\n\nclass TestG77Versions:\n def test_g77_version(self):\n fc = numpy.distutils.fcompiler.new_fcompiler(compiler='gnu')\n for vs, version in g77_version_strings:\n v = fc.version_match(vs)\n assert_(v == version, (vs, v))\n\n def test_not_g77(self):\n fc = numpy.distutils.fcompiler.new_fcompiler(compiler='gnu')\n for vs, _ in gfortran_version_strings:\n v = fc.version_match(vs)\n assert_(v is None, (vs, v))\n\nclass TestGFortranVersions:\n def test_gfortran_version(self):\n fc = numpy.distutils.fcompiler.new_fcompiler(compiler='gnu95')\n for vs, version in gfortran_version_strings:\n v = fc.version_match(vs)\n assert_(v == version, (vs, v))\n\n def test_not_gfortran(self):\n fc = numpy.distutils.fcompiler.new_fcompiler(compiler='gnu95')\n for vs, _ in g77_version_strings:\n v = fc.version_match(vs)\n assert_(v is None, (vs, v))\n", "import numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n Index,\n MultiIndex,\n Series,\n date_range,\n isna,\n)\nimport pandas._testing as tm\nfrom pandas.util.version import Version\n\n\[email protected](\n params=[\n \"linear\",\n \"index\",\n \"values\",\n \"nearest\",\n \"slinear\",\n \"zero\",\n \"quadratic\",\n \"cubic\",\n \"barycentric\",\n \"krogh\",\n \"polynomial\",\n \"spline\",\n \"piecewise_polynomial\",\n \"from_derivatives\",\n \"pchip\",\n \"akima\",\n \"cubicspline\",\n ]\n)\ndef nontemporal_method(request):\n \"\"\"Fixture that returns an (method name, required kwargs) pair.\n\n This fixture does not include method 'time' as a parameterization; that\n method requires a Series with a DatetimeIndex, and is generally tested\n separately from these non-temporal methods.\n \"\"\"\n method = request.param\n kwargs = {\"order\": 1} if method in (\"spline\", \"polynomial\") else {}\n return method, kwargs\n\n\[email protected](\n params=[\n \"linear\",\n \"slinear\",\n \"zero\",\n \"quadratic\",\n \"cubic\",\n \"barycentric\",\n \"krogh\",\n \"polynomial\",\n \"spline\",\n \"piecewise_polynomial\",\n \"from_derivatives\",\n \"pchip\",\n \"akima\",\n \"cubicspline\",\n ]\n)\ndef interp_methods_ind(request):\n \"\"\"Fixture that returns a (method name, required kwargs) pair to\n be tested for various Index types.\n\n This fixture does not include methods - 'time', 'index', 'nearest',\n 'values' as a parameterization\n \"\"\"\n method = request.param\n kwargs = {\"order\": 1} if method in (\"spline\", \"polynomial\") else {}\n return method, kwargs\n\n\nclass TestSeriesInterpolateData:\n def test_interpolate(self, datetime_series, string_series):\n ts = Series(np.arange(len(datetime_series), dtype=float), datetime_series.index)\n\n ts_copy = ts.copy()\n ts_copy[5:10] = np.NaN\n\n linear_interp = ts_copy.interpolate(method=\"linear\")\n tm.assert_series_equal(linear_interp, ts)\n\n ord_ts = Series(\n [d.toordinal() for d in datetime_series.index], index=datetime_series.index\n ).astype(float)\n\n ord_ts_copy = ord_ts.copy()\n ord_ts_copy[5:10] = np.NaN\n\n time_interp = ord_ts_copy.interpolate(method=\"time\")\n tm.assert_series_equal(time_interp, ord_ts)\n\n def test_interpolate_time_raises_for_non_timeseries(self):\n # When method='time' is used on a non-TimeSeries that contains a null\n # value, a ValueError should be raised.\n non_ts = Series([0, 1, 2, np.NaN])\n msg = \"time-weighted interpolation only works on Series.* with a DatetimeIndex\"\n with pytest.raises(ValueError, match=msg):\n non_ts.interpolate(method=\"time\")\n\n @td.skip_if_no_scipy\n def test_interpolate_cubicspline(self):\n\n ser = Series([10, 11, 12, 13])\n\n expected = Series(\n [11.00, 11.25, 11.50, 11.75, 12.00, 12.25, 12.50, 12.75, 13.00],\n index=Index([1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0]),\n )\n # interpolate at new_index\n new_index = ser.index.union(Index([1.25, 1.5, 1.75, 2.25, 2.5, 2.75])).astype(\n float\n )\n result = ser.reindex(new_index).interpolate(method=\"cubicspline\")[1:3]\n tm.assert_series_equal(result, expected)\n\n @td.skip_if_no_scipy\n def test_interpolate_pchip(self):\n\n ser = Series(np.sort(np.random.uniform(size=100)))\n\n # interpolate at new_index\n new_index = ser.index.union(\n Index([49.25, 49.5, 49.75, 50.25, 50.5, 50.75])\n ).astype(float)\n interp_s = ser.reindex(new_index).interpolate(method=\"pchip\")\n # does not blow up, GH5977\n interp_s[49:51]\n\n @td.skip_if_no_scipy\n def test_interpolate_akima(self):\n\n ser = Series([10, 11, 12, 13])\n\n # interpolate at new_index where `der` is zero\n expected = Series(\n [11.00, 11.25, 11.50, 11.75, 12.00, 12.25, 12.50, 12.75, 13.00],\n index=Index([1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0]),\n )\n new_index = ser.index.union(Index([1.25, 1.5, 1.75, 2.25, 2.5, 2.75])).astype(\n float\n )\n interp_s = ser.reindex(new_index).interpolate(method=\"akima\")\n tm.assert_series_equal(interp_s[1:3], expected)\n\n # interpolate at new_index where `der` is a non-zero int\n expected = Series(\n [11.0, 1.0, 1.0, 1.0, 12.0, 1.0, 1.0, 1.0, 13.0],\n index=Index([1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0]),\n )\n new_index = ser.index.union(Index([1.25, 1.5, 1.75, 2.25, 2.5, 2.75])).astype(\n float\n )\n interp_s = ser.reindex(new_index).interpolate(method=\"akima\", der=1)\n tm.assert_series_equal(interp_s[1:3], expected)\n\n @td.skip_if_no_scipy\n def test_interpolate_piecewise_polynomial(self):\n ser = Series([10, 11, 12, 13])\n\n expected = Series(\n [11.00, 11.25, 11.50, 11.75, 12.00, 12.25, 12.50, 12.75, 13.00],\n index=Index([1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0]),\n )\n # interpolate at new_index\n new_index = ser.index.union(Index([1.25, 1.5, 1.75, 2.25, 2.5, 2.75])).astype(\n float\n )\n interp_s = ser.reindex(new_index).interpolate(method=\"piecewise_polynomial\")\n tm.assert_series_equal(interp_s[1:3], expected)\n\n @td.skip_if_no_scipy\n def test_interpolate_from_derivatives(self):\n ser = Series([10, 11, 12, 13])\n\n expected = Series(\n [11.00, 11.25, 11.50, 11.75, 12.00, 12.25, 12.50, 12.75, 13.00],\n index=Index([1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0]),\n )\n # interpolate at new_index\n new_index = ser.index.union(Index([1.25, 1.5, 1.75, 2.25, 2.5, 2.75])).astype(\n float\n )\n interp_s = ser.reindex(new_index).interpolate(method=\"from_derivatives\")\n tm.assert_series_equal(interp_s[1:3], expected)\n\n @pytest.mark.parametrize(\n \"kwargs\",\n [\n {},\n pytest.param(\n {\"method\": \"polynomial\", \"order\": 1}, marks=td.skip_if_no_scipy\n ),\n ],\n )\n def test_interpolate_corners(self, kwargs):\n s = Series([np.nan, np.nan])\n tm.assert_series_equal(s.interpolate(**kwargs), s)\n\n s = Series([], dtype=object).interpolate()\n tm.assert_series_equal(s.interpolate(**kwargs), s)\n\n def test_interpolate_index_values(self):\n s = Series(np.nan, index=np.sort(np.random.rand(30)))\n s[::3] = np.random.randn(10)\n\n vals = s.index.values.astype(float)\n\n result = s.interpolate(method=\"index\")\n\n expected = s.copy()\n bad = isna(expected.values)\n good = ~bad\n expected = Series(\n np.interp(vals[bad], vals[good], s.values[good]), index=s.index[bad]\n )\n\n tm.assert_series_equal(result[bad], expected)\n\n # 'values' is synonymous with 'index' for the method kwarg\n other_result = s.interpolate(method=\"values\")\n\n tm.assert_series_equal(other_result, result)\n tm.assert_series_equal(other_result[bad], expected)\n\n def test_interpolate_non_ts(self):\n s = Series([1, 3, np.nan, np.nan, np.nan, 11])\n msg = (\n \"time-weighted interpolation only works on Series or DataFrames \"\n \"with a DatetimeIndex\"\n )\n with pytest.raises(ValueError, match=msg):\n s.interpolate(method=\"time\")\n\n @pytest.mark.parametrize(\n \"kwargs\",\n [\n {},\n pytest.param(\n {\"method\": \"polynomial\", \"order\": 1}, marks=td.skip_if_no_scipy\n ),\n ],\n )\n def test_nan_interpolate(self, kwargs):\n s = Series([0, 1, np.nan, 3])\n result = s.interpolate(**kwargs)\n expected = Series([0.0, 1.0, 2.0, 3.0])\n tm.assert_series_equal(result, expected)\n\n def test_nan_irregular_index(self):\n s = Series([1, 2, np.nan, 4], index=[1, 3, 5, 9])\n result = s.interpolate()\n expected = Series([1.0, 2.0, 3.0, 4.0], index=[1, 3, 5, 9])\n tm.assert_series_equal(result, expected)\n\n def test_nan_str_index(self):\n s = Series([0, 1, 2, np.nan], index=list(\"abcd\"))\n result = s.interpolate()\n expected = Series([0.0, 1.0, 2.0, 2.0], index=list(\"abcd\"))\n tm.assert_series_equal(result, expected)\n\n @td.skip_if_no_scipy\n def test_interp_quad(self):\n sq = Series([1, 4, np.nan, 16], index=[1, 2, 3, 4])\n result = sq.interpolate(method=\"quadratic\")\n expected = Series([1.0, 4.0, 9.0, 16.0], index=[1, 2, 3, 4])\n tm.assert_series_equal(result, expected)\n\n @td.skip_if_no_scipy\n def test_interp_scipy_basic(self):\n s = Series([1, 3, np.nan, 12, np.nan, 25])\n # slinear\n expected = Series([1.0, 3.0, 7.5, 12.0, 18.5, 25.0])\n result = s.interpolate(method=\"slinear\")\n tm.assert_series_equal(result, expected)\n\n result = s.interpolate(method=\"slinear\", downcast=\"infer\")\n tm.assert_series_equal(result, expected)\n # nearest\n expected = Series([1, 3, 3, 12, 12, 25])\n result = s.interpolate(method=\"nearest\")\n tm.assert_series_equal(result, expected.astype(\"float\"))\n\n result = s.interpolate(method=\"nearest\", downcast=\"infer\")\n tm.assert_series_equal(result, expected)\n # zero\n expected = Series([1, 3, 3, 12, 12, 25])\n result = s.interpolate(method=\"zero\")\n tm.assert_series_equal(result, expected.astype(\"float\"))\n\n result = s.interpolate(method=\"zero\", downcast=\"infer\")\n tm.assert_series_equal(result, expected)\n # quadratic\n # GH #15662.\n expected = Series([1, 3.0, 6.823529, 12.0, 18.058824, 25.0])\n result = s.interpolate(method=\"quadratic\")\n tm.assert_series_equal(result, expected)\n\n result = s.interpolate(method=\"quadratic\", downcast=\"infer\")\n tm.assert_series_equal(result, expected)\n # cubic\n expected = Series([1.0, 3.0, 6.8, 12.0, 18.2, 25.0])\n result = s.interpolate(method=\"cubic\")\n tm.assert_series_equal(result, expected)\n\n def test_interp_limit(self):\n s = Series([1, 3, np.nan, np.nan, np.nan, 11])\n\n expected = Series([1.0, 3.0, 5.0, 7.0, np.nan, 11.0])\n result = s.interpolate(method=\"linear\", limit=2)\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.parametrize(\"limit\", [-1, 0])\n def test_interpolate_invalid_nonpositive_limit(self, nontemporal_method, limit):\n # GH 9217: make sure limit is greater than zero.\n s = Series([1, 2, np.nan, 4])\n method, kwargs = nontemporal_method\n with pytest.raises(ValueError, match=\"Limit must be greater than 0\"):\n s.interpolate(limit=limit, method=method, **kwargs)\n\n def test_interpolate_invalid_float_limit(self, nontemporal_method):\n # GH 9217: make sure limit is an integer.\n s = Series([1, 2, np.nan, 4])\n method, kwargs = nontemporal_method\n limit = 2.0\n with pytest.raises(ValueError, match=\"Limit must be an integer\"):\n s.interpolate(limit=limit, method=method, **kwargs)\n\n @pytest.mark.parametrize(\"invalid_method\", [None, \"nonexistent_method\"])\n def test_interp_invalid_method(self, invalid_method):\n s = Series([1, 3, np.nan, 12, np.nan, 25])\n\n msg = f\"method must be one of.* Got '{invalid_method}' instead\"\n with pytest.raises(ValueError, match=msg):\n s.interpolate(method=invalid_method)\n\n # When an invalid method and invalid limit (such as -1) are\n # provided, the error message reflects the invalid method.\n with pytest.raises(ValueError, match=msg):\n s.interpolate(method=invalid_method, limit=-1)\n\n def test_interp_invalid_method_and_value(self):\n # GH#36624\n ser = Series([1, 3, np.nan, 12, np.nan, 25])\n\n msg = \"Cannot pass both fill_value and method\"\n with pytest.raises(ValueError, match=msg):\n ser.interpolate(fill_value=3, method=\"pad\")\n\n def test_interp_limit_forward(self):\n s = Series([1, 3, np.nan, np.nan, np.nan, 11])\n\n # Provide 'forward' (the default) explicitly here.\n expected = Series([1.0, 3.0, 5.0, 7.0, np.nan, 11.0])\n\n result = s.interpolate(method=\"linear\", limit=2, limit_direction=\"forward\")\n tm.assert_series_equal(result, expected)\n\n result = s.interpolate(method=\"linear\", limit=2, limit_direction=\"FORWARD\")\n tm.assert_series_equal(result, expected)\n\n def test_interp_unlimited(self):\n # these test are for issue #16282 default Limit=None is unlimited\n s = Series([np.nan, 1.0, 3.0, np.nan, np.nan, np.nan, 11.0, np.nan])\n expected = Series([1.0, 1.0, 3.0, 5.0, 7.0, 9.0, 11.0, 11.0])\n result = s.interpolate(method=\"linear\", limit_direction=\"both\")\n tm.assert_series_equal(result, expected)\n\n expected = Series([np.nan, 1.0, 3.0, 5.0, 7.0, 9.0, 11.0, 11.0])\n result = s.interpolate(method=\"linear\", limit_direction=\"forward\")\n tm.assert_series_equal(result, expected)\n\n expected = Series([1.0, 1.0, 3.0, 5.0, 7.0, 9.0, 11.0, np.nan])\n result = s.interpolate(method=\"linear\", limit_direction=\"backward\")\n tm.assert_series_equal(result, expected)\n\n def test_interp_limit_bad_direction(self):\n s = Series([1, 3, np.nan, np.nan, np.nan, 11])\n\n msg = (\n r\"Invalid limit_direction: expecting one of \\['forward', \"\n r\"'backward', 'both'\\], got 'abc'\"\n )\n with pytest.raises(ValueError, match=msg):\n s.interpolate(method=\"linear\", limit=2, limit_direction=\"abc\")\n\n # raises an error even if no limit is specified.\n with pytest.raises(ValueError, match=msg):\n s.interpolate(method=\"linear\", limit_direction=\"abc\")\n\n # limit_area introduced GH #16284\n def test_interp_limit_area(self):\n # These tests are for issue #9218 -- fill NaNs in both directions.\n s = Series([np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan])\n\n expected = Series([np.nan, np.nan, 3.0, 4.0, 5.0, 6.0, 7.0, np.nan, np.nan])\n result = s.interpolate(method=\"linear\", limit_area=\"inside\")\n tm.assert_series_equal(result, expected)\n\n expected = Series(\n [np.nan, np.nan, 3.0, 4.0, np.nan, np.nan, 7.0, np.nan, np.nan]\n )\n result = s.interpolate(method=\"linear\", limit_area=\"inside\", limit=1)\n tm.assert_series_equal(result, expected)\n\n expected = Series([np.nan, np.nan, 3.0, 4.0, np.nan, 6.0, 7.0, np.nan, np.nan])\n result = s.interpolate(\n method=\"linear\", limit_area=\"inside\", limit_direction=\"both\", limit=1\n )\n tm.assert_series_equal(result, expected)\n\n expected = Series([np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, 7.0])\n result = s.interpolate(method=\"linear\", limit_area=\"outside\")\n tm.assert_series_equal(result, expected)\n\n expected = Series(\n [np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, np.nan]\n )\n result = s.interpolate(method=\"linear\", limit_area=\"outside\", limit=1)\n tm.assert_series_equal(result, expected)\n\n expected = Series([np.nan, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, np.nan])\n result = s.interpolate(\n method=\"linear\", limit_area=\"outside\", limit_direction=\"both\", limit=1\n )\n tm.assert_series_equal(result, expected)\n\n expected = Series([3.0, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan])\n result = s.interpolate(\n method=\"linear\", limit_area=\"outside\", limit_direction=\"backward\"\n )\n tm.assert_series_equal(result, expected)\n\n # raises an error even if limit type is wrong.\n msg = r\"Invalid limit_area: expecting one of \\['inside', 'outside'\\], got abc\"\n with pytest.raises(ValueError, match=msg):\n s.interpolate(method=\"linear\", limit_area=\"abc\")\n\n @pytest.mark.parametrize(\n \"method, limit_direction, expected\",\n [\n (\"pad\", \"backward\", \"forward\"),\n (\"ffill\", \"backward\", \"forward\"),\n (\"backfill\", \"forward\", \"backward\"),\n (\"bfill\", \"forward\", \"backward\"),\n (\"pad\", \"both\", \"forward\"),\n (\"ffill\", \"both\", \"forward\"),\n (\"backfill\", \"both\", \"backward\"),\n (\"bfill\", \"both\", \"backward\"),\n ],\n )\n def test_interp_limit_direction_raises(self, method, limit_direction, expected):\n # https://github.com/pandas-dev/pandas/pull/34746\n s = Series([1, 2, 3])\n\n msg = f\"`limit_direction` must be '{expected}' for method `{method}`\"\n with pytest.raises(ValueError, match=msg):\n s.interpolate(method=method, limit_direction=limit_direction)\n\n @pytest.mark.parametrize(\n \"data, expected_data, kwargs\",\n (\n (\n [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],\n [np.nan, np.nan, 3.0, 3.0, 3.0, 3.0, 7.0, np.nan, np.nan],\n {\"method\": \"pad\", \"limit_area\": \"inside\"},\n ),\n (\n [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],\n [np.nan, np.nan, 3.0, 3.0, np.nan, np.nan, 7.0, np.nan, np.nan],\n {\"method\": \"pad\", \"limit_area\": \"inside\", \"limit\": 1},\n ),\n (\n [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],\n [np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, 7.0],\n {\"method\": \"pad\", \"limit_area\": \"outside\"},\n ),\n (\n [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],\n [np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, np.nan],\n {\"method\": \"pad\", \"limit_area\": \"outside\", \"limit\": 1},\n ),\n (\n [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],\n [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],\n {\"method\": \"pad\", \"limit_area\": \"outside\", \"limit\": 1},\n ),\n (\n range(5),\n range(5),\n {\"method\": \"pad\", \"limit_area\": \"outside\", \"limit\": 1},\n ),\n ),\n )\n def test_interp_limit_area_with_pad(self, data, expected_data, kwargs):\n # GH26796\n\n s = Series(data)\n expected = Series(expected_data)\n result = s.interpolate(**kwargs)\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"data, expected_data, kwargs\",\n (\n (\n [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],\n [np.nan, np.nan, 3.0, 7.0, 7.0, 7.0, 7.0, np.nan, np.nan],\n {\"method\": \"bfill\", \"limit_area\": \"inside\"},\n ),\n (\n [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],\n [np.nan, np.nan, 3.0, np.nan, np.nan, 7.0, 7.0, np.nan, np.nan],\n {\"method\": \"bfill\", \"limit_area\": \"inside\", \"limit\": 1},\n ),\n (\n [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],\n [3.0, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan],\n {\"method\": \"bfill\", \"limit_area\": \"outside\"},\n ),\n (\n [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],\n [np.nan, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan],\n {\"method\": \"bfill\", \"limit_area\": \"outside\", \"limit\": 1},\n ),\n ),\n )\n def test_interp_limit_area_with_backfill(self, data, expected_data, kwargs):\n # GH26796\n\n s = Series(data)\n expected = Series(expected_data)\n result = s.interpolate(**kwargs)\n tm.assert_series_equal(result, expected)\n\n def test_interp_limit_direction(self):\n # These tests are for issue #9218 -- fill NaNs in both directions.\n s = Series([1, 3, np.nan, np.nan, np.nan, 11])\n\n expected = Series([1.0, 3.0, np.nan, 7.0, 9.0, 11.0])\n result = s.interpolate(method=\"linear\", limit=2, limit_direction=\"backward\")\n tm.assert_series_equal(result, expected)\n\n expected = Series([1.0, 3.0, 5.0, np.nan, 9.0, 11.0])\n result = s.interpolate(method=\"linear\", limit=1, limit_direction=\"both\")\n tm.assert_series_equal(result, expected)\n\n # Check that this works on a longer series of nans.\n s = Series([1, 3, np.nan, np.nan, np.nan, 7, 9, np.nan, np.nan, 12, np.nan])\n\n expected = Series([1.0, 3.0, 4.0, 5.0, 6.0, 7.0, 9.0, 10.0, 11.0, 12.0, 12.0])\n result = s.interpolate(method=\"linear\", limit=2, limit_direction=\"both\")\n tm.assert_series_equal(result, expected)\n\n expected = Series(\n [1.0, 3.0, 4.0, np.nan, 6.0, 7.0, 9.0, 10.0, 11.0, 12.0, 12.0]\n )\n result = s.interpolate(method=\"linear\", limit=1, limit_direction=\"both\")\n tm.assert_series_equal(result, expected)\n\n def test_interp_limit_to_ends(self):\n # These test are for issue #10420 -- flow back to beginning.\n s = Series([np.nan, np.nan, 5, 7, 9, np.nan])\n\n expected = Series([5.0, 5.0, 5.0, 7.0, 9.0, np.nan])\n result = s.interpolate(method=\"linear\", limit=2, limit_direction=\"backward\")\n tm.assert_series_equal(result, expected)\n\n expected = Series([5.0, 5.0, 5.0, 7.0, 9.0, 9.0])\n result = s.interpolate(method=\"linear\", limit=2, limit_direction=\"both\")\n tm.assert_series_equal(result, expected)\n\n def test_interp_limit_before_ends(self):\n # These test are for issue #11115 -- limit ends properly.\n s = Series([np.nan, np.nan, 5, 7, np.nan, np.nan])\n\n expected = Series([np.nan, np.nan, 5.0, 7.0, 7.0, np.nan])\n result = s.interpolate(method=\"linear\", limit=1, limit_direction=\"forward\")\n tm.assert_series_equal(result, expected)\n\n expected = Series([np.nan, 5.0, 5.0, 7.0, np.nan, np.nan])\n result = s.interpolate(method=\"linear\", limit=1, limit_direction=\"backward\")\n tm.assert_series_equal(result, expected)\n\n expected = Series([np.nan, 5.0, 5.0, 7.0, 7.0, np.nan])\n result = s.interpolate(method=\"linear\", limit=1, limit_direction=\"both\")\n tm.assert_series_equal(result, expected)\n\n @td.skip_if_no_scipy\n def test_interp_all_good(self):\n s = Series([1, 2, 3])\n result = s.interpolate(method=\"polynomial\", order=1)\n tm.assert_series_equal(result, s)\n\n # non-scipy\n result = s.interpolate()\n tm.assert_series_equal(result, s)\n\n @pytest.mark.parametrize(\n \"check_scipy\", [False, pytest.param(True, marks=td.skip_if_no_scipy)]\n )\n def test_interp_multiIndex(self, check_scipy):\n idx = MultiIndex.from_tuples([(0, \"a\"), (1, \"b\"), (2, \"c\")])\n s = Series([1, 2, np.nan], index=idx)\n\n expected = s.copy()\n expected.loc[2] = 2\n result = s.interpolate()\n tm.assert_series_equal(result, expected)\n\n msg = \"Only `method=linear` interpolation is supported on MultiIndexes\"\n if check_scipy:\n with pytest.raises(ValueError, match=msg):\n s.interpolate(method=\"polynomial\", order=1)\n\n @td.skip_if_no_scipy\n def test_interp_nonmono_raise(self):\n s = Series([1, np.nan, 3], index=[0, 2, 1])\n msg = \"krogh interpolation requires that the index be monotonic\"\n with pytest.raises(ValueError, match=msg):\n s.interpolate(method=\"krogh\")\n\n @td.skip_if_no_scipy\n @pytest.mark.parametrize(\"method\", [\"nearest\", \"pad\"])\n def test_interp_datetime64(self, method, tz_naive_fixture):\n df = Series(\n [1, np.nan, 3], index=date_range(\"1/1/2000\", periods=3, tz=tz_naive_fixture)\n )\n result = df.interpolate(method=method)\n expected = Series(\n [1.0, 1.0, 3.0],\n index=date_range(\"1/1/2000\", periods=3, tz=tz_naive_fixture),\n )\n tm.assert_series_equal(result, expected)\n\n def test_interp_pad_datetime64tz_values(self):\n # GH#27628 missing.interpolate_2d should handle datetimetz values\n dti = date_range(\"2015-04-05\", periods=3, tz=\"US/Central\")\n ser = Series(dti)\n ser[1] = pd.NaT\n result = ser.interpolate(method=\"pad\")\n\n expected = Series(dti)\n expected[1] = expected[0]\n tm.assert_series_equal(result, expected)\n\n def test_interp_limit_no_nans(self):\n # GH 7173\n s = Series([1.0, 2.0, 3.0])\n result = s.interpolate(limit=1)\n expected = s\n tm.assert_series_equal(result, expected)\n\n @td.skip_if_no_scipy\n @pytest.mark.parametrize(\"method\", [\"polynomial\", \"spline\"])\n def test_no_order(self, method):\n # see GH-10633, GH-24014\n s = Series([0, 1, np.nan, 3])\n msg = \"You must specify the order of the spline or polynomial\"\n with pytest.raises(ValueError, match=msg):\n s.interpolate(method=method)\n\n @td.skip_if_no_scipy\n @pytest.mark.parametrize(\"order\", [-1, -1.0, 0, 0.0, np.nan])\n def test_interpolate_spline_invalid_order(self, order):\n s = Series([0, 1, np.nan, 3])\n msg = \"order needs to be specified and greater than 0\"\n with pytest.raises(ValueError, match=msg):\n s.interpolate(method=\"spline\", order=order)\n\n @td.skip_if_no_scipy\n def test_spline(self):\n s = Series([1, 2, np.nan, 4, 5, np.nan, 7])\n result = s.interpolate(method=\"spline\", order=1)\n expected = Series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0])\n tm.assert_series_equal(result, expected)\n\n @td.skip_if_no_scipy\n def test_spline_extrapolate(self):\n s = Series([1, 2, 3, 4, np.nan, 6, np.nan])\n result3 = s.interpolate(method=\"spline\", order=1, ext=3)\n expected3 = Series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 6.0])\n tm.assert_series_equal(result3, expected3)\n\n result1 = s.interpolate(method=\"spline\", order=1, ext=0)\n expected1 = Series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0])\n tm.assert_series_equal(result1, expected1)\n\n @td.skip_if_no_scipy\n def test_spline_smooth(self):\n s = Series([1, 2, np.nan, 4, 5.1, np.nan, 7])\n assert (\n s.interpolate(method=\"spline\", order=3, s=0)[5]\n != s.interpolate(method=\"spline\", order=3)[5]\n )\n\n @td.skip_if_no_scipy\n def test_spline_interpolation(self):\n s = Series(np.arange(10) ** 2)\n s[np.random.randint(0, 9, 3)] = np.nan\n result1 = s.interpolate(method=\"spline\", order=1)\n expected1 = s.interpolate(method=\"spline\", order=1)\n tm.assert_series_equal(result1, expected1)\n\n def test_interp_timedelta64(self):\n # GH 6424\n df = Series([1, np.nan, 3], index=pd.to_timedelta([1, 2, 3]))\n result = df.interpolate(method=\"time\")\n expected = Series([1.0, 2.0, 3.0], index=pd.to_timedelta([1, 2, 3]))\n tm.assert_series_equal(result, expected)\n\n # test for non uniform spacing\n df = Series([1, np.nan, 3], index=pd.to_timedelta([1, 2, 4]))\n result = df.interpolate(method=\"time\")\n expected = Series([1.0, 1.666667, 3.0], index=pd.to_timedelta([1, 2, 4]))\n tm.assert_series_equal(result, expected)\n\n def test_series_interpolate_method_values(self):\n # GH#1646\n rng = date_range(\"1/1/2000\", \"1/20/2000\", freq=\"D\")\n ts = Series(np.random.randn(len(rng)), index=rng)\n\n ts[::2] = np.nan\n\n result = ts.interpolate(method=\"values\")\n exp = ts.interpolate()\n tm.assert_series_equal(result, exp)\n\n def test_series_interpolate_intraday(self):\n # #1698\n index = date_range(\"1/1/2012\", periods=4, freq=\"12D\")\n ts = Series([0, 12, 24, 36], index)\n new_index = index.append(index + pd.DateOffset(days=1)).sort_values()\n\n exp = ts.reindex(new_index).interpolate(method=\"time\")\n\n index = date_range(\"1/1/2012\", periods=4, freq=\"12H\")\n ts = Series([0, 12, 24, 36], index)\n new_index = index.append(index + pd.DateOffset(hours=1)).sort_values()\n result = ts.reindex(new_index).interpolate(method=\"time\")\n\n tm.assert_numpy_array_equal(result.values, exp.values)\n\n @pytest.mark.parametrize(\n \"ind\",\n [\n [\"a\", \"b\", \"c\", \"d\"],\n pd.period_range(start=\"2019-01-01\", periods=4),\n pd.interval_range(start=0, end=4),\n ],\n )\n def test_interp_non_timedelta_index(self, interp_methods_ind, ind):\n # gh 21662\n df = pd.DataFrame([0, 1, np.nan, 3], index=ind)\n\n method, kwargs = interp_methods_ind\n if method == \"pchip\":\n pytest.importorskip(\"scipy\")\n\n if method == \"linear\":\n result = df[0].interpolate(**kwargs)\n expected = Series([0.0, 1.0, 2.0, 3.0], name=0, index=ind)\n tm.assert_series_equal(result, expected)\n else:\n expected_error = (\n \"Index column must be numeric or datetime type when \"\n f\"using {method} method other than linear. \"\n \"Try setting a numeric or datetime index column before \"\n \"interpolating.\"\n )\n with pytest.raises(ValueError, match=expected_error):\n df[0].interpolate(method=method, **kwargs)\n\n @td.skip_if_no_scipy\n def test_interpolate_timedelta_index(self, request, interp_methods_ind):\n \"\"\"\n Tests for non numerical index types - object, period, timedelta\n Note that all methods except time, index, nearest and values\n are tested here.\n \"\"\"\n # gh 21662\n ind = pd.timedelta_range(start=1, periods=4)\n df = pd.DataFrame([0, 1, np.nan, 3], index=ind)\n\n method, kwargs = interp_methods_ind\n import scipy\n\n if method in {\"cubic\", \"zero\"} or (\n method == \"barycentric\" and Version(scipy.__version__) < Version(\"1.5.0\")\n ):\n request.node.add_marker(\n pytest.mark.xfail(\n reason=f\"{method} interpolation is not supported for TimedeltaIndex\"\n )\n )\n result = df[0].interpolate(method=method, **kwargs)\n expected = Series([0.0, 1.0, 2.0, 3.0], name=0, index=ind)\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"ascending, expected_values\",\n [(True, [1, 2, 3, 9, 10]), (False, [10, 9, 3, 2, 1])],\n )\n def test_interpolate_unsorted_index(self, ascending, expected_values):\n # GH 21037\n ts = Series(data=[10, 9, np.nan, 2, 1], index=[10, 9, 3, 2, 1])\n result = ts.sort_index(ascending=ascending).interpolate(method=\"index\")\n expected = Series(data=expected_values, index=expected_values, dtype=float)\n tm.assert_series_equal(result, expected)\n\n def test_interpolate_pos_args_deprecation(self):\n # https://github.com/pandas-dev/pandas/issues/41485\n ser = Series([1, 2, 3])\n msg = (\n r\"In a future version of pandas all arguments of Series.interpolate except \"\n r\"for the argument 'method' will be keyword-only\"\n )\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = ser.interpolate(\"pad\", 0)\n expected = Series([1, 2, 3])\n tm.assert_series_equal(result, expected)\n", "from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom pandas.core.dtypes.common import (\n is_integer,\n is_list_like,\n)\nfrom pandas.core.dtypes.generic import (\n ABCDataFrame,\n ABCIndex,\n)\nfrom pandas.core.dtypes.missing import (\n isna,\n remove_na_arraylike,\n)\n\nfrom pandas.core.frame import DataFrame\n\nfrom pandas.io.formats.printing import pprint_thing\nfrom pandas.plotting._matplotlib.core import (\n LinePlot,\n MPLPlot,\n)\nfrom pandas.plotting._matplotlib.groupby import (\n create_iter_data_given_by,\n reformat_hist_y_given_by,\n)\nfrom pandas.plotting._matplotlib.tools import (\n create_subplots,\n flatten_axes,\n maybe_adjust_figure,\n set_ticks_props,\n)\n\nif TYPE_CHECKING:\n from matplotlib.axes import Axes\n\n\nclass HistPlot(LinePlot):\n _kind = \"hist\"\n\n def __init__(self, data, bins=10, bottom=0, **kwargs):\n self.bins = bins # use mpl default\n self.bottom = bottom\n # Do not call LinePlot.__init__ which may fill nan\n MPLPlot.__init__(self, data, **kwargs)\n\n def _args_adjust(self):\n\n # calculate bin number separately in different subplots\n # where subplots are created based on by argument\n if is_integer(self.bins):\n if self.by is not None:\n grouped = self.data.groupby(self.by)[self.columns]\n self.bins = [self._calculate_bins(group) for key, group in grouped]\n else:\n self.bins = self._calculate_bins(self.data)\n\n if is_list_like(self.bottom):\n self.bottom = np.array(self.bottom)\n\n def _calculate_bins(self, data: DataFrame) -> np.ndarray:\n \"\"\"Calculate bins given data\"\"\"\n values = data._convert(datetime=True)._get_numeric_data()\n values = np.ravel(values)\n values = values[~isna(values)]\n\n hist, bins = np.histogram(\n values, bins=self.bins, range=self.kwds.get(\"range\", None)\n )\n return bins\n\n @classmethod\n def _plot(\n cls,\n ax,\n y,\n style=None,\n bins=None,\n bottom=0,\n column_num=0,\n stacking_id=None,\n **kwds,\n ):\n if column_num == 0:\n cls._initialize_stacker(ax, stacking_id, len(bins) - 1)\n\n base = np.zeros(len(bins) - 1)\n bottom = bottom + cls._get_stacked_values(ax, stacking_id, base, kwds[\"label\"])\n # ignore style\n n, bins, patches = ax.hist(y, bins=bins, bottom=bottom, **kwds)\n cls._update_stacker(ax, stacking_id, n)\n return patches\n\n def _make_plot(self):\n colors = self._get_colors()\n stacking_id = self._get_stacking_id()\n\n # Re-create iterated data if `by` is assigned by users\n data = (\n create_iter_data_given_by(self.data, self._kind)\n if self.by is not None\n else self.data\n )\n\n for i, (label, y) in enumerate(self._iter_data(data=data)):\n ax = self._get_ax(i)\n\n kwds = self.kwds.copy()\n\n label = pprint_thing(label)\n label = self._mark_right_label(label, index=i)\n kwds[\"label\"] = label\n\n style, kwds = self._apply_style_colors(colors, kwds, i, label)\n if style is not None:\n kwds[\"style\"] = style\n\n kwds = self._make_plot_keywords(kwds, y)\n\n # the bins is multi-dimension array now and each plot need only 1-d and\n # when by is applied, label should be columns that are grouped\n if self.by is not None:\n kwds[\"bins\"] = kwds[\"bins\"][i]\n kwds[\"label\"] = self.columns\n kwds.pop(\"color\")\n\n y = reformat_hist_y_given_by(y, self.by)\n\n # We allow weights to be a multi-dimensional array, e.g. a (10, 2) array,\n # and each sub-array (10,) will be called in each iteration. If users only\n # provide 1D array, we assume the same weights is used for all iterations\n weights = kwds.get(\"weights\", None)\n if weights is not None and np.ndim(weights) != 1:\n kwds[\"weights\"] = weights[:, i]\n\n artists = self._plot(ax, y, column_num=i, stacking_id=stacking_id, **kwds)\n\n # when by is applied, show title for subplots to know which group it is\n if self.by is not None:\n ax.set_title(pprint_thing(label))\n\n self._append_legend_handles_labels(artists[0], label)\n\n def _make_plot_keywords(self, kwds, y):\n \"\"\"merge BoxPlot/KdePlot properties to passed kwds\"\"\"\n # y is required for KdePlot\n kwds[\"bottom\"] = self.bottom\n kwds[\"bins\"] = self.bins\n return kwds\n\n def _post_plot_logic(self, ax: Axes, data):\n if self.orientation == \"horizontal\":\n ax.set_xlabel(\"Frequency\")\n else:\n ax.set_ylabel(\"Frequency\")\n\n @property\n def orientation(self):\n if self.kwds.get(\"orientation\", None) == \"horizontal\":\n return \"horizontal\"\n else:\n return \"vertical\"\n\n\nclass KdePlot(HistPlot):\n _kind = \"kde\"\n orientation = \"vertical\"\n\n def __init__(self, data, bw_method=None, ind=None, **kwargs):\n MPLPlot.__init__(self, data, **kwargs)\n self.bw_method = bw_method\n self.ind = ind\n\n def _args_adjust(self):\n pass\n\n def _get_ind(self, y):\n if self.ind is None:\n # np.nanmax() and np.nanmin() ignores the missing values\n sample_range = np.nanmax(y) - np.nanmin(y)\n ind = np.linspace(\n np.nanmin(y) - 0.5 * sample_range,\n np.nanmax(y) + 0.5 * sample_range,\n 1000,\n )\n elif is_integer(self.ind):\n sample_range = np.nanmax(y) - np.nanmin(y)\n ind = np.linspace(\n np.nanmin(y) - 0.5 * sample_range,\n np.nanmax(y) + 0.5 * sample_range,\n self.ind,\n )\n else:\n ind = self.ind\n return ind\n\n @classmethod\n def _plot(\n cls,\n ax,\n y,\n style=None,\n bw_method=None,\n ind=None,\n column_num=None,\n stacking_id=None,\n **kwds,\n ):\n from scipy.stats import gaussian_kde\n\n y = remove_na_arraylike(y)\n gkde = gaussian_kde(y, bw_method=bw_method)\n\n y = gkde.evaluate(ind)\n lines = MPLPlot._plot(ax, ind, y, style=style, **kwds)\n return lines\n\n def _make_plot_keywords(self, kwds, y):\n kwds[\"bw_method\"] = self.bw_method\n kwds[\"ind\"] = self._get_ind(y)\n return kwds\n\n def _post_plot_logic(self, ax, data):\n ax.set_ylabel(\"Density\")\n\n\ndef _grouped_plot(\n plotf,\n data,\n column=None,\n by=None,\n numeric_only=True,\n figsize=None,\n sharex=True,\n sharey=True,\n layout=None,\n rot=0,\n ax=None,\n **kwargs,\n):\n\n if figsize == \"default\":\n # allowed to specify mpl default with 'default'\n raise ValueError(\n \"figsize='default' is no longer supported. \"\n \"Specify figure size by tuple instead\"\n )\n\n grouped = data.groupby(by)\n if column is not None:\n grouped = grouped[column]\n\n naxes = len(grouped)\n fig, axes = create_subplots(\n naxes=naxes, figsize=figsize, sharex=sharex, sharey=sharey, ax=ax, layout=layout\n )\n\n _axes = flatten_axes(axes)\n\n for i, (key, group) in enumerate(grouped):\n ax = _axes[i]\n if numeric_only and isinstance(group, ABCDataFrame):\n group = group._get_numeric_data()\n plotf(group, ax, **kwargs)\n ax.set_title(pprint_thing(key))\n\n return fig, axes\n\n\ndef _grouped_hist(\n data,\n column=None,\n by=None,\n ax=None,\n bins=50,\n figsize=None,\n layout=None,\n sharex=False,\n sharey=False,\n rot=90,\n grid=True,\n xlabelsize=None,\n xrot=None,\n ylabelsize=None,\n yrot=None,\n legend=False,\n **kwargs,\n):\n \"\"\"\n Grouped histogram\n\n Parameters\n ----------\n data : Series/DataFrame\n column : object, optional\n by : object, optional\n ax : axes, optional\n bins : int, default 50\n figsize : tuple, optional\n layout : optional\n sharex : bool, default False\n sharey : bool, default False\n rot : int, default 90\n grid : bool, default True\n legend: : bool, default False\n kwargs : dict, keyword arguments passed to matplotlib.Axes.hist\n\n Returns\n -------\n collection of Matplotlib Axes\n \"\"\"\n if legend:\n assert \"label\" not in kwargs\n if data.ndim == 1:\n kwargs[\"label\"] = data.name\n elif column is None:\n kwargs[\"label\"] = data.columns\n else:\n kwargs[\"label\"] = column\n\n def plot_group(group, ax):\n ax.hist(group.dropna().values, bins=bins, **kwargs)\n if legend:\n ax.legend()\n\n if xrot is None:\n xrot = rot\n\n fig, axes = _grouped_plot(\n plot_group,\n data,\n column=column,\n by=by,\n sharex=sharex,\n sharey=sharey,\n ax=ax,\n figsize=figsize,\n layout=layout,\n rot=rot,\n )\n\n set_ticks_props(\n axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot\n )\n\n maybe_adjust_figure(\n fig, bottom=0.15, top=0.9, left=0.1, right=0.9, hspace=0.5, wspace=0.3\n )\n return axes\n\n\ndef hist_series(\n self,\n by=None,\n ax=None,\n grid=True,\n xlabelsize=None,\n xrot=None,\n ylabelsize=None,\n yrot=None,\n figsize=None,\n bins=10,\n legend: bool = False,\n **kwds,\n):\n import matplotlib.pyplot as plt\n\n if legend and \"label\" in kwds:\n raise ValueError(\"Cannot use both legend and label\")\n\n if by is None:\n if kwds.get(\"layout\", None) is not None:\n raise ValueError(\"The 'layout' keyword is not supported when 'by' is None\")\n # hack until the plotting interface is a bit more unified\n fig = kwds.pop(\n \"figure\", plt.gcf() if plt.get_fignums() else plt.figure(figsize=figsize)\n )\n if figsize is not None and tuple(figsize) != tuple(fig.get_size_inches()):\n fig.set_size_inches(*figsize, forward=True)\n if ax is None:\n ax = fig.gca()\n elif ax.get_figure() != fig:\n raise AssertionError(\"passed axis not bound to passed figure\")\n values = self.dropna().values\n if legend:\n kwds[\"label\"] = self.name\n ax.hist(values, bins=bins, **kwds)\n if legend:\n ax.legend()\n ax.grid(grid)\n axes = np.array([ax])\n\n set_ticks_props(\n axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot\n )\n\n else:\n if \"figure\" in kwds:\n raise ValueError(\n \"Cannot pass 'figure' when using the \"\n \"'by' argument, since a new 'Figure' instance will be created\"\n )\n axes = _grouped_hist(\n self,\n by=by,\n ax=ax,\n grid=grid,\n figsize=figsize,\n bins=bins,\n xlabelsize=xlabelsize,\n xrot=xrot,\n ylabelsize=ylabelsize,\n yrot=yrot,\n legend=legend,\n **kwds,\n )\n\n if hasattr(axes, \"ndim\"):\n if axes.ndim == 1 and len(axes) == 1:\n return axes[0]\n return axes\n\n\ndef hist_frame(\n data,\n column=None,\n by=None,\n grid=True,\n xlabelsize=None,\n xrot=None,\n ylabelsize=None,\n yrot=None,\n ax=None,\n sharex=False,\n sharey=False,\n figsize=None,\n layout=None,\n bins=10,\n legend: bool = False,\n **kwds,\n):\n if legend and \"label\" in kwds:\n raise ValueError(\"Cannot use both legend and label\")\n if by is not None:\n axes = _grouped_hist(\n data,\n column=column,\n by=by,\n ax=ax,\n grid=grid,\n figsize=figsize,\n sharex=sharex,\n sharey=sharey,\n layout=layout,\n bins=bins,\n xlabelsize=xlabelsize,\n xrot=xrot,\n ylabelsize=ylabelsize,\n yrot=yrot,\n legend=legend,\n **kwds,\n )\n return axes\n\n if column is not None:\n if not isinstance(column, (list, np.ndarray, ABCIndex)):\n column = [column]\n data = data[column]\n # GH32590\n data = data.select_dtypes(\n include=(np.number, \"datetime64\", \"datetimetz\"), exclude=\"timedelta\"\n )\n naxes = len(data.columns)\n\n if naxes == 0:\n raise ValueError(\n \"hist method requires numerical or datetime columns, nothing to plot.\"\n )\n\n fig, axes = create_subplots(\n naxes=naxes,\n ax=ax,\n squeeze=False,\n sharex=sharex,\n sharey=sharey,\n figsize=figsize,\n layout=layout,\n )\n _axes = flatten_axes(axes)\n\n can_set_label = \"label\" not in kwds\n\n for i, col in enumerate(data.columns):\n ax = _axes[i]\n if legend and can_set_label:\n kwds[\"label\"] = col\n ax.hist(data[col].dropna().values, bins=bins, **kwds)\n ax.set_title(col)\n ax.grid(grid)\n if legend:\n ax.legend()\n\n set_ticks_props(\n axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot\n )\n maybe_adjust_figure(fig, wspace=0.3, hspace=0.3)\n\n return axes\n", "import numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nfrom pandas import DataFrame\nimport pandas._testing as tm\n\n\nclass TestCopy:\n @pytest.mark.parametrize(\"attr\", [\"index\", \"columns\"])\n def test_copy_index_name_checking(self, float_frame, attr):\n # don't want to be able to modify the index stored elsewhere after\n # making a copy\n ind = getattr(float_frame, attr)\n ind.name = None\n cp = float_frame.copy()\n getattr(cp, attr).name = \"foo\"\n assert getattr(float_frame, attr).name is None\n\n def test_copy_cache(self):\n # GH#31784 _item_cache not cleared on copy causes incorrect reads after updates\n df = DataFrame({\"a\": [1]})\n\n df[\"x\"] = [0]\n df[\"a\"]\n\n df.copy()\n\n df[\"a\"].values[0] = -1\n\n tm.assert_frame_equal(df, DataFrame({\"a\": [-1], \"x\": [0]}))\n\n df[\"y\"] = [0]\n\n assert df[\"a\"].values[0] == -1\n tm.assert_frame_equal(df, DataFrame({\"a\": [-1], \"x\": [0], \"y\": [0]}))\n\n def test_copy(self, float_frame, float_string_frame):\n cop = float_frame.copy()\n cop[\"E\"] = cop[\"A\"]\n assert \"E\" not in float_frame\n\n # copy objects\n copy = float_string_frame.copy()\n assert copy._mgr is not float_string_frame._mgr\n\n @td.skip_array_manager_invalid_test\n def test_copy_consolidates(self):\n # GH#42477\n df = DataFrame(\n {\n \"a\": np.random.randint(0, 100, size=55),\n \"b\": np.random.randint(0, 100, size=55),\n }\n )\n\n for i in range(0, 10):\n df.loc[:, f\"n_{i}\"] = np.random.randint(0, 100, size=55)\n\n assert len(df._mgr.blocks) == 11\n result = df.copy()\n assert len(result._mgr.blocks) == 1\n", "import sys\nimport warnings\nimport functools\nimport operator\n\nimport pytest\n\nimport numpy as np\nfrom numpy.core._multiarray_tests import array_indexing\nfrom itertools import product\nfrom numpy.testing import (\n assert_, assert_equal, assert_raises, assert_raises_regex,\n assert_array_equal, assert_warns, HAS_REFCOUNT,\n )\n\n\nclass TestIndexing:\n def test_index_no_floats(self):\n a = np.array([[[5]]])\n\n assert_raises(IndexError, lambda: a[0.0])\n assert_raises(IndexError, lambda: a[0, 0.0])\n assert_raises(IndexError, lambda: a[0.0, 0])\n assert_raises(IndexError, lambda: a[0.0,:])\n assert_raises(IndexError, lambda: a[:, 0.0])\n assert_raises(IndexError, lambda: a[:, 0.0,:])\n assert_raises(IndexError, lambda: a[0.0,:,:])\n assert_raises(IndexError, lambda: a[0, 0, 0.0])\n assert_raises(IndexError, lambda: a[0.0, 0, 0])\n assert_raises(IndexError, lambda: a[0, 0.0, 0])\n assert_raises(IndexError, lambda: a[-1.4])\n assert_raises(IndexError, lambda: a[0, -1.4])\n assert_raises(IndexError, lambda: a[-1.4, 0])\n assert_raises(IndexError, lambda: a[-1.4,:])\n assert_raises(IndexError, lambda: a[:, -1.4])\n assert_raises(IndexError, lambda: a[:, -1.4,:])\n assert_raises(IndexError, lambda: a[-1.4,:,:])\n assert_raises(IndexError, lambda: a[0, 0, -1.4])\n assert_raises(IndexError, lambda: a[-1.4, 0, 0])\n assert_raises(IndexError, lambda: a[0, -1.4, 0])\n assert_raises(IndexError, lambda: a[0.0:, 0.0])\n assert_raises(IndexError, lambda: a[0.0:, 0.0,:])\n\n def test_slicing_no_floats(self):\n a = np.array([[5]])\n\n # start as float.\n assert_raises(TypeError, lambda: a[0.0:])\n assert_raises(TypeError, lambda: a[0:, 0.0:2])\n assert_raises(TypeError, lambda: a[0.0::2, :0])\n assert_raises(TypeError, lambda: a[0.0:1:2,:])\n assert_raises(TypeError, lambda: a[:, 0.0:])\n # stop as float.\n assert_raises(TypeError, lambda: a[:0.0])\n assert_raises(TypeError, lambda: a[:0, 1:2.0])\n assert_raises(TypeError, lambda: a[:0.0:2, :0])\n assert_raises(TypeError, lambda: a[:0.0,:])\n assert_raises(TypeError, lambda: a[:, 0:4.0:2])\n # step as float.\n assert_raises(TypeError, lambda: a[::1.0])\n assert_raises(TypeError, lambda: a[0:, :2:2.0])\n assert_raises(TypeError, lambda: a[1::4.0, :0])\n assert_raises(TypeError, lambda: a[::5.0,:])\n assert_raises(TypeError, lambda: a[:, 0:4:2.0])\n # mixed.\n assert_raises(TypeError, lambda: a[1.0:2:2.0])\n assert_raises(TypeError, lambda: a[1.0::2.0])\n assert_raises(TypeError, lambda: a[0:, :2.0:2.0])\n assert_raises(TypeError, lambda: a[1.0:1:4.0, :0])\n assert_raises(TypeError, lambda: a[1.0:5.0:5.0,:])\n assert_raises(TypeError, lambda: a[:, 0.4:4.0:2.0])\n # should still get the DeprecationWarning if step = 0.\n assert_raises(TypeError, lambda: a[::0.0])\n\n def test_index_no_array_to_index(self):\n # No non-scalar arrays.\n a = np.array([[[1]]])\n\n assert_raises(TypeError, lambda: a[a:a:a])\n\n def test_none_index(self):\n # `None` index adds newaxis\n a = np.array([1, 2, 3])\n assert_equal(a[None], a[np.newaxis])\n assert_equal(a[None].ndim, a.ndim + 1)\n\n def test_empty_tuple_index(self):\n # Empty tuple index creates a view\n a = np.array([1, 2, 3])\n assert_equal(a[()], a)\n assert_(a[()].base is a)\n a = np.array(0)\n assert_(isinstance(a[()], np.int_))\n\n def test_void_scalar_empty_tuple(self):\n s = np.zeros((), dtype='V4')\n assert_equal(s[()].dtype, s.dtype)\n assert_equal(s[()], s)\n assert_equal(type(s[...]), np.ndarray)\n\n def test_same_kind_index_casting(self):\n # Indexes should be cast with same-kind and not safe, even if that\n # is somewhat unsafe. So test various different code paths.\n index = np.arange(5)\n u_index = index.astype(np.uintp)\n arr = np.arange(10)\n\n assert_array_equal(arr[index], arr[u_index])\n arr[u_index] = np.arange(5)\n assert_array_equal(arr, np.arange(10))\n\n arr = np.arange(10).reshape(5, 2)\n assert_array_equal(arr[index], arr[u_index])\n\n arr[u_index] = np.arange(5)[:,None]\n assert_array_equal(arr, np.arange(5)[:,None].repeat(2, axis=1))\n\n arr = np.arange(25).reshape(5, 5)\n assert_array_equal(arr[u_index, u_index], arr[index, index])\n\n def test_empty_fancy_index(self):\n # Empty list index creates an empty array\n # with the same dtype (but with weird shape)\n a = np.array([1, 2, 3])\n assert_equal(a[[]], [])\n assert_equal(a[[]].dtype, a.dtype)\n\n b = np.array([], dtype=np.intp)\n assert_equal(a[[]], [])\n assert_equal(a[[]].dtype, a.dtype)\n\n b = np.array([])\n assert_raises(IndexError, a.__getitem__, b)\n\n def test_ellipsis_index(self):\n a = np.array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n assert_(a[...] is not a)\n assert_equal(a[...], a)\n # `a[...]` was `a` in numpy <1.9.\n assert_(a[...].base is a)\n\n # Slicing with ellipsis can skip an\n # arbitrary number of dimensions\n assert_equal(a[0, ...], a[0])\n assert_equal(a[0, ...], a[0,:])\n assert_equal(a[..., 0], a[:, 0])\n\n # Slicing with ellipsis always results\n # in an array, not a scalar\n assert_equal(a[0, ..., 1], np.array(2))\n\n # Assignment with `(Ellipsis,)` on 0-d arrays\n b = np.array(1)\n b[(Ellipsis,)] = 2\n assert_equal(b, 2)\n\n def test_single_int_index(self):\n # Single integer index selects one row\n a = np.array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n\n assert_equal(a[0], [1, 2, 3])\n assert_equal(a[-1], [7, 8, 9])\n\n # Index out of bounds produces IndexError\n assert_raises(IndexError, a.__getitem__, 1 << 30)\n # Index overflow produces IndexError\n assert_raises(IndexError, a.__getitem__, 1 << 64)\n\n def test_single_bool_index(self):\n # Single boolean index\n a = np.array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n\n assert_equal(a[np.array(True)], a[None])\n assert_equal(a[np.array(False)], a[None][0:0])\n\n def test_boolean_shape_mismatch(self):\n arr = np.ones((5, 4, 3))\n\n index = np.array([True])\n assert_raises(IndexError, arr.__getitem__, index)\n\n index = np.array([False] * 6)\n assert_raises(IndexError, arr.__getitem__, index)\n\n index = np.zeros((4, 4), dtype=bool)\n assert_raises(IndexError, arr.__getitem__, index)\n\n assert_raises(IndexError, arr.__getitem__, (slice(None), index))\n\n def test_boolean_indexing_onedim(self):\n # Indexing a 2-dimensional array with\n # boolean array of length one\n a = np.array([[ 0., 0., 0.]])\n b = np.array([ True], dtype=bool)\n assert_equal(a[b], a)\n # boolean assignment\n a[b] = 1.\n assert_equal(a, [[1., 1., 1.]])\n\n def test_boolean_assignment_value_mismatch(self):\n # A boolean assignment should fail when the shape of the values\n # cannot be broadcast to the subscription. (see also gh-3458)\n a = np.arange(4)\n\n def f(a, v):\n a[a > -1] = v\n\n assert_raises(ValueError, f, a, [])\n assert_raises(ValueError, f, a, [1, 2, 3])\n assert_raises(ValueError, f, a[:1], [1, 2, 3])\n\n def test_boolean_assignment_needs_api(self):\n # See also gh-7666\n # This caused a segfault on Python 2 due to the GIL not being\n # held when the iterator does not need it, but the transfer function\n # does\n arr = np.zeros(1000)\n indx = np.zeros(1000, dtype=bool)\n indx[:100] = True\n arr[indx] = np.ones(100, dtype=object)\n\n expected = np.zeros(1000)\n expected[:100] = 1\n assert_array_equal(arr, expected)\n\n def test_boolean_indexing_twodim(self):\n # Indexing a 2-dimensional array with\n # 2-dimensional boolean array\n a = np.array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n b = np.array([[ True, False, True],\n [False, True, False],\n [ True, False, True]])\n assert_equal(a[b], [1, 3, 5, 7, 9])\n assert_equal(a[b[1]], [[4, 5, 6]])\n assert_equal(a[b[0]], a[b[2]])\n\n # boolean assignment\n a[b] = 0\n assert_equal(a, [[0, 2, 0],\n [4, 0, 6],\n [0, 8, 0]])\n\n def test_boolean_indexing_list(self):\n # Regression test for #13715. It's a use-after-free bug which the\n # test won't directly catch, but it will show up in valgrind.\n a = np.array([1, 2, 3])\n b = [True, False, True]\n # Two variants of the test because the first takes a fast path\n assert_equal(a[b], [1, 3])\n assert_equal(a[None, b], [[1, 3]])\n\n def test_reverse_strides_and_subspace_bufferinit(self):\n # This tests that the strides are not reversed for simple and\n # subspace fancy indexing.\n a = np.ones(5)\n b = np.zeros(5, dtype=np.intp)[::-1]\n c = np.arange(5)[::-1]\n\n a[b] = c\n # If the strides are not reversed, the 0 in the arange comes last.\n assert_equal(a[0], 0)\n\n # This also tests that the subspace buffer is initialized:\n a = np.ones((5, 2))\n c = np.arange(10).reshape(5, 2)[::-1]\n a[b, :] = c\n assert_equal(a[0], [0, 1])\n\n def test_reversed_strides_result_allocation(self):\n # Test a bug when calculating the output strides for a result array\n # when the subspace size was 1 (and test other cases as well)\n a = np.arange(10)[:, None]\n i = np.arange(10)[::-1]\n assert_array_equal(a[i], a[i.copy('C')])\n\n a = np.arange(20).reshape(-1, 2)\n\n def test_uncontiguous_subspace_assignment(self):\n # During development there was a bug activating a skip logic\n # based on ndim instead of size.\n a = np.full((3, 4, 2), -1)\n b = np.full((3, 4, 2), -1)\n\n a[[0, 1]] = np.arange(2 * 4 * 2).reshape(2, 4, 2).T\n b[[0, 1]] = np.arange(2 * 4 * 2).reshape(2, 4, 2).T.copy()\n\n assert_equal(a, b)\n\n def test_too_many_fancy_indices_special_case(self):\n # Just documents behaviour, this is a small limitation.\n a = np.ones((1,) * 32) # 32 is NPY_MAXDIMS\n assert_raises(IndexError, a.__getitem__, (np.array([0]),) * 32)\n\n def test_scalar_array_bool(self):\n # NumPy bools can be used as boolean index (python ones as of yet not)\n a = np.array(1)\n assert_equal(a[np.bool_(True)], a[np.array(True)])\n assert_equal(a[np.bool_(False)], a[np.array(False)])\n\n # After deprecating bools as integers:\n #a = np.array([0,1,2])\n #assert_equal(a[True, :], a[None, :])\n #assert_equal(a[:, True], a[:, None])\n #\n #assert_(not np.may_share_memory(a, a[True, :]))\n\n def test_everything_returns_views(self):\n # Before `...` would return a itself.\n a = np.arange(5)\n\n assert_(a is not a[()])\n assert_(a is not a[...])\n assert_(a is not a[:])\n\n def test_broaderrors_indexing(self):\n a = np.zeros((5, 5))\n assert_raises(IndexError, a.__getitem__, ([0, 1], [0, 1, 2]))\n assert_raises(IndexError, a.__setitem__, ([0, 1], [0, 1, 2]), 0)\n\n def test_trivial_fancy_out_of_bounds(self):\n a = np.zeros(5)\n ind = np.ones(20, dtype=np.intp)\n ind[-1] = 10\n assert_raises(IndexError, a.__getitem__, ind)\n assert_raises(IndexError, a.__setitem__, ind, 0)\n ind = np.ones(20, dtype=np.intp)\n ind[0] = 11\n assert_raises(IndexError, a.__getitem__, ind)\n assert_raises(IndexError, a.__setitem__, ind, 0)\n\n def test_trivial_fancy_not_possible(self):\n # Test that the fast path for trivial assignment is not incorrectly\n # used when the index is not contiguous or 1D, see also gh-11467.\n a = np.arange(6)\n idx = np.arange(6, dtype=np.intp).reshape(2, 1, 3)[:, :, 0]\n assert_array_equal(a[idx], idx)\n\n # this case must not go into the fast path, note that idx is\n # a non-contiuguous none 1D array here.\n a[idx] = -1\n res = np.arange(6)\n res[0] = -1\n res[3] = -1\n assert_array_equal(a, res)\n\n def test_nonbaseclass_values(self):\n class SubClass(np.ndarray):\n def __array_finalize__(self, old):\n # Have array finalize do funny things\n self.fill(99)\n\n a = np.zeros((5, 5))\n s = a.copy().view(type=SubClass)\n s.fill(1)\n\n a[[0, 1, 2, 3, 4], :] = s\n assert_((a == 1).all())\n\n # Subspace is last, so transposing might want to finalize\n a[:, [0, 1, 2, 3, 4]] = s\n assert_((a == 1).all())\n\n a.fill(0)\n a[...] = s\n assert_((a == 1).all())\n\n def test_array_like_values(self):\n # Similar to the above test, but use a memoryview instead\n a = np.zeros((5, 5))\n s = np.arange(25, dtype=np.float64).reshape(5, 5)\n\n a[[0, 1, 2, 3, 4], :] = memoryview(s)\n assert_array_equal(a, s)\n\n a[:, [0, 1, 2, 3, 4]] = memoryview(s)\n assert_array_equal(a, s)\n\n a[...] = memoryview(s)\n assert_array_equal(a, s)\n\n def test_subclass_writeable(self):\n d = np.rec.array([('NGC1001', 11), ('NGC1002', 1.), ('NGC1003', 1.)],\n dtype=[('target', 'S20'), ('V_mag', '>f4')])\n ind = np.array([False, True, True], dtype=bool)\n assert_(d[ind].flags.writeable)\n ind = np.array([0, 1])\n assert_(d[ind].flags.writeable)\n assert_(d[...].flags.writeable)\n assert_(d[0].flags.writeable)\n\n def test_memory_order(self):\n # This is not necessary to preserve. Memory layouts for\n # more complex indices are not as simple.\n a = np.arange(10)\n b = np.arange(10).reshape(5,2).T\n assert_(a[b].flags.f_contiguous)\n\n # Takes a different implementation branch:\n a = a.reshape(-1, 1)\n assert_(a[b, 0].flags.f_contiguous)\n\n def test_scalar_return_type(self):\n # Full scalar indices should return scalars and object\n # arrays should not call PyArray_Return on their items\n class Zero:\n # The most basic valid indexing\n def __index__(self):\n return 0\n\n z = Zero()\n\n class ArrayLike:\n # Simple array, should behave like the array\n def __array__(self):\n return np.array(0)\n\n a = np.zeros(())\n assert_(isinstance(a[()], np.float_))\n a = np.zeros(1)\n assert_(isinstance(a[z], np.float_))\n a = np.zeros((1, 1))\n assert_(isinstance(a[z, np.array(0)], np.float_))\n assert_(isinstance(a[z, ArrayLike()], np.float_))\n\n # And object arrays do not call it too often:\n b = np.array(0)\n a = np.array(0, dtype=object)\n a[()] = b\n assert_(isinstance(a[()], np.ndarray))\n a = np.array([b, None])\n assert_(isinstance(a[z], np.ndarray))\n a = np.array([[b, None]])\n assert_(isinstance(a[z, np.array(0)], np.ndarray))\n assert_(isinstance(a[z, ArrayLike()], np.ndarray))\n\n def test_small_regressions(self):\n # Reference count of intp for index checks\n a = np.array([0])\n if HAS_REFCOUNT:\n refcount = sys.getrefcount(np.dtype(np.intp))\n # item setting always checks indices in separate function:\n a[np.array([0], dtype=np.intp)] = 1\n a[np.array([0], dtype=np.uint8)] = 1\n assert_raises(IndexError, a.__setitem__,\n np.array([1], dtype=np.intp), 1)\n assert_raises(IndexError, a.__setitem__,\n np.array([1], dtype=np.uint8), 1)\n\n if HAS_REFCOUNT:\n assert_equal(sys.getrefcount(np.dtype(np.intp)), refcount)\n\n def test_unaligned(self):\n v = (np.zeros(64, dtype=np.int8) + ord('a'))[1:-7]\n d = v.view(np.dtype(\"S8\"))\n # unaligned source\n x = (np.zeros(16, dtype=np.int8) + ord('a'))[1:-7]\n x = x.view(np.dtype(\"S8\"))\n x[...] = np.array(\"b\" * 8, dtype=\"S\")\n b = np.arange(d.size)\n #trivial\n assert_equal(d[b], d)\n d[b] = x\n # nontrivial\n # unaligned index array\n b = np.zeros(d.size + 1).view(np.int8)[1:-(np.intp(0).itemsize - 1)]\n b = b.view(np.intp)[:d.size]\n b[...] = np.arange(d.size)\n assert_equal(d[b.astype(np.int16)], d)\n d[b.astype(np.int16)] = x\n # boolean\n d[b % 2 == 0]\n d[b % 2 == 0] = x[::2]\n\n def test_tuple_subclass(self):\n arr = np.ones((5, 5))\n\n # A tuple subclass should also be an nd-index\n class TupleSubclass(tuple):\n pass\n index = ([1], [1])\n index = TupleSubclass(index)\n assert_(arr[index].shape == (1,))\n # Unlike the non nd-index:\n assert_(arr[index,].shape != (1,))\n\n def test_broken_sequence_not_nd_index(self):\n # See gh-5063:\n # If we have an object which claims to be a sequence, but fails\n # on item getting, this should not be converted to an nd-index (tuple)\n # If this object happens to be a valid index otherwise, it should work\n # This object here is very dubious and probably bad though:\n class SequenceLike:\n def __index__(self):\n return 0\n\n def __len__(self):\n return 1\n\n def __getitem__(self, item):\n raise IndexError('Not possible')\n\n arr = np.arange(10)\n assert_array_equal(arr[SequenceLike()], arr[SequenceLike(),])\n\n # also test that field indexing does not segfault\n # for a similar reason, by indexing a structured array\n arr = np.zeros((1,), dtype=[('f1', 'i8'), ('f2', 'i8')])\n assert_array_equal(arr[SequenceLike()], arr[SequenceLike(),])\n\n def test_indexing_array_weird_strides(self):\n # See also gh-6221\n # the shapes used here come from the issue and create the correct\n # size for the iterator buffering size.\n x = np.ones(10)\n x2 = np.ones((10, 2))\n ind = np.arange(10)[:, None, None, None]\n ind = np.broadcast_to(ind, (10, 55, 4, 4))\n\n # single advanced index case\n assert_array_equal(x[ind], x[ind.copy()])\n # higher dimensional advanced index\n zind = np.zeros(4, dtype=np.intp)\n assert_array_equal(x2[ind, zind], x2[ind.copy(), zind])\n\n def test_indexing_array_negative_strides(self):\n # From gh-8264,\n # core dumps if negative strides are used in iteration\n arro = np.zeros((4, 4))\n arr = arro[::-1, ::-1]\n\n slices = (slice(None), [0, 1, 2, 3])\n arr[slices] = 10\n assert_array_equal(arr, 10.)\n\n def test_character_assignment(self):\n # This is an example a function going through CopyObject which\n # used to have an untested special path for scalars\n # (the character special dtype case, should be deprecated probably)\n arr = np.zeros((1, 5), dtype=\"c\")\n arr[0] = np.str_(\"asdfg\") # must assign as a sequence\n assert_array_equal(arr[0], np.array(\"asdfg\", dtype=\"c\"))\n assert arr[0, 1] == b\"s\" # make sure not all were set to \"a\" for both\n\n @pytest.mark.parametrize(\"index\",\n [True, False, np.array([0])])\n @pytest.mark.parametrize(\"num\", [32, 40])\n @pytest.mark.parametrize(\"original_ndim\", [1, 32])\n def test_too_many_advanced_indices(self, index, num, original_ndim):\n # These are limitations based on the number of arguments we can process.\n # For `num=32` (and all boolean cases), the result is actually define;\n # but the use of NpyIter (NPY_MAXARGS) limits it for technical reasons.\n arr = np.ones((1,) * original_ndim)\n with pytest.raises(IndexError):\n arr[(index,) * num]\n with pytest.raises(IndexError):\n arr[(index,) * num] = 1.\n\n def test_structured_advanced_indexing(self):\n # Test that copyswap(n) used by integer array indexing is threadsafe\n # for structured datatypes, see gh-15387. This test can behave randomly.\n from concurrent.futures import ThreadPoolExecutor\n\n # Create a deeply nested dtype to make a failure more likely:\n dt = np.dtype([(\"\", \"f8\")])\n dt = np.dtype([(\"\", dt)] * 2)\n dt = np.dtype([(\"\", dt)] * 2)\n # The array should be large enough to likely run into threading issues\n arr = np.random.uniform(size=(6000, 8)).view(dt)[:, 0]\n\n rng = np.random.default_rng()\n def func(arr):\n indx = rng.integers(0, len(arr), size=6000, dtype=np.intp)\n arr[indx]\n\n tpe = ThreadPoolExecutor(max_workers=8)\n futures = [tpe.submit(func, arr) for _ in range(10)]\n for f in futures:\n f.result()\n\n assert arr.dtype is dt\n\n\nclass TestFieldIndexing:\n def test_scalar_return_type(self):\n # Field access on an array should return an array, even if it\n # is 0-d.\n a = np.zeros((), [('a','f8')])\n assert_(isinstance(a['a'], np.ndarray))\n assert_(isinstance(a[['a']], np.ndarray))\n\n\nclass TestBroadcastedAssignments:\n def assign(self, a, ind, val):\n a[ind] = val\n return a\n\n def test_prepending_ones(self):\n a = np.zeros((3, 2))\n\n a[...] = np.ones((1, 3, 2))\n # Fancy with subspace with and without transpose\n a[[0, 1, 2], :] = np.ones((1, 3, 2))\n a[:, [0, 1]] = np.ones((1, 3, 2))\n # Fancy without subspace (with broadcasting)\n a[[[0], [1], [2]], [0, 1]] = np.ones((1, 3, 2))\n\n def test_prepend_not_one(self):\n assign = self.assign\n s_ = np.s_\n a = np.zeros(5)\n\n # Too large and not only ones.\n assert_raises(ValueError, assign, a, s_[...], np.ones((2, 1)))\n assert_raises(ValueError, assign, a, s_[[1, 2, 3],], np.ones((2, 1)))\n assert_raises(ValueError, assign, a, s_[[[1], [2]],], np.ones((2,2,1)))\n\n def test_simple_broadcasting_errors(self):\n assign = self.assign\n s_ = np.s_\n a = np.zeros((5, 1))\n\n assert_raises(ValueError, assign, a, s_[...], np.zeros((5, 2)))\n assert_raises(ValueError, assign, a, s_[...], np.zeros((5, 0)))\n assert_raises(ValueError, assign, a, s_[:, [0]], np.zeros((5, 2)))\n assert_raises(ValueError, assign, a, s_[:, [0]], np.zeros((5, 0)))\n assert_raises(ValueError, assign, a, s_[[0], :], np.zeros((2, 1)))\n\n @pytest.mark.parametrize(\"index\", [\n (..., [1, 2], slice(None)),\n ([0, 1], ..., 0),\n (..., [1, 2], [1, 2])])\n def test_broadcast_error_reports_correct_shape(self, index):\n values = np.zeros((100, 100)) # will never broadcast below \n\n arr = np.zeros((3, 4, 5, 6, 7))\n # We currently report without any spaces (could be changed)\n shape_str = str(arr[index].shape).replace(\" \", \"\")\n \n with pytest.raises(ValueError) as e:\n arr[index] = values\n\n assert str(e.value).endswith(shape_str)\n\n def test_index_is_larger(self):\n # Simple case of fancy index broadcasting of the index.\n a = np.zeros((5, 5))\n a[[[0], [1], [2]], [0, 1, 2]] = [2, 3, 4]\n\n assert_((a[:3, :3] == [2, 3, 4]).all())\n\n def test_broadcast_subspace(self):\n a = np.zeros((100, 100))\n v = np.arange(100)[:,None]\n b = np.arange(100)[::-1]\n a[b] = v\n assert_((a[::-1] == v).all())\n\n\nclass TestSubclasses:\n def test_basic(self):\n # Test that indexing in various ways produces SubClass instances,\n # and that the base is set up correctly: the original subclass\n # instance for views, and a new ndarray for advanced/boolean indexing\n # where a copy was made (latter a regression test for gh-11983).\n class SubClass(np.ndarray):\n pass\n\n a = np.arange(5)\n s = a.view(SubClass)\n s_slice = s[:3]\n assert_(type(s_slice) is SubClass)\n assert_(s_slice.base is s)\n assert_array_equal(s_slice, a[:3])\n\n s_fancy = s[[0, 1, 2]]\n assert_(type(s_fancy) is SubClass)\n assert_(s_fancy.base is not s)\n assert_(type(s_fancy.base) is np.ndarray)\n assert_array_equal(s_fancy, a[[0, 1, 2]])\n assert_array_equal(s_fancy.base, a[[0, 1, 2]])\n\n s_bool = s[s > 0]\n assert_(type(s_bool) is SubClass)\n assert_(s_bool.base is not s)\n assert_(type(s_bool.base) is np.ndarray)\n assert_array_equal(s_bool, a[a > 0])\n assert_array_equal(s_bool.base, a[a > 0])\n\n def test_fancy_on_read_only(self):\n # Test that fancy indexing on read-only SubClass does not make a\n # read-only copy (gh-14132)\n class SubClass(np.ndarray):\n pass\n\n a = np.arange(5)\n s = a.view(SubClass)\n s.flags.writeable = False\n s_fancy = s[[0, 1, 2]]\n assert_(s_fancy.flags.writeable)\n\n\n def test_finalize_gets_full_info(self):\n # Array finalize should be called on the filled array.\n class SubClass(np.ndarray):\n def __array_finalize__(self, old):\n self.finalize_status = np.array(self)\n self.old = old\n\n s = np.arange(10).view(SubClass)\n new_s = s[:3]\n assert_array_equal(new_s.finalize_status, new_s)\n assert_array_equal(new_s.old, s)\n\n new_s = s[[0,1,2,3]]\n assert_array_equal(new_s.finalize_status, new_s)\n assert_array_equal(new_s.old, s)\n\n new_s = s[s > 0]\n assert_array_equal(new_s.finalize_status, new_s)\n assert_array_equal(new_s.old, s)\n\n\nclass TestFancyIndexingCast:\n def test_boolean_index_cast_assign(self):\n # Setup the boolean index and float arrays.\n shape = (8, 63)\n bool_index = np.zeros(shape).astype(bool)\n bool_index[0, 1] = True\n zero_array = np.zeros(shape)\n\n # Assigning float is fine.\n zero_array[bool_index] = np.array([1])\n assert_equal(zero_array[0, 1], 1)\n\n # Fancy indexing works, although we get a cast warning.\n assert_warns(np.ComplexWarning,\n zero_array.__setitem__, ([0], [1]), np.array([2 + 1j]))\n assert_equal(zero_array[0, 1], 2) # No complex part\n\n # Cast complex to float, throwing away the imaginary portion.\n assert_warns(np.ComplexWarning,\n zero_array.__setitem__, bool_index, np.array([1j]))\n assert_equal(zero_array[0, 1], 0)\n\nclass TestFancyIndexingEquivalence:\n def test_object_assign(self):\n # Check that the field and object special case using copyto is active.\n # The right hand side cannot be converted to an array here.\n a = np.arange(5, dtype=object)\n b = a.copy()\n a[:3] = [1, (1,2), 3]\n b[[0, 1, 2]] = [1, (1,2), 3]\n assert_array_equal(a, b)\n\n # test same for subspace fancy indexing\n b = np.arange(5, dtype=object)[None, :]\n b[[0], :3] = [[1, (1,2), 3]]\n assert_array_equal(a, b[0])\n\n # Check that swapping of axes works.\n # There was a bug that made the later assignment throw a ValueError\n # do to an incorrectly transposed temporary right hand side (gh-5714)\n b = b.T\n b[:3, [0]] = [[1], [(1,2)], [3]]\n assert_array_equal(a, b[:, 0])\n\n # Another test for the memory order of the subspace\n arr = np.ones((3, 4, 5), dtype=object)\n # Equivalent slicing assignment for comparison\n cmp_arr = arr.copy()\n cmp_arr[:1, ...] = [[[1], [2], [3], [4]]]\n arr[[0], ...] = [[[1], [2], [3], [4]]]\n assert_array_equal(arr, cmp_arr)\n arr = arr.copy('F')\n arr[[0], ...] = [[[1], [2], [3], [4]]]\n assert_array_equal(arr, cmp_arr)\n\n def test_cast_equivalence(self):\n # Yes, normal slicing uses unsafe casting.\n a = np.arange(5)\n b = a.copy()\n\n a[:3] = np.array(['2', '-3', '-1'])\n b[[0, 2, 1]] = np.array(['2', '-1', '-3'])\n assert_array_equal(a, b)\n\n # test the same for subspace fancy indexing\n b = np.arange(5)[None, :]\n b[[0], :3] = np.array([['2', '-3', '-1']])\n assert_array_equal(a, b[0])\n\n\nclass TestMultiIndexingAutomated:\n \"\"\"\n These tests use code to mimic the C-Code indexing for selection.\n\n NOTE:\n\n * This still lacks tests for complex item setting.\n * If you change behavior of indexing, you might want to modify\n these tests to try more combinations.\n * Behavior was written to match numpy version 1.8. (though a\n first version matched 1.7.)\n * Only tuple indices are supported by the mimicking code.\n (and tested as of writing this)\n * Error types should match most of the time as long as there\n is only one error. For multiple errors, what gets raised\n will usually not be the same one. They are *not* tested.\n\n Update 2016-11-30: It is probably not worth maintaining this test\n indefinitely and it can be dropped if maintenance becomes a burden.\n\n \"\"\"\n\n def setup(self):\n self.a = np.arange(np.prod([3, 1, 5, 6])).reshape(3, 1, 5, 6)\n self.b = np.empty((3, 0, 5, 6))\n self.complex_indices = ['skip', Ellipsis,\n 0,\n # Boolean indices, up to 3-d for some special cases of eating up\n # dimensions, also need to test all False\n np.array([True, False, False]),\n np.array([[True, False], [False, True]]),\n np.array([[[False, False], [False, False]]]),\n # Some slices:\n slice(-5, 5, 2),\n slice(1, 1, 100),\n slice(4, -1, -2),\n slice(None, None, -3),\n # Some Fancy indexes:\n np.empty((0, 1, 1), dtype=np.intp), # empty and can be broadcast\n np.array([0, 1, -2]),\n np.array([[2], [0], [1]]),\n np.array([[0, -1], [0, 1]], dtype=np.dtype('intp').newbyteorder()),\n np.array([2, -1], dtype=np.int8),\n np.zeros([1]*31, dtype=int), # trigger too large array.\n np.array([0., 1.])] # invalid datatype\n # Some simpler indices that still cover a bit more\n self.simple_indices = [Ellipsis, None, -1, [1], np.array([True]),\n 'skip']\n # Very simple ones to fill the rest:\n self.fill_indices = [slice(None, None), 0]\n\n def _get_multi_index(self, arr, indices):\n \"\"\"Mimic multi dimensional indexing.\n\n Parameters\n ----------\n arr : ndarray\n Array to be indexed.\n indices : tuple of index objects\n\n Returns\n -------\n out : ndarray\n An array equivalent to the indexing operation (but always a copy).\n `arr[indices]` should be identical.\n no_copy : bool\n Whether the indexing operation requires a copy. If this is `True`,\n `np.may_share_memory(arr, arr[indices])` should be `True` (with\n some exceptions for scalars and possibly 0-d arrays).\n\n Notes\n -----\n While the function may mostly match the errors of normal indexing this\n is generally not the case.\n \"\"\"\n in_indices = list(indices)\n indices = []\n # if False, this is a fancy or boolean index\n no_copy = True\n # number of fancy/scalar indexes that are not consecutive\n num_fancy = 0\n # number of dimensions indexed by a \"fancy\" index\n fancy_dim = 0\n # NOTE: This is a funny twist (and probably OK to change).\n # The boolean array has illegal indexes, but this is\n # allowed if the broadcast fancy-indices are 0-sized.\n # This variable is to catch that case.\n error_unless_broadcast_to_empty = False\n\n # We need to handle Ellipsis and make arrays from indices, also\n # check if this is fancy indexing (set no_copy).\n ndim = 0\n ellipsis_pos = None # define here mostly to replace all but first.\n for i, indx in enumerate(in_indices):\n if indx is None:\n continue\n if isinstance(indx, np.ndarray) and indx.dtype == bool:\n no_copy = False\n if indx.ndim == 0:\n raise IndexError\n # boolean indices can have higher dimensions\n ndim += indx.ndim\n fancy_dim += indx.ndim\n continue\n if indx is Ellipsis:\n if ellipsis_pos is None:\n ellipsis_pos = i\n continue # do not increment ndim counter\n raise IndexError\n if isinstance(indx, slice):\n ndim += 1\n continue\n if not isinstance(indx, np.ndarray):\n # This could be open for changes in numpy.\n # numpy should maybe raise an error if casting to intp\n # is not safe. It rejects np.array([1., 2.]) but not\n # [1., 2.] as index (same for ie. np.take).\n # (Note the importance of empty lists if changing this here)\n try:\n indx = np.array(indx, dtype=np.intp)\n except ValueError:\n raise IndexError\n in_indices[i] = indx\n elif indx.dtype.kind != 'b' and indx.dtype.kind != 'i':\n raise IndexError('arrays used as indices must be of '\n 'integer (or boolean) type')\n if indx.ndim != 0:\n no_copy = False\n ndim += 1\n fancy_dim += 1\n\n if arr.ndim - ndim < 0:\n # we can't take more dimensions then we have, not even for 0-d\n # arrays. since a[()] makes sense, but not a[(),]. We will\n # raise an error later on, unless a broadcasting error occurs\n # first.\n raise IndexError\n\n if ndim == 0 and None not in in_indices:\n # Well we have no indexes or one Ellipsis. This is legal.\n return arr.copy(), no_copy\n\n if ellipsis_pos is not None:\n in_indices[ellipsis_pos:ellipsis_pos+1] = ([slice(None, None)] *\n (arr.ndim - ndim))\n\n for ax, indx in enumerate(in_indices):\n if isinstance(indx, slice):\n # convert to an index array\n indx = np.arange(*indx.indices(arr.shape[ax]))\n indices.append(['s', indx])\n continue\n elif indx is None:\n # this is like taking a slice with one element from a new axis:\n indices.append(['n', np.array([0], dtype=np.intp)])\n arr = arr.reshape((arr.shape[:ax] + (1,) + arr.shape[ax:]))\n continue\n if isinstance(indx, np.ndarray) and indx.dtype == bool:\n if indx.shape != arr.shape[ax:ax+indx.ndim]:\n raise IndexError\n\n try:\n flat_indx = np.ravel_multi_index(np.nonzero(indx),\n arr.shape[ax:ax+indx.ndim], mode='raise')\n except Exception:\n error_unless_broadcast_to_empty = True\n # fill with 0s instead, and raise error later\n flat_indx = np.array([0]*indx.sum(), dtype=np.intp)\n # concatenate axis into a single one:\n if indx.ndim != 0:\n arr = arr.reshape((arr.shape[:ax]\n + (np.prod(arr.shape[ax:ax+indx.ndim]),)\n + arr.shape[ax+indx.ndim:]))\n indx = flat_indx\n else:\n # This could be changed, a 0-d boolean index can\n # make sense (even outside the 0-d indexed array case)\n # Note that originally this is could be interpreted as\n # integer in the full integer special case.\n raise IndexError\n else:\n # If the index is a singleton, the bounds check is done\n # before the broadcasting. This used to be different in <1.9\n if indx.ndim == 0:\n if indx >= arr.shape[ax] or indx < -arr.shape[ax]:\n raise IndexError\n if indx.ndim == 0:\n # The index is a scalar. This used to be two fold, but if\n # fancy indexing was active, the check was done later,\n # possibly after broadcasting it away (1.7. or earlier).\n # Now it is always done.\n if indx >= arr.shape[ax] or indx < - arr.shape[ax]:\n raise IndexError\n if (len(indices) > 0 and\n indices[-1][0] == 'f' and\n ax != ellipsis_pos):\n # NOTE: There could still have been a 0-sized Ellipsis\n # between them. Checked that with ellipsis_pos.\n indices[-1].append(indx)\n else:\n # We have a fancy index that is not after an existing one.\n # NOTE: A 0-d array triggers this as well, while one may\n # expect it to not trigger it, since a scalar would not be\n # considered fancy indexing.\n num_fancy += 1\n indices.append(['f', indx])\n\n if num_fancy > 1 and not no_copy:\n # We have to flush the fancy indexes left\n new_indices = indices[:]\n axes = list(range(arr.ndim))\n fancy_axes = []\n new_indices.insert(0, ['f'])\n ni = 0\n ai = 0\n for indx in indices:\n ni += 1\n if indx[0] == 'f':\n new_indices[0].extend(indx[1:])\n del new_indices[ni]\n ni -= 1\n for ax in range(ai, ai + len(indx[1:])):\n fancy_axes.append(ax)\n axes.remove(ax)\n ai += len(indx) - 1 # axis we are at\n indices = new_indices\n # and now we need to transpose arr:\n arr = arr.transpose(*(fancy_axes + axes))\n\n # We only have one 'f' index now and arr is transposed accordingly.\n # Now handle newaxis by reshaping...\n ax = 0\n for indx in indices:\n if indx[0] == 'f':\n if len(indx) == 1:\n continue\n # First of all, reshape arr to combine fancy axes into one:\n orig_shape = arr.shape\n orig_slice = orig_shape[ax:ax + len(indx[1:])]\n arr = arr.reshape((arr.shape[:ax]\n + (np.prod(orig_slice).astype(int),)\n + arr.shape[ax + len(indx[1:]):]))\n\n # Check if broadcasting works\n res = np.broadcast(*indx[1:])\n # unfortunately the indices might be out of bounds. So check\n # that first, and use mode='wrap' then. However only if\n # there are any indices...\n if res.size != 0:\n if error_unless_broadcast_to_empty:\n raise IndexError\n for _indx, _size in zip(indx[1:], orig_slice):\n if _indx.size == 0:\n continue\n if np.any(_indx >= _size) or np.any(_indx < -_size):\n raise IndexError\n if len(indx[1:]) == len(orig_slice):\n if np.product(orig_slice) == 0:\n # Work around for a crash or IndexError with 'wrap'\n # in some 0-sized cases.\n try:\n mi = np.ravel_multi_index(indx[1:], orig_slice,\n mode='raise')\n except Exception:\n # This happens with 0-sized orig_slice (sometimes?)\n # here it is a ValueError, but indexing gives a:\n raise IndexError('invalid index into 0-sized')\n else:\n mi = np.ravel_multi_index(indx[1:], orig_slice,\n mode='wrap')\n else:\n # Maybe never happens...\n raise ValueError\n arr = arr.take(mi.ravel(), axis=ax)\n try:\n arr = arr.reshape((arr.shape[:ax]\n + mi.shape\n + arr.shape[ax+1:]))\n except ValueError:\n # too many dimensions, probably\n raise IndexError\n ax += mi.ndim\n continue\n\n # If we are here, we have a 1D array for take:\n arr = arr.take(indx[1], axis=ax)\n ax += 1\n\n return arr, no_copy\n\n def _check_multi_index(self, arr, index):\n \"\"\"Check a multi index item getting and simple setting.\n\n Parameters\n ----------\n arr : ndarray\n Array to be indexed, must be a reshaped arange.\n index : tuple of indexing objects\n Index being tested.\n \"\"\"\n # Test item getting\n try:\n mimic_get, no_copy = self._get_multi_index(arr, index)\n except Exception as e:\n if HAS_REFCOUNT:\n prev_refcount = sys.getrefcount(arr)\n assert_raises(type(e), arr.__getitem__, index)\n assert_raises(type(e), arr.__setitem__, index, 0)\n if HAS_REFCOUNT:\n assert_equal(prev_refcount, sys.getrefcount(arr))\n return\n\n self._compare_index_result(arr, index, mimic_get, no_copy)\n\n def _check_single_index(self, arr, index):\n \"\"\"Check a single index item getting and simple setting.\n\n Parameters\n ----------\n arr : ndarray\n Array to be indexed, must be an arange.\n index : indexing object\n Index being tested. Must be a single index and not a tuple\n of indexing objects (see also `_check_multi_index`).\n \"\"\"\n try:\n mimic_get, no_copy = self._get_multi_index(arr, (index,))\n except Exception as e:\n if HAS_REFCOUNT:\n prev_refcount = sys.getrefcount(arr)\n assert_raises(type(e), arr.__getitem__, index)\n assert_raises(type(e), arr.__setitem__, index, 0)\n if HAS_REFCOUNT:\n assert_equal(prev_refcount, sys.getrefcount(arr))\n return\n\n self._compare_index_result(arr, index, mimic_get, no_copy)\n\n def _compare_index_result(self, arr, index, mimic_get, no_copy):\n \"\"\"Compare mimicked result to indexing result.\n \"\"\"\n arr = arr.copy()\n indexed_arr = arr[index]\n assert_array_equal(indexed_arr, mimic_get)\n # Check if we got a view, unless its a 0-sized or 0-d array.\n # (then its not a view, and that does not matter)\n if indexed_arr.size != 0 and indexed_arr.ndim != 0:\n assert_(np.may_share_memory(indexed_arr, arr) == no_copy)\n # Check reference count of the original array\n if HAS_REFCOUNT:\n if no_copy:\n # refcount increases by one:\n assert_equal(sys.getrefcount(arr), 3)\n else:\n assert_equal(sys.getrefcount(arr), 2)\n\n # Test non-broadcast setitem:\n b = arr.copy()\n b[index] = mimic_get + 1000\n if b.size == 0:\n return # nothing to compare here...\n if no_copy and indexed_arr.ndim != 0:\n # change indexed_arr in-place to manipulate original:\n indexed_arr += 1000\n assert_array_equal(arr, b)\n return\n # Use the fact that the array is originally an arange:\n arr.flat[indexed_arr.ravel()] += 1000\n assert_array_equal(arr, b)\n\n def test_boolean(self):\n a = np.array(5)\n assert_equal(a[np.array(True)], 5)\n a[np.array(True)] = 1\n assert_equal(a, 1)\n # NOTE: This is different from normal broadcasting, as\n # arr[boolean_array] works like in a multi index. Which means\n # it is aligned to the left. This is probably correct for\n # consistency with arr[boolean_array,] also no broadcasting\n # is done at all\n self._check_multi_index(\n self.a, (np.zeros_like(self.a, dtype=bool),))\n self._check_multi_index(\n self.a, (np.zeros_like(self.a, dtype=bool)[..., 0],))\n self._check_multi_index(\n self.a, (np.zeros_like(self.a, dtype=bool)[None, ...],))\n\n def test_multidim(self):\n # Automatically test combinations with complex indexes on 2nd (or 1st)\n # spot and the simple ones in one other spot.\n with warnings.catch_warnings():\n # This is so that np.array(True) is not accepted in a full integer\n # index, when running the file separately.\n warnings.filterwarnings('error', '', DeprecationWarning)\n warnings.filterwarnings('error', '', np.VisibleDeprecationWarning)\n\n def isskip(idx):\n return isinstance(idx, str) and idx == \"skip\"\n\n for simple_pos in [0, 2, 3]:\n tocheck = [self.fill_indices, self.complex_indices,\n self.fill_indices, self.fill_indices]\n tocheck[simple_pos] = self.simple_indices\n for index in product(*tocheck):\n index = tuple(i for i in index if not isskip(i))\n self._check_multi_index(self.a, index)\n self._check_multi_index(self.b, index)\n\n # Check very simple item getting:\n self._check_multi_index(self.a, (0, 0, 0, 0))\n self._check_multi_index(self.b, (0, 0, 0, 0))\n # Also check (simple cases of) too many indices:\n assert_raises(IndexError, self.a.__getitem__, (0, 0, 0, 0, 0))\n assert_raises(IndexError, self.a.__setitem__, (0, 0, 0, 0, 0), 0)\n assert_raises(IndexError, self.a.__getitem__, (0, 0, [1], 0, 0))\n assert_raises(IndexError, self.a.__setitem__, (0, 0, [1], 0, 0), 0)\n\n def test_1d(self):\n a = np.arange(10)\n for index in self.complex_indices:\n self._check_single_index(a, index)\n\nclass TestFloatNonIntegerArgument:\n \"\"\"\n These test that ``TypeError`` is raised when you try to use\n non-integers as arguments to for indexing and slicing e.g. ``a[0.0:5]``\n and ``a[0.5]``, or other functions like ``array.reshape(1., -1)``.\n\n \"\"\"\n def test_valid_indexing(self):\n # These should raise no errors.\n a = np.array([[[5]]])\n\n a[np.array([0])]\n a[[0, 0]]\n a[:, [0, 0]]\n a[:, 0,:]\n a[:,:,:]\n\n def test_valid_slicing(self):\n # These should raise no errors.\n a = np.array([[[5]]])\n\n a[::]\n a[0:]\n a[:2]\n a[0:2]\n a[::2]\n a[1::2]\n a[:2:2]\n a[1:2:2]\n\n def test_non_integer_argument_errors(self):\n a = np.array([[5]])\n\n assert_raises(TypeError, np.reshape, a, (1., 1., -1))\n assert_raises(TypeError, np.reshape, a, (np.array(1.), -1))\n assert_raises(TypeError, np.take, a, [0], 1.)\n assert_raises(TypeError, np.take, a, [0], np.float64(1.))\n\n def test_non_integer_sequence_multiplication(self):\n # NumPy scalar sequence multiply should not work with non-integers\n def mult(a, b):\n return a * b\n\n assert_raises(TypeError, mult, [1], np.float_(3))\n # following should be OK\n mult([1], np.int_(3))\n\n def test_reduce_axis_float_index(self):\n d = np.zeros((3,3,3))\n assert_raises(TypeError, np.min, d, 0.5)\n assert_raises(TypeError, np.min, d, (0.5, 1))\n assert_raises(TypeError, np.min, d, (1, 2.2))\n assert_raises(TypeError, np.min, d, (.2, 1.2))\n\n\nclass TestBooleanIndexing:\n # Using a boolean as integer argument/indexing is an error.\n def test_bool_as_int_argument_errors(self):\n a = np.array([[[1]]])\n\n assert_raises(TypeError, np.reshape, a, (True, -1))\n assert_raises(TypeError, np.reshape, a, (np.bool_(True), -1))\n # Note that operator.index(np.array(True)) does not work, a boolean\n # array is thus also deprecated, but not with the same message:\n assert_raises(TypeError, operator.index, np.array(True))\n assert_warns(DeprecationWarning, operator.index, np.True_)\n assert_raises(TypeError, np.take, args=(a, [0], False))\n\n def test_boolean_indexing_weirdness(self):\n # Weird boolean indexing things\n a = np.ones((2, 3, 4))\n a[False, True, ...].shape == (0, 2, 3, 4)\n a[True, [0, 1], True, True, [1], [[2]]] == (1, 2)\n assert_raises(IndexError, lambda: a[False, [0, 1], ...])\n\n\n def test_boolean_indexing_fast_path(self):\n # These used to either give the wrong error, or incorrectly give no\n # error.\n a = np.ones((3, 3))\n\n # This used to incorrectly work (and give an array of shape (0,))\n idx1 = np.array([[False]*9])\n assert_raises_regex(IndexError,\n \"boolean index did not match indexed array along dimension 0; \"\n \"dimension is 3 but corresponding boolean dimension is 1\",\n lambda: a[idx1])\n\n # This used to incorrectly give a ValueError: operands could not be broadcast together\n idx2 = np.array([[False]*8 + [True]])\n assert_raises_regex(IndexError,\n \"boolean index did not match indexed array along dimension 0; \"\n \"dimension is 3 but corresponding boolean dimension is 1\",\n lambda: a[idx2])\n\n # This is the same as it used to be. The above two should work like this.\n idx3 = np.array([[False]*10])\n assert_raises_regex(IndexError,\n \"boolean index did not match indexed array along dimension 0; \"\n \"dimension is 3 but corresponding boolean dimension is 1\",\n lambda: a[idx3])\n\n # This used to give ValueError: non-broadcastable operand\n a = np.ones((1, 1, 2))\n idx = np.array([[[True], [False]]])\n assert_raises_regex(IndexError,\n \"boolean index did not match indexed array along dimension 1; \"\n \"dimension is 1 but corresponding boolean dimension is 2\",\n lambda: a[idx])\n\n\nclass TestArrayToIndexDeprecation:\n \"\"\"Creating an an index from array not 0-D is an error.\n\n \"\"\"\n def test_array_to_index_error(self):\n # so no exception is expected. The raising is effectively tested above.\n a = np.array([[[1]]])\n\n assert_raises(TypeError, operator.index, np.array([1]))\n assert_raises(TypeError, np.reshape, a, (a, -1))\n assert_raises(TypeError, np.take, a, [0], a)\n\n\nclass TestNonIntegerArrayLike:\n \"\"\"Tests that array_likes only valid if can safely cast to integer.\n\n For instance, lists give IndexError when they cannot be safely cast to\n an integer.\n\n \"\"\"\n def test_basic(self):\n a = np.arange(10)\n\n assert_raises(IndexError, a.__getitem__, [0.5, 1.5])\n assert_raises(IndexError, a.__getitem__, (['1', '2'],))\n\n # The following is valid\n a.__getitem__([])\n\n\nclass TestMultipleEllipsisError:\n \"\"\"An index can only have a single ellipsis.\n\n \"\"\"\n def test_basic(self):\n a = np.arange(10)\n assert_raises(IndexError, lambda: a[..., ...])\n assert_raises(IndexError, a.__getitem__, ((Ellipsis,) * 2,))\n assert_raises(IndexError, a.__getitem__, ((Ellipsis,) * 3,))\n\n\nclass TestCApiAccess:\n def test_getitem(self):\n subscript = functools.partial(array_indexing, 0)\n\n # 0-d arrays don't work:\n assert_raises(IndexError, subscript, np.ones(()), 0)\n # Out of bound values:\n assert_raises(IndexError, subscript, np.ones(10), 11)\n assert_raises(IndexError, subscript, np.ones(10), -11)\n assert_raises(IndexError, subscript, np.ones((10, 10)), 11)\n assert_raises(IndexError, subscript, np.ones((10, 10)), -11)\n\n a = np.arange(10)\n assert_array_equal(a[4], subscript(a, 4))\n a = a.reshape(5, 2)\n assert_array_equal(a[-4], subscript(a, -4))\n\n def test_setitem(self):\n assign = functools.partial(array_indexing, 1)\n\n # Deletion is impossible:\n assert_raises(ValueError, assign, np.ones(10), 0)\n # 0-d arrays don't work:\n assert_raises(IndexError, assign, np.ones(()), 0, 0)\n # Out of bound values:\n assert_raises(IndexError, assign, np.ones(10), 11, 0)\n assert_raises(IndexError, assign, np.ones(10), -11, 0)\n assert_raises(IndexError, assign, np.ones((10, 10)), 11, 0)\n assert_raises(IndexError, assign, np.ones((10, 10)), -11, 0)\n\n a = np.arange(10)\n assign(a, 4, 10)\n assert_(a[4] == 10)\n\n a = a.reshape(5, 2)\n assign(a, 4, 10)\n assert_array_equal(a[-1], [10, 10])\n", "import numpy as np\nimport pytest\n\nfrom pandas import (\n Categorical,\n Series,\n)\nimport pandas._testing as tm\n\n\[email protected](\n \"keep, expected\",\n [\n (\"first\", Series([False, False, True, False, True], name=\"name\")),\n (\"last\", Series([True, True, False, False, False], name=\"name\")),\n (False, Series([True, True, True, False, True], name=\"name\")),\n ],\n)\ndef test_duplicated_keep(keep, expected):\n ser = Series([\"a\", \"b\", \"b\", \"c\", \"a\"], name=\"name\")\n\n result = ser.duplicated(keep=keep)\n tm.assert_series_equal(result, expected)\n\n\[email protected](\n \"keep, expected\",\n [\n (\"first\", Series([False, False, True, False, True])),\n (\"last\", Series([True, True, False, False, False])),\n (False, Series([True, True, True, False, True])),\n ],\n)\ndef test_duplicated_nan_none(keep, expected):\n ser = Series([np.nan, 3, 3, None, np.nan], dtype=object)\n\n result = ser.duplicated(keep=keep)\n tm.assert_series_equal(result, expected)\n\n\ndef test_duplicated_categorical_bool_na(nulls_fixture):\n # GH#44351\n ser = Series(\n Categorical(\n [True, False, True, False, nulls_fixture],\n categories=[True, False],\n ordered=True,\n )\n )\n result = ser.duplicated()\n expected = Series([False, False, True, True, False])\n tm.assert_series_equal(result, expected)\n", "\"\"\"\naxes3d.py, original mplot3d version by John Porter\nCreated: 23 Sep 2005\n\nParts fixed by Reinier Heeres <[email protected]>\nMinor additions by Ben Axelrod <[email protected]>\nSignificant updates and revisions by Ben Root <[email protected]>\n\nModule containing Axes3D, an object which can plot 3D objects on a\n2D matplotlib figure.\n\"\"\"\n\nfrom collections import defaultdict\nimport functools\nimport inspect\nimport itertools\nimport math\nfrom numbers import Integral\nimport textwrap\n\nimport numpy as np\n\nfrom matplotlib import _api, cbook, docstring, _preprocess_data\nimport matplotlib.artist as martist\nimport matplotlib.axes as maxes\nimport matplotlib.collections as mcoll\nimport matplotlib.colors as mcolors\nimport matplotlib.image as mimage\nimport matplotlib.lines as mlines\nimport matplotlib.patches as mpatches\nimport matplotlib.scale as mscale\nimport matplotlib.container as mcontainer\nimport matplotlib.transforms as mtransforms\nfrom matplotlib.axes import Axes, rcParams\nfrom matplotlib.axes._base import _axis_method_wrapper, _process_plot_format\nfrom matplotlib.transforms import Bbox\nfrom matplotlib.tri.triangulation import Triangulation\n\nfrom . import art3d\nfrom . import proj3d\nfrom . import axis3d\n\n\[email protected]\n@cbook._define_aliases({\n \"xlim3d\": [\"xlim\"], \"ylim3d\": [\"ylim\"], \"zlim3d\": [\"zlim\"]})\nclass Axes3D(Axes):\n \"\"\"\n 3D axes object.\n \"\"\"\n name = '3d'\n\n _axis_names = (\"x\", \"y\", \"z\")\n Axes._shared_axes[\"z\"] = cbook.Grouper()\n\n def __init__(\n self, fig, rect=None, *args,\n azim=-60, elev=30, sharez=None, proj_type='persp',\n box_aspect=None, computed_zorder=True,\n **kwargs):\n \"\"\"\n Parameters\n ----------\n fig : Figure\n The parent figure.\n rect : (float, float, float, float)\n The ``(left, bottom, width, height)`` axes position.\n azim : float, default: -60\n Azimuthal viewing angle.\n elev : float, default: 30\n Elevation viewing angle.\n sharez : Axes3D, optional\n Other axes to share z-limits with.\n proj_type : {'persp', 'ortho'}\n The projection type, default 'persp'.\n computed_zorder : bool, default: True\n If True, the draw order is computed based on the average position\n of the `.Artist`\\\\s along the view direction.\n Set to False if you want to manually control the order in which\n Artists are drawn on top of each other using their *zorder*\n attribute. This can be used for fine-tuning if the automatic order\n does not produce the desired result. Note however, that a manual\n zorder will only be correct for a limited view angle. If the figure\n is rotated by the user, it will look wrong from certain angles.\n auto_add_to_figure : bool, default: True\n Prior to Matplotlib 3.4 Axes3D would add themselves\n to their host Figure on init. Other Axes class do not\n do this.\n\n This behavior is deprecated in 3.4, the default will\n change to False in 3.5. The keyword will be undocumented\n and a non-False value will be an error in 3.6.\n\n **kwargs\n Other optional keyword arguments:\n\n %(Axes3D:kwdoc)s\n \"\"\"\n\n if rect is None:\n rect = [0.0, 0.0, 1.0, 1.0]\n\n self.initial_azim = azim\n self.initial_elev = elev\n self.set_proj_type(proj_type)\n self.computed_zorder = computed_zorder\n\n self.xy_viewLim = Bbox.unit()\n self.zz_viewLim = Bbox.unit()\n self.xy_dataLim = Bbox.unit()\n # z-limits are encoded in the x-component of the Bbox, y is un-used\n self.zz_dataLim = Bbox.unit()\n\n # inhibit autoscale_view until the axes are defined\n # they can't be defined until Axes.__init__ has been called\n self.view_init(self.initial_elev, self.initial_azim)\n\n self._sharez = sharez\n if sharez is not None:\n self._shared_axes[\"z\"].join(self, sharez)\n self._adjustable = 'datalim'\n\n auto_add_to_figure = kwargs.pop('auto_add_to_figure', True)\n\n super().__init__(\n fig, rect, frameon=True, box_aspect=box_aspect, *args, **kwargs\n )\n # Disable drawing of axes by base class\n super().set_axis_off()\n # Enable drawing of axes by Axes3D class\n self.set_axis_on()\n self.M = None\n\n # func used to format z -- fall back on major formatters\n self.fmt_zdata = None\n\n self.mouse_init()\n self.figure.canvas.callbacks._pickled_cids.update({\n self.figure.canvas.mpl_connect(\n 'motion_notify_event', self._on_move),\n self.figure.canvas.mpl_connect(\n 'button_press_event', self._button_press),\n self.figure.canvas.mpl_connect(\n 'button_release_event', self._button_release),\n })\n self.set_top_view()\n\n self.patch.set_linewidth(0)\n # Calculate the pseudo-data width and height\n pseudo_bbox = self.transLimits.inverted().transform([(0, 0), (1, 1)])\n self._pseudo_w, self._pseudo_h = pseudo_bbox[1] - pseudo_bbox[0]\n\n # mplot3d currently manages its own spines and needs these turned off\n # for bounding box calculations\n self.spines[:].set_visible(False)\n\n if auto_add_to_figure:\n _api.warn_deprecated(\n \"3.4\", removal=\"3.6\", message=\"Axes3D(fig) adding itself \"\n \"to the figure is deprecated since %(since)s. \"\n \"Pass the keyword argument auto_add_to_figure=False \"\n \"and use fig.add_axes(ax) to suppress this warning. \"\n \"The default value of auto_add_to_figure will change to \"\n \"False in mpl3.5 and True values will \"\n \"no longer work %(removal)s. This is consistent with \"\n \"other Axes classes.\")\n fig.add_axes(self)\n\n def set_axis_off(self):\n self._axis3don = False\n self.stale = True\n\n def set_axis_on(self):\n self._axis3don = True\n self.stale = True\n\n def convert_zunits(self, z):\n \"\"\"\n For artists in an axes, if the zaxis has units support,\n convert *z* using zaxis unit type\n \"\"\"\n return self.zaxis.convert_units(z)\n\n def set_top_view(self):\n # this happens to be the right view for the viewing coordinates\n # moved up and to the left slightly to fit labels and axes\n xdwl = 0.95 / self.dist\n xdw = 0.9 / self.dist\n ydwl = 0.95 / self.dist\n ydw = 0.9 / self.dist\n # This is purposely using the 2D Axes's set_xlim and set_ylim,\n # because we are trying to place our viewing pane.\n super().set_xlim(-xdwl, xdw, auto=None)\n super().set_ylim(-ydwl, ydw, auto=None)\n\n def _init_axis(self):\n \"\"\"Init 3D axes; overrides creation of regular X/Y axes.\"\"\"\n self.xaxis = axis3d.XAxis('x', self.xy_viewLim.intervalx,\n self.xy_dataLim.intervalx, self)\n self.yaxis = axis3d.YAxis('y', self.xy_viewLim.intervaly,\n self.xy_dataLim.intervaly, self)\n self.zaxis = axis3d.ZAxis('z', self.zz_viewLim.intervalx,\n self.zz_dataLim.intervalx, self)\n for ax in self.xaxis, self.yaxis, self.zaxis:\n ax.init3d()\n\n def get_zaxis(self):\n \"\"\"Return the ``ZAxis`` (`~.axis3d.Axis`) instance.\"\"\"\n return self.zaxis\n\n get_zgridlines = _axis_method_wrapper(\"zaxis\", \"get_gridlines\")\n get_zticklines = _axis_method_wrapper(\"zaxis\", \"get_ticklines\")\n\n w_xaxis = _api.deprecated(\"3.1\", alternative=\"xaxis\", pending=True)(\n property(lambda self: self.xaxis))\n w_yaxis = _api.deprecated(\"3.1\", alternative=\"yaxis\", pending=True)(\n property(lambda self: self.yaxis))\n w_zaxis = _api.deprecated(\"3.1\", alternative=\"zaxis\", pending=True)(\n property(lambda self: self.zaxis))\n\n def unit_cube(self, vals=None):\n minx, maxx, miny, maxy, minz, maxz = vals or self.get_w_lims()\n return [(minx, miny, minz),\n (maxx, miny, minz),\n (maxx, maxy, minz),\n (minx, maxy, minz),\n (minx, miny, maxz),\n (maxx, miny, maxz),\n (maxx, maxy, maxz),\n (minx, maxy, maxz)]\n\n def tunit_cube(self, vals=None, M=None):\n if M is None:\n M = self.M\n xyzs = self.unit_cube(vals)\n tcube = proj3d.proj_points(xyzs, M)\n return tcube\n\n def tunit_edges(self, vals=None, M=None):\n tc = self.tunit_cube(vals, M)\n edges = [(tc[0], tc[1]),\n (tc[1], tc[2]),\n (tc[2], tc[3]),\n (tc[3], tc[0]),\n\n (tc[0], tc[4]),\n (tc[1], tc[5]),\n (tc[2], tc[6]),\n (tc[3], tc[7]),\n\n (tc[4], tc[5]),\n (tc[5], tc[6]),\n (tc[6], tc[7]),\n (tc[7], tc[4])]\n return edges\n\n def set_aspect(self, aspect, adjustable=None, anchor=None, share=False):\n \"\"\"\n Set the aspect ratios.\n\n Axes 3D does not current support any aspect but 'auto' which fills\n the axes with the data limits.\n\n To simulate having equal aspect in data space, set the ratio\n of your data limits to match the value of `.get_box_aspect`.\n To control box aspect ratios use `~.Axes3D.set_box_aspect`.\n\n Parameters\n ----------\n aspect : {'auto'}\n Possible values:\n\n ========= ==================================================\n value description\n ========= ==================================================\n 'auto' automatic; fill the position rectangle with data.\n ========= ==================================================\n\n adjustable : None\n Currently ignored by Axes3D\n\n If not *None*, this defines which parameter will be adjusted to\n meet the required aspect. See `.set_adjustable` for further\n details.\n\n anchor : None or str or 2-tuple of float, optional\n If not *None*, this defines where the Axes will be drawn if there\n is extra space due to aspect constraints. The most common way to\n to specify the anchor are abbreviations of cardinal directions:\n\n ===== =====================\n value description\n ===== =====================\n 'C' centered\n 'SW' lower left corner\n 'S' middle of bottom edge\n 'SE' lower right corner\n etc.\n ===== =====================\n\n See `~.Axes.set_anchor` for further details.\n\n share : bool, default: False\n If ``True``, apply the settings to all shared Axes.\n\n See Also\n --------\n mpl_toolkits.mplot3d.axes3d.Axes3D.set_box_aspect\n \"\"\"\n if aspect != 'auto':\n raise NotImplementedError(\n \"Axes3D currently only supports the aspect argument \"\n f\"'auto'. You passed in {aspect!r}.\"\n )\n super().set_aspect(\n aspect, adjustable=adjustable, anchor=anchor, share=share)\n\n def set_box_aspect(self, aspect, *, zoom=1):\n \"\"\"\n Set the axes box aspect.\n\n The box aspect is the ratio of height to width in display\n units for each face of the box when viewed perpendicular to\n that face. This is not to be confused with the data aspect\n (which for Axes3D is always 'auto'). The default ratios are\n 4:4:3 (x:y:z).\n\n To simulate having equal aspect in data space, set the box\n aspect to match your data range in each dimension.\n\n *zoom* controls the overall size of the Axes3D in the figure.\n\n Parameters\n ----------\n aspect : 3-tuple of floats or None\n Changes the physical dimensions of the Axes3D, such that the ratio\n of the axis lengths in display units is x:y:z.\n\n If None, defaults to 4:4:3\n\n zoom : float\n Control overall size of the Axes3D in the figure.\n \"\"\"\n if aspect is None:\n aspect = np.asarray((4, 4, 3), dtype=float)\n else:\n orig_aspect = aspect\n aspect = np.asarray(aspect, dtype=float)\n if aspect.shape != (3,):\n raise ValueError(\n \"You must pass a 3-tuple that can be cast to floats. \"\n f\"You passed {orig_aspect!r}\"\n )\n # default scale tuned to match the mpl32 appearance.\n aspect *= 1.8294640721620434 * zoom / np.linalg.norm(aspect)\n\n self._box_aspect = aspect\n self.stale = True\n\n def apply_aspect(self, position=None):\n if position is None:\n position = self.get_position(original=True)\n\n # in the superclass, we would go through and actually deal with axis\n # scales and box/datalim. Those are all irrelevant - all we need to do\n # is make sure our coordinate system is square.\n trans = self.get_figure().transSubfigure\n bb = mtransforms.Bbox.from_bounds(0, 0, 1, 1).transformed(trans)\n # this is the physical aspect of the panel (or figure):\n fig_aspect = bb.height / bb.width\n\n box_aspect = 1\n pb = position.frozen()\n pb1 = pb.shrunk_to_aspect(box_aspect, pb, fig_aspect)\n self._set_position(pb1.anchored(self.get_anchor(), pb), 'active')\n\n @martist.allow_rasterization\n def draw(self, renderer):\n self._unstale_viewLim()\n\n # draw the background patch\n self.patch.draw(renderer)\n self._frameon = False\n\n # first, set the aspect\n # this is duplicated from `axes._base._AxesBase.draw`\n # but must be called before any of the artist are drawn as\n # it adjusts the view limits and the size of the bounding box\n # of the axes\n locator = self.get_axes_locator()\n if locator:\n pos = locator(self, renderer)\n self.apply_aspect(pos)\n else:\n self.apply_aspect()\n\n # add the projection matrix to the renderer\n self.M = self.get_proj()\n props3d = {\n # To raise a deprecation, we need to wrap the attribute in a\n # function, but binding that to an instance does not work, as you\n # would end up with an instance-specific method. Properties are\n # class-level attributes which *are* functions, so we do that\n # instead.\n # This dictionary comprehension creates deprecated properties for\n # the attributes listed below, and they are temporarily attached to\n # the _class_ in the `_setattr_cm` call. These can both be removed\n # once the deprecation expires\n name: _api.deprecated('3.4', name=name,\n alternative=f'self.axes.{name}')(\n property(lambda self, _value=getattr(self, name): _value))\n for name in ['M', 'vvec', 'eye', 'get_axis_position']\n }\n\n with cbook._setattr_cm(type(renderer), **props3d):\n def do_3d_projection(artist):\n \"\"\"\n Call `do_3d_projection` on an *artist*, and warn if passing\n *renderer*.\n\n Attempt to bind the empty signature first, so external Artists\n can avoid the deprecation warning if they support the new\n calling convention.\n \"\"\"\n try:\n signature = inspect.signature(artist.do_3d_projection)\n signature.bind()\n # ValueError if `inspect.signature` cannot provide a signature\n # and TypeError if the binding fails or the object does not\n # appear to be callable - the next call will then re-raise.\n except (ValueError, TypeError):\n _api.warn_deprecated(\n \"3.4\",\n message=\"The 'renderer' parameter of \"\n \"do_3d_projection() was deprecated in Matplotlib \"\n \"%(since)s and will be removed %(removal)s.\")\n return artist.do_3d_projection(renderer)\n else:\n # Call this directly once the deprecation period expires.\n return artist.do_3d_projection()\n\n collections_and_patches = (\n artist for artist in self._children\n if isinstance(artist, (mcoll.Collection, mpatches.Patch)))\n if self.computed_zorder:\n # Calculate projection of collections and patches and zorder\n # them. Make sure they are drawn above the grids.\n zorder_offset = max(axis.get_zorder()\n for axis in self._get_axis_list()) + 1\n collection_zorder = patch_zorder = zorder_offset\n for artist in sorted(collections_and_patches,\n key=do_3d_projection,\n reverse=True):\n if isinstance(artist, mcoll.Collection):\n artist.zorder = collection_zorder\n collection_zorder += 1\n elif isinstance(artist, mpatches.Patch):\n artist.zorder = patch_zorder\n patch_zorder += 1\n else:\n for artist in collections_and_patches:\n artist.do_3d_projection()\n\n if self._axis3don:\n # Draw panes first\n for axis in self._get_axis_list():\n axis.draw_pane(renderer)\n # Then axes\n for axis in self._get_axis_list():\n axis.draw(renderer)\n\n # Then rest\n super().draw(renderer)\n\n def get_axis_position(self):\n vals = self.get_w_lims()\n tc = self.tunit_cube(vals, self.M)\n xhigh = tc[1][2] > tc[2][2]\n yhigh = tc[3][2] > tc[2][2]\n zhigh = tc[0][2] > tc[2][2]\n return xhigh, yhigh, zhigh\n\n def _unit_change_handler(self, axis_name, event=None):\n # docstring inherited\n if event is None: # Allow connecting `self._unit_change_handler(name)`\n return functools.partial(\n self._unit_change_handler, axis_name, event=object())\n _api.check_in_list(self._get_axis_map(), axis_name=axis_name)\n self.relim()\n self._request_autoscale_view(scalex=(axis_name == \"x\"),\n scaley=(axis_name == \"y\"),\n scalez=(axis_name == \"z\"))\n\n def update_datalim(self, xys, **kwargs):\n pass\n\n def get_autoscale_on(self):\n # docstring inherited\n return super().get_autoscale_on() and self.get_autoscalez_on()\n\n def get_autoscalez_on(self):\n \"\"\"Return whether the z-axis is autoscaled.\"\"\"\n return self._autoscaleZon\n\n def set_autoscale_on(self, b):\n # docstring inherited\n super().set_autoscale_on(b)\n self.set_autoscalez_on(b)\n\n def set_autoscalez_on(self, b):\n \"\"\"\n Set whether the z-axis is autoscaled on the next draw or call to\n `.Axes.autoscale_view`.\n\n Parameters\n ----------\n b : bool\n \"\"\"\n self._autoscaleZon = b\n\n def set_xmargin(self, m):\n # docstring inherited\n scalez = self._stale_viewlims[\"z\"]\n super().set_xmargin(m)\n # Superclass is 2D and will call _request_autoscale_view with defaults\n # for unknown Axis, which would be scalez=True, but it shouldn't be for\n # this call, so restore it.\n self._stale_viewlims[\"z\"] = scalez\n\n def set_ymargin(self, m):\n # docstring inherited\n scalez = self._stale_viewlims[\"z\"]\n super().set_ymargin(m)\n # Superclass is 2D and will call _request_autoscale_view with defaults\n # for unknown Axis, which would be scalez=True, but it shouldn't be for\n # this call, so restore it.\n self._stale_viewlims[\"z\"] = scalez\n\n def set_zmargin(self, m):\n \"\"\"\n Set padding of Z data limits prior to autoscaling.\n\n *m* times the data interval will be added to each\n end of that interval before it is used in autoscaling.\n\n accepts: float in range 0 to 1\n \"\"\"\n if m < 0 or m > 1:\n raise ValueError(\"margin must be in range 0 to 1\")\n self._zmargin = m\n self._request_autoscale_view(scalex=False, scaley=False, scalez=True)\n self.stale = True\n\n def margins(self, *margins, x=None, y=None, z=None, tight=True):\n \"\"\"\n Convenience method to set or retrieve autoscaling margins.\n\n Call signatures::\n\n margins()\n\n returns xmargin, ymargin, zmargin\n\n ::\n\n margins(margin)\n\n margins(xmargin, ymargin, zmargin)\n\n margins(x=xmargin, y=ymargin, z=zmargin)\n\n margins(..., tight=False)\n\n All forms above set the xmargin, ymargin and zmargin\n parameters. All keyword parameters are optional. A single\n positional argument specifies xmargin, ymargin and zmargin.\n Passing both positional and keyword arguments for xmargin,\n ymargin, and/or zmargin is invalid.\n\n The *tight* parameter\n is passed to :meth:`autoscale_view`, which is executed after\n a margin is changed; the default here is *True*, on the\n assumption that when margins are specified, no additional\n padding to match tick marks is usually desired. Setting\n *tight* to *None* will preserve the previous setting.\n\n Specifying any margin changes only the autoscaling; for example,\n if *xmargin* is not None, then *xmargin* times the X data\n interval will be added to each end of that interval before\n it is used in autoscaling.\n \"\"\"\n if margins and x is not None and y is not None and z is not None:\n raise TypeError('Cannot pass both positional and keyword '\n 'arguments for x, y, and/or z.')\n elif len(margins) == 1:\n x = y = z = margins[0]\n elif len(margins) == 3:\n x, y, z = margins\n elif margins:\n raise TypeError('Must pass a single positional argument for all '\n 'margins, or one for each margin (x, y, z).')\n\n if x is None and y is None and z is None:\n if tight is not True:\n _api.warn_external(f'ignoring tight={tight!r} in get mode')\n return self._xmargin, self._ymargin, self._zmargin\n\n if x is not None:\n self.set_xmargin(x)\n if y is not None:\n self.set_ymargin(y)\n if z is not None:\n self.set_zmargin(z)\n\n self.autoscale_view(\n tight=tight, scalex=(x is not None), scaley=(y is not None),\n scalez=(z is not None)\n )\n\n def autoscale(self, enable=True, axis='both', tight=None):\n \"\"\"\n Convenience method for simple axis view autoscaling.\n See :meth:`matplotlib.axes.Axes.autoscale` for full explanation.\n Note that this function behaves the same, but for all\n three axes. Therefore, 'z' can be passed for *axis*,\n and 'both' applies to all three axes.\n \"\"\"\n if enable is None:\n scalex = True\n scaley = True\n scalez = True\n else:\n if axis in ['x', 'both']:\n self._autoscaleXon = scalex = bool(enable)\n else:\n scalex = False\n if axis in ['y', 'both']:\n self._autoscaleYon = scaley = bool(enable)\n else:\n scaley = False\n if axis in ['z', 'both']:\n self._autoscaleZon = scalez = bool(enable)\n else:\n scalez = False\n self._request_autoscale_view(tight=tight, scalex=scalex, scaley=scaley,\n scalez=scalez)\n\n def auto_scale_xyz(self, X, Y, Z=None, had_data=None):\n # This updates the bounding boxes as to keep a record as to what the\n # minimum sized rectangular volume holds the data.\n if np.shape(X) == np.shape(Y):\n self.xy_dataLim.update_from_data_xy(\n np.column_stack([np.ravel(X), np.ravel(Y)]), not had_data)\n else:\n self.xy_dataLim.update_from_data_x(X, not had_data)\n self.xy_dataLim.update_from_data_y(Y, not had_data)\n if Z is not None:\n self.zz_dataLim.update_from_data_x(Z, not had_data)\n # Let autoscale_view figure out how to use this data.\n self.autoscale_view()\n\n def autoscale_view(self, tight=None, scalex=True, scaley=True,\n scalez=True):\n \"\"\"\n Autoscale the view limits using the data limits.\n See :meth:`matplotlib.axes.Axes.autoscale_view` for documentation.\n Note that this function applies to the 3D axes, and as such\n adds the *scalez* to the function arguments.\n \"\"\"\n # This method looks at the rectangular volume (see above)\n # of data and decides how to scale the view portal to fit it.\n if tight is None:\n _tight = self._tight\n if not _tight:\n # if image data only just use the datalim\n for artist in self._children:\n if isinstance(artist, mimage.AxesImage):\n _tight = True\n elif isinstance(artist, (mlines.Line2D, mpatches.Patch)):\n _tight = False\n break\n else:\n _tight = self._tight = bool(tight)\n\n if scalex and self._autoscaleXon:\n self._shared_axes[\"x\"].clean()\n x0, x1 = self.xy_dataLim.intervalx\n xlocator = self.xaxis.get_major_locator()\n x0, x1 = xlocator.nonsingular(x0, x1)\n if self._xmargin > 0:\n delta = (x1 - x0) * self._xmargin\n x0 -= delta\n x1 += delta\n if not _tight:\n x0, x1 = xlocator.view_limits(x0, x1)\n self.set_xbound(x0, x1)\n\n if scaley and self._autoscaleYon:\n self._shared_axes[\"y\"].clean()\n y0, y1 = self.xy_dataLim.intervaly\n ylocator = self.yaxis.get_major_locator()\n y0, y1 = ylocator.nonsingular(y0, y1)\n if self._ymargin > 0:\n delta = (y1 - y0) * self._ymargin\n y0 -= delta\n y1 += delta\n if not _tight:\n y0, y1 = ylocator.view_limits(y0, y1)\n self.set_ybound(y0, y1)\n\n if scalez and self._autoscaleZon:\n self._shared_axes[\"z\"].clean()\n z0, z1 = self.zz_dataLim.intervalx\n zlocator = self.zaxis.get_major_locator()\n z0, z1 = zlocator.nonsingular(z0, z1)\n if self._zmargin > 0:\n delta = (z1 - z0) * self._zmargin\n z0 -= delta\n z1 += delta\n if not _tight:\n z0, z1 = zlocator.view_limits(z0, z1)\n self.set_zbound(z0, z1)\n\n def get_w_lims(self):\n \"\"\"Get 3D world limits.\"\"\"\n minx, maxx = self.get_xlim3d()\n miny, maxy = self.get_ylim3d()\n minz, maxz = self.get_zlim3d()\n return minx, maxx, miny, maxy, minz, maxz\n\n def set_xlim3d(self, left=None, right=None, emit=True, auto=False,\n *, xmin=None, xmax=None):\n \"\"\"\n Set 3D x limits.\n\n See :meth:`matplotlib.axes.Axes.set_xlim` for full documentation.\n \"\"\"\n if right is None and np.iterable(left):\n left, right = left\n if xmin is not None:\n if left is not None:\n raise TypeError('Cannot pass both `xmin` and `left`')\n left = xmin\n if xmax is not None:\n if right is not None:\n raise TypeError('Cannot pass both `xmax` and `right`')\n right = xmax\n\n self._process_unit_info([(\"x\", (left, right))], convert=False)\n left = self._validate_converted_limits(left, self.convert_xunits)\n right = self._validate_converted_limits(right, self.convert_xunits)\n\n old_left, old_right = self.get_xlim()\n if left is None:\n left = old_left\n if right is None:\n right = old_right\n\n if left == right:\n _api.warn_external(\n f\"Attempting to set identical left == right == {left} results \"\n f\"in singular transformations; automatically expanding.\")\n reverse = left > right\n left, right = self.xaxis.get_major_locator().nonsingular(left, right)\n left, right = self.xaxis.limit_range_for_scale(left, right)\n # cast to bool to avoid bad interaction between python 3.8 and np.bool_\n left, right = sorted([left, right], reverse=bool(reverse))\n self.xy_viewLim.intervalx = (left, right)\n\n # Mark viewlims as no longer stale without triggering an autoscale.\n for ax in self._shared_axes[\"x\"].get_siblings(self):\n ax._stale_viewlims[\"x\"] = False\n if auto is not None:\n self._autoscaleXon = bool(auto)\n\n if emit:\n self.callbacks.process('xlim_changed', self)\n # Call all of the other x-axes that are shared with this one\n for other in self._shared_axes[\"x\"].get_siblings(self):\n if other is not self:\n other.set_xlim(self.xy_viewLim.intervalx,\n emit=False, auto=auto)\n if other.figure != self.figure:\n other.figure.canvas.draw_idle()\n self.stale = True\n return left, right\n\n def set_ylim3d(self, bottom=None, top=None, emit=True, auto=False,\n *, ymin=None, ymax=None):\n \"\"\"\n Set 3D y limits.\n\n See :meth:`matplotlib.axes.Axes.set_ylim` for full documentation.\n \"\"\"\n if top is None and np.iterable(bottom):\n bottom, top = bottom\n if ymin is not None:\n if bottom is not None:\n raise TypeError('Cannot pass both `ymin` and `bottom`')\n bottom = ymin\n if ymax is not None:\n if top is not None:\n raise TypeError('Cannot pass both `ymax` and `top`')\n top = ymax\n\n self._process_unit_info([(\"y\", (bottom, top))], convert=False)\n bottom = self._validate_converted_limits(bottom, self.convert_yunits)\n top = self._validate_converted_limits(top, self.convert_yunits)\n\n old_bottom, old_top = self.get_ylim()\n if bottom is None:\n bottom = old_bottom\n if top is None:\n top = old_top\n\n if bottom == top:\n _api.warn_external(\n f\"Attempting to set identical bottom == top == {bottom} \"\n f\"results in singular transformations; automatically \"\n f\"expanding.\")\n swapped = bottom > top\n bottom, top = self.yaxis.get_major_locator().nonsingular(bottom, top)\n bottom, top = self.yaxis.limit_range_for_scale(bottom, top)\n if swapped:\n bottom, top = top, bottom\n self.xy_viewLim.intervaly = (bottom, top)\n\n # Mark viewlims as no longer stale without triggering an autoscale.\n for ax in self._shared_axes[\"y\"].get_siblings(self):\n ax._stale_viewlims[\"y\"] = False\n if auto is not None:\n self._autoscaleYon = bool(auto)\n\n if emit:\n self.callbacks.process('ylim_changed', self)\n # Call all of the other y-axes that are shared with this one\n for other in self._shared_axes[\"y\"].get_siblings(self):\n if other is not self:\n other.set_ylim(self.xy_viewLim.intervaly,\n emit=False, auto=auto)\n if other.figure != self.figure:\n other.figure.canvas.draw_idle()\n self.stale = True\n return bottom, top\n\n def set_zlim3d(self, bottom=None, top=None, emit=True, auto=False,\n *, zmin=None, zmax=None):\n \"\"\"\n Set 3D z limits.\n\n See :meth:`matplotlib.axes.Axes.set_ylim` for full documentation\n \"\"\"\n if top is None and np.iterable(bottom):\n bottom, top = bottom\n if zmin is not None:\n if bottom is not None:\n raise TypeError('Cannot pass both `zmin` and `bottom`')\n bottom = zmin\n if zmax is not None:\n if top is not None:\n raise TypeError('Cannot pass both `zmax` and `top`')\n top = zmax\n\n self._process_unit_info([(\"z\", (bottom, top))], convert=False)\n bottom = self._validate_converted_limits(bottom, self.convert_zunits)\n top = self._validate_converted_limits(top, self.convert_zunits)\n\n old_bottom, old_top = self.get_zlim()\n if bottom is None:\n bottom = old_bottom\n if top is None:\n top = old_top\n\n if bottom == top:\n _api.warn_external(\n f\"Attempting to set identical bottom == top == {bottom} \"\n f\"results in singular transformations; automatically \"\n f\"expanding.\")\n swapped = bottom > top\n bottom, top = self.zaxis.get_major_locator().nonsingular(bottom, top)\n bottom, top = self.zaxis.limit_range_for_scale(bottom, top)\n if swapped:\n bottom, top = top, bottom\n self.zz_viewLim.intervalx = (bottom, top)\n\n # Mark viewlims as no longer stale without triggering an autoscale.\n for ax in self._shared_axes[\"z\"].get_siblings(self):\n ax._stale_viewlims[\"z\"] = False\n if auto is not None:\n self._autoscaleZon = bool(auto)\n\n if emit:\n self.callbacks.process('zlim_changed', self)\n # Call all of the other y-axes that are shared with this one\n for other in self._shared_axes[\"z\"].get_siblings(self):\n if other is not self:\n other.set_zlim(self.zz_viewLim.intervalx,\n emit=False, auto=auto)\n if other.figure != self.figure:\n other.figure.canvas.draw_idle()\n self.stale = True\n return bottom, top\n\n def get_xlim3d(self):\n return tuple(self.xy_viewLim.intervalx)\n get_xlim3d.__doc__ = maxes.Axes.get_xlim.__doc__\n\n def get_ylim3d(self):\n return tuple(self.xy_viewLim.intervaly)\n get_ylim3d.__doc__ = maxes.Axes.get_ylim.__doc__\n\n def get_zlim3d(self):\n \"\"\"Get 3D z limits.\"\"\"\n return tuple(self.zz_viewLim.intervalx)\n\n def get_zscale(self):\n \"\"\"\n Return the zaxis scale string %s\n\n \"\"\" % (\", \".join(mscale.get_scale_names()))\n return self.zaxis.get_scale()\n\n # We need to slightly redefine these to pass scalez=False\n # to their calls of autoscale_view.\n\n def set_xscale(self, value, **kwargs):\n self.xaxis._set_scale(value, **kwargs)\n self.autoscale_view(scaley=False, scalez=False)\n self._update_transScale()\n self.stale = True\n\n def set_yscale(self, value, **kwargs):\n self.yaxis._set_scale(value, **kwargs)\n self.autoscale_view(scalex=False, scalez=False)\n self._update_transScale()\n self.stale = True\n\n def set_zscale(self, value, **kwargs):\n self.zaxis._set_scale(value, **kwargs)\n self.autoscale_view(scalex=False, scaley=False)\n self._update_transScale()\n self.stale = True\n\n set_xscale.__doc__, set_yscale.__doc__, set_zscale.__doc__ = map(\n \"\"\"\n Set the {}-axis scale.\n\n Parameters\n ----------\n value : {{\"linear\"}}\n The axis scale type to apply. 3D axes currently only support\n linear scales; other scales yield nonsensical results.\n\n **kwargs\n Keyword arguments are nominally forwarded to the scale class, but\n none of them is applicable for linear scales.\n \"\"\".format,\n [\"x\", \"y\", \"z\"])\n\n get_zticks = _axis_method_wrapper(\"zaxis\", \"get_ticklocs\")\n set_zticks = _axis_method_wrapper(\"zaxis\", \"set_ticks\")\n get_zmajorticklabels = _axis_method_wrapper(\"zaxis\", \"get_majorticklabels\")\n get_zminorticklabels = _axis_method_wrapper(\"zaxis\", \"get_minorticklabels\")\n get_zticklabels = _axis_method_wrapper(\"zaxis\", \"get_ticklabels\")\n set_zticklabels = _axis_method_wrapper(\n \"zaxis\", \"_set_ticklabels\",\n doc_sub={\"Axis.set_ticks\": \"Axes3D.set_zticks\"})\n\n zaxis_date = _axis_method_wrapper(\"zaxis\", \"axis_date\")\n if zaxis_date.__doc__:\n zaxis_date.__doc__ += textwrap.dedent(\"\"\"\n\n Notes\n -----\n This function is merely provided for completeness, but 3D axes do not\n support dates for ticks, and so this may not work as expected.\n \"\"\")\n\n def clabel(self, *args, **kwargs):\n \"\"\"Currently not implemented for 3D axes, and returns *None*.\"\"\"\n return None\n\n def view_init(self, elev=None, azim=None, vertical_axis=\"z\"):\n \"\"\"\n Set the elevation and azimuth of the axes in degrees (not radians).\n\n This can be used to rotate the axes programmatically.\n\n Parameters\n ----------\n elev : float, default: None\n The elevation angle in the vertical plane in degrees.\n If None then the initial value as specified in the `Axes3D`\n constructor is used.\n azim : float, default: None\n The azimuth angle in the horizontal plane in degrees.\n If None then the initial value as specified in the `Axes3D`\n constructor is used.\n vertical_axis : {\"z\", \"x\", \"y\"}, default: \"z\"\n The axis to align vertically. *azim* rotates about this axis.\n \"\"\"\n\n self.dist = 10\n\n if elev is None:\n self.elev = self.initial_elev\n else:\n self.elev = elev\n\n if azim is None:\n self.azim = self.initial_azim\n else:\n self.azim = azim\n\n self._vertical_axis = _api.check_getitem(\n dict(x=0, y=1, z=2), vertical_axis=vertical_axis\n )\n\n def set_proj_type(self, proj_type):\n \"\"\"\n Set the projection type.\n\n Parameters\n ----------\n proj_type : {'persp', 'ortho'}\n \"\"\"\n self._projection = _api.check_getitem({\n 'persp': proj3d.persp_transformation,\n 'ortho': proj3d.ortho_transformation,\n }, proj_type=proj_type)\n\n def _roll_to_vertical(self, arr):\n \"\"\"Roll arrays to match the different vertical axis.\"\"\"\n return np.roll(arr, self._vertical_axis - 2)\n\n def get_proj(self):\n \"\"\"Create the projection matrix from the current viewing position.\"\"\"\n\n # Transform to uniform world coordinates 0-1, 0-1, 0-1\n box_aspect = self._roll_to_vertical(self._box_aspect)\n worldM = proj3d.world_transformation(\n *self.get_xlim3d(),\n *self.get_ylim3d(),\n *self.get_zlim3d(),\n pb_aspect=box_aspect,\n )\n\n # Look into the middle of the new coordinates:\n R = 0.5 * box_aspect\n\n # elev stores the elevation angle in the z plane\n # azim stores the azimuth angle in the x,y plane\n elev_rad = np.deg2rad(self.elev)\n azim_rad = np.deg2rad(self.azim)\n\n # Coordinates for a point that rotates around the box of data.\n # p0, p1 corresponds to rotating the box only around the\n # vertical axis.\n # p2 corresponds to rotating the box only around the horizontal\n # axis.\n p0 = np.cos(elev_rad) * np.cos(azim_rad)\n p1 = np.cos(elev_rad) * np.sin(azim_rad)\n p2 = np.sin(elev_rad)\n\n # When changing vertical axis the coordinates changes as well.\n # Roll the values to get the same behaviour as the default:\n ps = self._roll_to_vertical([p0, p1, p2])\n\n # The coordinates for the eye viewing point. The eye is looking\n # towards the middle of the box of data from a distance:\n eye = R + self.dist * ps\n\n # TODO: Is this being used somewhere? Can it be removed?\n self.eye = eye\n self.vvec = R - eye\n self.vvec = self.vvec / np.linalg.norm(self.vvec)\n\n # Define which axis should be vertical. A negative value\n # indicates the plot is upside down and therefore the values\n # have been reversed:\n V = np.zeros(3)\n V[self._vertical_axis] = -1 if abs(elev_rad) > 0.5 * np.pi else 1\n\n viewM = proj3d.view_transformation(eye, R, V)\n projM = self._projection(-self.dist, self.dist)\n M0 = np.dot(viewM, worldM)\n M = np.dot(projM, M0)\n return M\n\n def mouse_init(self, rotate_btn=1, zoom_btn=3):\n \"\"\"\n Set the mouse buttons for 3D rotation and zooming.\n\n Parameters\n ----------\n rotate_btn : int or list of int, default: 1\n The mouse button or buttons to use for 3D rotation of the axes.\n zoom_btn : int or list of int, default: 3\n The mouse button or buttons to use to zoom the 3D axes.\n \"\"\"\n self.button_pressed = None\n # coerce scalars into array-like, then convert into\n # a regular list to avoid comparisons against None\n # which breaks in recent versions of numpy.\n self._rotate_btn = np.atleast_1d(rotate_btn).tolist()\n self._zoom_btn = np.atleast_1d(zoom_btn).tolist()\n\n def disable_mouse_rotation(self):\n \"\"\"Disable mouse buttons for 3D rotation and zooming.\"\"\"\n self.mouse_init(rotate_btn=[], zoom_btn=[])\n\n def can_zoom(self):\n \"\"\"\n Return whether this axes supports the zoom box button functionality.\n\n 3D axes objects do not use the zoom box button.\n \"\"\"\n return False\n\n def can_pan(self):\n \"\"\"\n Return whether this axes supports the pan/zoom button functionality.\n\n 3D axes objects do not use the pan/zoom button.\n \"\"\"\n return False\n\n def cla(self):\n # docstring inherited.\n\n super().cla()\n self.zaxis.clear()\n\n if self._sharez is not None:\n self.zaxis.major = self._sharez.zaxis.major\n self.zaxis.minor = self._sharez.zaxis.minor\n z0, z1 = self._sharez.get_zlim()\n self.set_zlim(z0, z1, emit=False, auto=None)\n self.zaxis._set_scale(self._sharez.zaxis.get_scale())\n else:\n self.zaxis._set_scale('linear')\n try:\n self.set_zlim(0, 1)\n except TypeError:\n pass\n\n self._autoscaleZon = True\n if self._projection is proj3d.ortho_transformation:\n self._zmargin = rcParams['axes.zmargin']\n else:\n self._zmargin = 0.\n\n self.grid(rcParams['axes3d.grid'])\n\n def _button_press(self, event):\n if event.inaxes == self:\n self.button_pressed = event.button\n self.sx, self.sy = event.xdata, event.ydata\n toolbar = getattr(self.figure.canvas, \"toolbar\")\n if toolbar and toolbar._nav_stack() is None:\n self.figure.canvas.toolbar.push_current()\n\n def _button_release(self, event):\n self.button_pressed = None\n toolbar = getattr(self.figure.canvas, \"toolbar\")\n if toolbar:\n self.figure.canvas.toolbar.push_current()\n\n def _get_view(self):\n # docstring inherited\n return (self.get_xlim(), self.get_ylim(), self.get_zlim(),\n self.elev, self.azim)\n\n def _set_view(self, view):\n # docstring inherited\n xlim, ylim, zlim, elev, azim = view\n self.set(xlim=xlim, ylim=ylim, zlim=zlim)\n self.elev = elev\n self.azim = azim\n\n def format_zdata(self, z):\n \"\"\"\n Return *z* string formatted. This function will use the\n :attr:`fmt_zdata` attribute if it is callable, else will fall\n back on the zaxis major formatter\n \"\"\"\n try:\n return self.fmt_zdata(z)\n except (AttributeError, TypeError):\n func = self.zaxis.get_major_formatter().format_data_short\n val = func(z)\n return val\n\n def format_coord(self, xd, yd):\n \"\"\"\n Given the 2D view coordinates attempt to guess a 3D coordinate.\n Looks for the nearest edge to the point and then assumes that\n the point is at the same z location as the nearest point on the edge.\n \"\"\"\n\n if self.M is None:\n return ''\n\n if self.button_pressed in self._rotate_btn:\n # ignore xd and yd and display angles instead\n return (f\"azimuth={self.azim:.0f}\\N{DEGREE SIGN}, \"\n f\"elevation={self.elev:.0f}\\N{DEGREE SIGN}\"\n ).replace(\"-\", \"\\N{MINUS SIGN}\")\n\n # nearest edge\n p0, p1 = min(self.tunit_edges(),\n key=lambda edge: proj3d._line2d_seg_dist(\n edge[0], edge[1], (xd, yd)))\n\n # scale the z value to match\n x0, y0, z0 = p0\n x1, y1, z1 = p1\n d0 = np.hypot(x0-xd, y0-yd)\n d1 = np.hypot(x1-xd, y1-yd)\n dt = d0+d1\n z = d1/dt * z0 + d0/dt * z1\n\n x, y, z = proj3d.inv_transform(xd, yd, z, self.M)\n\n xs = self.format_xdata(x)\n ys = self.format_ydata(y)\n zs = self.format_zdata(z)\n return 'x=%s, y=%s, z=%s' % (xs, ys, zs)\n\n def _on_move(self, event):\n \"\"\"\n Mouse moving.\n\n By default, button-1 rotates and button-3 zooms; these buttons can be\n modified via `mouse_init`.\n \"\"\"\n\n if not self.button_pressed:\n return\n\n if self.M is None:\n return\n\n x, y = event.xdata, event.ydata\n # In case the mouse is out of bounds.\n if x is None:\n return\n\n dx, dy = x - self.sx, y - self.sy\n w = self._pseudo_w\n h = self._pseudo_h\n self.sx, self.sy = x, y\n\n # Rotation\n if self.button_pressed in self._rotate_btn:\n # rotate viewing point\n # get the x and y pixel coords\n if dx == 0 and dy == 0:\n return\n self.elev = art3d._norm_angle(self.elev - (dy/h)*180)\n self.azim = art3d._norm_angle(self.azim - (dx/w)*180)\n self.get_proj()\n self.stale = True\n self.figure.canvas.draw_idle()\n\n elif self.button_pressed == 2:\n # pan view\n # get the x and y pixel coords\n if dx == 0 and dy == 0:\n return\n minx, maxx, miny, maxy, minz, maxz = self.get_w_lims()\n dx = 1-((w - dx)/w)\n dy = 1-((h - dy)/h)\n elev, azim = np.deg2rad(self.elev), np.deg2rad(self.azim)\n # project xv, yv, zv -> xw, yw, zw\n dxx = (maxx-minx)*(dy*np.sin(elev)*np.cos(azim) + dx*np.sin(azim))\n dyy = (maxy-miny)*(-dx*np.cos(azim) + dy*np.sin(elev)*np.sin(azim))\n dzz = (maxz-minz)*(-dy*np.cos(elev))\n # pan\n self.set_xlim3d(minx + dxx, maxx + dxx)\n self.set_ylim3d(miny + dyy, maxy + dyy)\n self.set_zlim3d(minz + dzz, maxz + dzz)\n self.get_proj()\n self.figure.canvas.draw_idle()\n\n # Zoom\n elif self.button_pressed in self._zoom_btn:\n # zoom view\n # hmmm..this needs some help from clipping....\n minx, maxx, miny, maxy, minz, maxz = self.get_w_lims()\n df = 1-((h - dy)/h)\n dx = (maxx-minx)*df\n dy = (maxy-miny)*df\n dz = (maxz-minz)*df\n self.set_xlim3d(minx - dx, maxx + dx)\n self.set_ylim3d(miny - dy, maxy + dy)\n self.set_zlim3d(minz - dz, maxz + dz)\n self.get_proj()\n self.figure.canvas.draw_idle()\n\n def set_zlabel(self, zlabel, fontdict=None, labelpad=None, **kwargs):\n \"\"\"\n Set zlabel. See doc for `.set_ylabel` for description.\n \"\"\"\n if labelpad is not None:\n self.zaxis.labelpad = labelpad\n return self.zaxis.set_label_text(zlabel, fontdict, **kwargs)\n\n def get_zlabel(self):\n \"\"\"\n Get the z-label text string.\n \"\"\"\n label = self.zaxis.get_label()\n return label.get_text()\n\n # Axes rectangle characteristics\n\n def get_frame_on(self):\n \"\"\"Get whether the 3D axes panels are drawn.\"\"\"\n return self._frameon\n\n def set_frame_on(self, b):\n \"\"\"\n Set whether the 3D axes panels are drawn.\n\n Parameters\n ----------\n b : bool\n \"\"\"\n self._frameon = bool(b)\n self.stale = True\n\n @_api.rename_parameter(\"3.5\", \"b\", \"visible\")\n def grid(self, visible=True, **kwargs):\n \"\"\"\n Set / unset 3D grid.\n\n .. note::\n\n Currently, this function does not behave the same as\n :meth:`matplotlib.axes.Axes.grid`, but it is intended to\n eventually support that behavior.\n \"\"\"\n # TODO: Operate on each axes separately\n if len(kwargs):\n visible = True\n self._draw_grid = visible\n self.stale = True\n\n def locator_params(self, axis='both', tight=None, **kwargs):\n \"\"\"\n Convenience method for controlling tick locators.\n\n See :meth:`matplotlib.axes.Axes.locator_params` for full\n documentation. Note that this is for Axes3D objects,\n therefore, setting *axis* to 'both' will result in the\n parameters being set for all three axes. Also, *axis*\n can also take a value of 'z' to apply parameters to the\n z axis.\n \"\"\"\n _x = axis in ['x', 'both']\n _y = axis in ['y', 'both']\n _z = axis in ['z', 'both']\n if _x:\n self.xaxis.get_major_locator().set_params(**kwargs)\n if _y:\n self.yaxis.get_major_locator().set_params(**kwargs)\n if _z:\n self.zaxis.get_major_locator().set_params(**kwargs)\n self._request_autoscale_view(tight=tight, scalex=_x, scaley=_y,\n scalez=_z)\n\n def tick_params(self, axis='both', **kwargs):\n \"\"\"\n Convenience method for changing the appearance of ticks and\n tick labels.\n\n See :meth:`matplotlib.axes.Axes.tick_params` for more complete\n documentation.\n\n The only difference is that setting *axis* to 'both' will\n mean that the settings are applied to all three axes. Also,\n the *axis* parameter also accepts a value of 'z', which\n would mean to apply to only the z-axis.\n\n Also, because of how Axes3D objects are drawn very differently\n from regular 2D axes, some of these settings may have\n ambiguous meaning. For simplicity, the 'z' axis will\n accept settings as if it was like the 'y' axis.\n\n .. note::\n Axes3D currently ignores some of these settings.\n \"\"\"\n _api.check_in_list(['x', 'y', 'z', 'both'], axis=axis)\n if axis in ['x', 'y', 'both']:\n super().tick_params(axis, **kwargs)\n if axis in ['z', 'both']:\n zkw = dict(kwargs)\n zkw.pop('top', None)\n zkw.pop('bottom', None)\n zkw.pop('labeltop', None)\n zkw.pop('labelbottom', None)\n self.zaxis.set_tick_params(**zkw)\n\n # data limits, ticks, tick labels, and formatting\n\n def invert_zaxis(self):\n \"\"\"\n Invert the z-axis.\n \"\"\"\n bottom, top = self.get_zlim()\n self.set_zlim(top, bottom, auto=None)\n\n def zaxis_inverted(self):\n \"\"\"\n Returns True if the z-axis is inverted.\n \"\"\"\n bottom, top = self.get_zlim()\n return top < bottom\n\n def get_zbound(self):\n \"\"\"\n Return the lower and upper z-axis bounds, in increasing order.\n \"\"\"\n bottom, top = self.get_zlim()\n if bottom < top:\n return bottom, top\n else:\n return top, bottom\n\n def set_zbound(self, lower=None, upper=None):\n \"\"\"\n Set the lower and upper numerical bounds of the z-axis.\n\n This method will honor axes inversion regardless of parameter order.\n It will not change the autoscaling setting (`.get_autoscalez_on()`).\n \"\"\"\n if upper is None and np.iterable(lower):\n lower, upper = lower\n\n old_lower, old_upper = self.get_zbound()\n if lower is None:\n lower = old_lower\n if upper is None:\n upper = old_upper\n\n self.set_zlim(sorted((lower, upper),\n reverse=bool(self.zaxis_inverted())),\n auto=None)\n\n def text(self, x, y, z, s, zdir=None, **kwargs):\n \"\"\"\n Add text to the plot. kwargs will be passed on to Axes.text,\n except for the *zdir* keyword, which sets the direction to be\n used as the z direction.\n \"\"\"\n text = super().text(x, y, s, **kwargs)\n art3d.text_2d_to_3d(text, z, zdir)\n return text\n\n text3D = text\n text2D = Axes.text\n\n def plot(self, xs, ys, *args, zdir='z', **kwargs):\n \"\"\"\n Plot 2D or 3D data.\n\n Parameters\n ----------\n xs : 1D array-like\n x coordinates of vertices.\n ys : 1D array-like\n y coordinates of vertices.\n zs : float or 1D array-like\n z coordinates of vertices; either one for all points or one for\n each point.\n zdir : {'x', 'y', 'z'}, default: 'z'\n When plotting 2D data, the direction to use as z ('x', 'y' or 'z').\n **kwargs\n Other arguments are forwarded to `matplotlib.axes.Axes.plot`.\n \"\"\"\n had_data = self.has_data()\n\n # `zs` can be passed positionally or as keyword; checking whether\n # args[0] is a string matches the behavior of 2D `plot` (via\n # `_process_plot_var_args`).\n if args and not isinstance(args[0], str):\n zs, *args = args\n if 'zs' in kwargs:\n raise TypeError(\"plot() for multiple values for argument 'z'\")\n else:\n zs = kwargs.pop('zs', 0)\n\n # Match length\n zs = np.broadcast_to(zs, np.shape(xs))\n\n lines = super().plot(xs, ys, *args, **kwargs)\n for line in lines:\n art3d.line_2d_to_3d(line, zs=zs, zdir=zdir)\n\n xs, ys, zs = art3d.juggle_axes(xs, ys, zs, zdir)\n self.auto_scale_xyz(xs, ys, zs, had_data)\n return lines\n\n plot3D = plot\n\n @_api.delete_parameter(\"3.4\", \"args\", alternative=\"kwargs\")\n def plot_surface(self, X, Y, Z, *args, norm=None, vmin=None,\n vmax=None, lightsource=None, **kwargs):\n \"\"\"\n Create a surface plot.\n\n By default it will be colored in shades of a solid color, but it also\n supports colormapping by supplying the *cmap* argument.\n\n .. note::\n\n The *rcount* and *ccount* kwargs, which both default to 50,\n determine the maximum number of samples used in each direction. If\n the input data is larger, it will be downsampled (by slicing) to\n these numbers of points.\n\n .. note::\n\n To maximize rendering speed consider setting *rstride* and *cstride*\n to divisors of the number of rows minus 1 and columns minus 1\n respectively. For example, given 51 rows rstride can be any of the\n divisors of 50.\n\n Similarly, a setting of *rstride* and *cstride* equal to 1 (or\n *rcount* and *ccount* equal the number of rows and columns) can use\n the optimized path.\n\n Parameters\n ----------\n X, Y, Z : 2D arrays\n Data values.\n\n rcount, ccount : int\n Maximum number of samples used in each direction. If the input\n data is larger, it will be downsampled (by slicing) to these\n numbers of points. Defaults to 50.\n\n rstride, cstride : int\n Downsampling stride in each direction. These arguments are\n mutually exclusive with *rcount* and *ccount*. If only one of\n *rstride* or *cstride* is set, the other defaults to 10.\n\n 'classic' mode uses a default of ``rstride = cstride = 10`` instead\n of the new default of ``rcount = ccount = 50``.\n\n color : color-like\n Color of the surface patches.\n\n cmap : Colormap\n Colormap of the surface patches.\n\n facecolors : array-like of colors.\n Colors of each individual patch.\n\n norm : Normalize\n Normalization for the colormap.\n\n vmin, vmax : float\n Bounds for the normalization.\n\n shade : bool, default: True\n Whether to shade the facecolors. Shading is always disabled when\n *cmap* is specified.\n\n lightsource : `~matplotlib.colors.LightSource`\n The lightsource to use when *shade* is True.\n\n **kwargs\n Other arguments are forwarded to `.Poly3DCollection`.\n \"\"\"\n\n had_data = self.has_data()\n\n if Z.ndim != 2:\n raise ValueError(\"Argument Z must be 2-dimensional.\")\n\n Z = cbook._to_unmasked_float_array(Z)\n X, Y, Z = np.broadcast_arrays(X, Y, Z)\n rows, cols = Z.shape\n\n has_stride = 'rstride' in kwargs or 'cstride' in kwargs\n has_count = 'rcount' in kwargs or 'ccount' in kwargs\n\n if has_stride and has_count:\n raise ValueError(\"Cannot specify both stride and count arguments\")\n\n rstride = kwargs.pop('rstride', 10)\n cstride = kwargs.pop('cstride', 10)\n rcount = kwargs.pop('rcount', 50)\n ccount = kwargs.pop('ccount', 50)\n\n if rcParams['_internal.classic_mode']:\n # Strides have priority over counts in classic mode.\n # So, only compute strides from counts\n # if counts were explicitly given\n compute_strides = has_count\n else:\n # If the strides are provided then it has priority.\n # Otherwise, compute the strides from the counts.\n compute_strides = not has_stride\n\n if compute_strides:\n rstride = int(max(np.ceil(rows / rcount), 1))\n cstride = int(max(np.ceil(cols / ccount), 1))\n\n if 'facecolors' in kwargs:\n fcolors = kwargs.pop('facecolors')\n else:\n color = kwargs.pop('color', None)\n if color is None:\n color = self._get_lines.get_next_color()\n color = np.array(mcolors.to_rgba(color))\n fcolors = None\n\n cmap = kwargs.get('cmap', None)\n shade = kwargs.pop('shade', cmap is None)\n if shade is None:\n _api.warn_deprecated(\n \"3.1\",\n message=\"Passing shade=None to Axes3D.plot_surface() is \"\n \"deprecated since matplotlib 3.1 and will change its \"\n \"semantic or raise an error in matplotlib 3.3. \"\n \"Please use shade=False instead.\")\n\n colset = [] # the sampled facecolor\n if (rows - 1) % rstride == 0 and \\\n (cols - 1) % cstride == 0 and \\\n fcolors is None:\n polys = np.stack(\n [cbook._array_patch_perimeters(a, rstride, cstride)\n for a in (X, Y, Z)],\n axis=-1)\n else:\n # evenly spaced, and including both endpoints\n row_inds = list(range(0, rows-1, rstride)) + [rows-1]\n col_inds = list(range(0, cols-1, cstride)) + [cols-1]\n\n polys = []\n for rs, rs_next in zip(row_inds[:-1], row_inds[1:]):\n for cs, cs_next in zip(col_inds[:-1], col_inds[1:]):\n ps = [\n # +1 ensures we share edges between polygons\n cbook._array_perimeter(a[rs:rs_next+1, cs:cs_next+1])\n for a in (X, Y, Z)\n ]\n # ps = np.stack(ps, axis=-1)\n ps = np.array(ps).T\n polys.append(ps)\n\n if fcolors is not None:\n colset.append(fcolors[rs][cs])\n\n # In cases where there are NaNs in the data (possibly from masked\n # arrays), artifacts can be introduced. Here check whether NaNs exist\n # and remove the entries if so\n if not isinstance(polys, np.ndarray) or np.isnan(polys).any():\n new_polys = []\n new_colset = []\n\n # Depending on fcolors, colset is either an empty list or has as\n # many elements as polys. In the former case new_colset results in\n # a list with None entries, that is discarded later.\n for p, col in itertools.zip_longest(polys, colset):\n new_poly = np.array(p)[~np.isnan(p).any(axis=1)]\n if len(new_poly):\n new_polys.append(new_poly)\n new_colset.append(col)\n\n # Replace previous polys and, if fcolors is not None, colset\n polys = new_polys\n if fcolors is not None:\n colset = new_colset\n\n # note that the striding causes some polygons to have more coordinates\n # than others\n polyc = art3d.Poly3DCollection(polys, *args, **kwargs)\n\n if fcolors is not None:\n if shade:\n colset = self._shade_colors(\n colset, self._generate_normals(polys), lightsource)\n polyc.set_facecolors(colset)\n polyc.set_edgecolors(colset)\n elif cmap:\n # can't always vectorize, because polys might be jagged\n if isinstance(polys, np.ndarray):\n avg_z = polys[..., 2].mean(axis=-1)\n else:\n avg_z = np.array([ps[:, 2].mean() for ps in polys])\n polyc.set_array(avg_z)\n if vmin is not None or vmax is not None:\n polyc.set_clim(vmin, vmax)\n if norm is not None:\n polyc.set_norm(norm)\n else:\n if shade:\n colset = self._shade_colors(\n color, self._generate_normals(polys), lightsource)\n else:\n colset = color\n polyc.set_facecolors(colset)\n\n self.add_collection(polyc)\n self.auto_scale_xyz(X, Y, Z, had_data)\n\n return polyc\n\n def _generate_normals(self, polygons):\n \"\"\"\n Compute the normals of a list of polygons.\n\n Normals point towards the viewer for a face with its vertices in\n counterclockwise order, following the right hand rule.\n\n Uses three points equally spaced around the polygon.\n This normal of course might not make sense for polygons with more than\n three points not lying in a plane, but it's a plausible and fast\n approximation.\n\n Parameters\n ----------\n polygons : list of (M_i, 3) array-like, or (..., M, 3) array-like\n A sequence of polygons to compute normals for, which can have\n varying numbers of vertices. If the polygons all have the same\n number of vertices and array is passed, then the operation will\n be vectorized.\n\n Returns\n -------\n normals : (..., 3) array\n A normal vector estimated for the polygon.\n \"\"\"\n if isinstance(polygons, np.ndarray):\n # optimization: polygons all have the same number of points, so can\n # vectorize\n n = polygons.shape[-2]\n i1, i2, i3 = 0, n//3, 2*n//3\n v1 = polygons[..., i1, :] - polygons[..., i2, :]\n v2 = polygons[..., i2, :] - polygons[..., i3, :]\n else:\n # The subtraction doesn't vectorize because polygons is jagged.\n v1 = np.empty((len(polygons), 3))\n v2 = np.empty((len(polygons), 3))\n for poly_i, ps in enumerate(polygons):\n n = len(ps)\n i1, i2, i3 = 0, n//3, 2*n//3\n v1[poly_i, :] = ps[i1, :] - ps[i2, :]\n v2[poly_i, :] = ps[i2, :] - ps[i3, :]\n return np.cross(v1, v2)\n\n def _shade_colors(self, color, normals, lightsource=None):\n \"\"\"\n Shade *color* using normal vectors given by *normals*.\n *color* can also be an array of the same length as *normals*.\n \"\"\"\n if lightsource is None:\n # chosen for backwards-compatibility\n lightsource = mcolors.LightSource(azdeg=225, altdeg=19.4712)\n\n with np.errstate(invalid=\"ignore\"):\n shade = ((normals / np.linalg.norm(normals, axis=1, keepdims=True))\n @ lightsource.direction)\n mask = ~np.isnan(shade)\n\n if mask.any():\n # convert dot product to allowed shading fractions\n in_norm = mcolors.Normalize(-1, 1)\n out_norm = mcolors.Normalize(0.3, 1).inverse\n\n def norm(x):\n return out_norm(in_norm(x))\n\n shade[~mask] = 0\n\n color = mcolors.to_rgba_array(color)\n # shape of color should be (M, 4) (where M is number of faces)\n # shape of shade should be (M,)\n # colors should have final shape of (M, 4)\n alpha = color[:, 3]\n colors = norm(shade)[:, np.newaxis] * color\n colors[:, 3] = alpha\n else:\n colors = np.asanyarray(color).copy()\n\n return colors\n\n @_api.delete_parameter(\"3.4\", \"args\", alternative=\"kwargs\")\n def plot_wireframe(self, X, Y, Z, *args, **kwargs):\n \"\"\"\n Plot a 3D wireframe.\n\n .. note::\n\n The *rcount* and *ccount* kwargs, which both default to 50,\n determine the maximum number of samples used in each direction. If\n the input data is larger, it will be downsampled (by slicing) to\n these numbers of points.\n\n Parameters\n ----------\n X, Y, Z : 2D arrays\n Data values.\n\n rcount, ccount : int\n Maximum number of samples used in each direction. If the input\n data is larger, it will be downsampled (by slicing) to these\n numbers of points. Setting a count to zero causes the data to be\n not sampled in the corresponding direction, producing a 3D line\n plot rather than a wireframe plot. Defaults to 50.\n\n rstride, cstride : int\n Downsampling stride in each direction. These arguments are\n mutually exclusive with *rcount* and *ccount*. If only one of\n *rstride* or *cstride* is set, the other defaults to 1. Setting a\n stride to zero causes the data to be not sampled in the\n corresponding direction, producing a 3D line plot rather than a\n wireframe plot.\n\n 'classic' mode uses a default of ``rstride = cstride = 1`` instead\n of the new default of ``rcount = ccount = 50``.\n\n **kwargs\n Other arguments are forwarded to `.Line3DCollection`.\n \"\"\"\n\n had_data = self.has_data()\n if Z.ndim != 2:\n raise ValueError(\"Argument Z must be 2-dimensional.\")\n # FIXME: Support masked arrays\n X, Y, Z = np.broadcast_arrays(X, Y, Z)\n rows, cols = Z.shape\n\n has_stride = 'rstride' in kwargs or 'cstride' in kwargs\n has_count = 'rcount' in kwargs or 'ccount' in kwargs\n\n if has_stride and has_count:\n raise ValueError(\"Cannot specify both stride and count arguments\")\n\n rstride = kwargs.pop('rstride', 1)\n cstride = kwargs.pop('cstride', 1)\n rcount = kwargs.pop('rcount', 50)\n ccount = kwargs.pop('ccount', 50)\n\n if rcParams['_internal.classic_mode']:\n # Strides have priority over counts in classic mode.\n # So, only compute strides from counts\n # if counts were explicitly given\n if has_count:\n rstride = int(max(np.ceil(rows / rcount), 1)) if rcount else 0\n cstride = int(max(np.ceil(cols / ccount), 1)) if ccount else 0\n else:\n # If the strides are provided then it has priority.\n # Otherwise, compute the strides from the counts.\n if not has_stride:\n rstride = int(max(np.ceil(rows / rcount), 1)) if rcount else 0\n cstride = int(max(np.ceil(cols / ccount), 1)) if ccount else 0\n\n # We want two sets of lines, one running along the \"rows\" of\n # Z and another set of lines running along the \"columns\" of Z.\n # This transpose will make it easy to obtain the columns.\n tX, tY, tZ = np.transpose(X), np.transpose(Y), np.transpose(Z)\n\n if rstride:\n rii = list(range(0, rows, rstride))\n # Add the last index only if needed\n if rows > 0 and rii[-1] != (rows - 1):\n rii += [rows-1]\n else:\n rii = []\n if cstride:\n cii = list(range(0, cols, cstride))\n # Add the last index only if needed\n if cols > 0 and cii[-1] != (cols - 1):\n cii += [cols-1]\n else:\n cii = []\n\n if rstride == 0 and cstride == 0:\n raise ValueError(\"Either rstride or cstride must be non zero\")\n\n # If the inputs were empty, then just\n # reset everything.\n if Z.size == 0:\n rii = []\n cii = []\n\n xlines = [X[i] for i in rii]\n ylines = [Y[i] for i in rii]\n zlines = [Z[i] for i in rii]\n\n txlines = [tX[i] for i in cii]\n tylines = [tY[i] for i in cii]\n tzlines = [tZ[i] for i in cii]\n\n lines = ([list(zip(xl, yl, zl))\n for xl, yl, zl in zip(xlines, ylines, zlines)]\n + [list(zip(xl, yl, zl))\n for xl, yl, zl in zip(txlines, tylines, tzlines)])\n\n linec = art3d.Line3DCollection(lines, *args, **kwargs)\n self.add_collection(linec)\n self.auto_scale_xyz(X, Y, Z, had_data)\n\n return linec\n\n def plot_trisurf(self, *args, color=None, norm=None, vmin=None, vmax=None,\n lightsource=None, **kwargs):\n \"\"\"\n Plot a triangulated surface.\n\n The (optional) triangulation can be specified in one of two ways;\n either::\n\n plot_trisurf(triangulation, ...)\n\n where triangulation is a `~matplotlib.tri.Triangulation` object, or::\n\n plot_trisurf(X, Y, ...)\n plot_trisurf(X, Y, triangles, ...)\n plot_trisurf(X, Y, triangles=triangles, ...)\n\n in which case a Triangulation object will be created. See\n `.Triangulation` for a explanation of these possibilities.\n\n The remaining arguments are::\n\n plot_trisurf(..., Z)\n\n where *Z* is the array of values to contour, one per point\n in the triangulation.\n\n Parameters\n ----------\n X, Y, Z : array-like\n Data values as 1D arrays.\n color\n Color of the surface patches.\n cmap\n A colormap for the surface patches.\n norm : Normalize\n An instance of Normalize to map values to colors.\n vmin, vmax : float, default: None\n Minimum and maximum value to map.\n shade : bool, default: True\n Whether to shade the facecolors. Shading is always disabled when\n *cmap* is specified.\n lightsource : `~matplotlib.colors.LightSource`\n The lightsource to use when *shade* is True.\n **kwargs\n All other arguments are passed on to\n :class:`~mpl_toolkits.mplot3d.art3d.Poly3DCollection`\n\n Examples\n --------\n .. plot:: gallery/mplot3d/trisurf3d.py\n .. plot:: gallery/mplot3d/trisurf3d_2.py\n \"\"\"\n\n had_data = self.has_data()\n\n # TODO: Support custom face colours\n if color is None:\n color = self._get_lines.get_next_color()\n color = np.array(mcolors.to_rgba(color))\n\n cmap = kwargs.get('cmap', None)\n shade = kwargs.pop('shade', cmap is None)\n\n tri, args, kwargs = \\\n Triangulation.get_from_args_and_kwargs(*args, **kwargs)\n try:\n z = kwargs.pop('Z')\n except KeyError:\n # We do this so Z doesn't get passed as an arg to PolyCollection\n z, *args = args\n z = np.asarray(z)\n\n triangles = tri.get_masked_triangles()\n xt = tri.x[triangles]\n yt = tri.y[triangles]\n zt = z[triangles]\n verts = np.stack((xt, yt, zt), axis=-1)\n\n polyc = art3d.Poly3DCollection(verts, *args, **kwargs)\n\n if cmap:\n # average over the three points of each triangle\n avg_z = verts[:, :, 2].mean(axis=1)\n polyc.set_array(avg_z)\n if vmin is not None or vmax is not None:\n polyc.set_clim(vmin, vmax)\n if norm is not None:\n polyc.set_norm(norm)\n else:\n if shade:\n normals = self._generate_normals(verts)\n colset = self._shade_colors(color, normals, lightsource)\n else:\n colset = color\n polyc.set_facecolors(colset)\n\n self.add_collection(polyc)\n self.auto_scale_xyz(tri.x, tri.y, z, had_data)\n\n return polyc\n\n def _3d_extend_contour(self, cset, stride=5):\n \"\"\"\n Extend a contour in 3D by creating\n \"\"\"\n\n levels = cset.levels\n colls = cset.collections\n dz = (levels[1] - levels[0]) / 2\n\n for z, linec in zip(levels, colls):\n paths = linec.get_paths()\n if not paths:\n continue\n topverts = art3d._paths_to_3d_segments(paths, z - dz)\n botverts = art3d._paths_to_3d_segments(paths, z + dz)\n\n color = linec.get_edgecolor()[0]\n\n polyverts = []\n normals = []\n nsteps = round(len(topverts[0]) / stride)\n if nsteps <= 1:\n if len(topverts[0]) > 1:\n nsteps = 2\n else:\n continue\n\n stepsize = (len(topverts[0]) - 1) / (nsteps - 1)\n for i in range(int(round(nsteps)) - 1):\n i1 = int(round(i * stepsize))\n i2 = int(round((i + 1) * stepsize))\n polyverts.append([topverts[0][i1],\n topverts[0][i2],\n botverts[0][i2],\n botverts[0][i1]])\n\n # all polygons have 4 vertices, so vectorize\n polyverts = np.array(polyverts)\n normals = self._generate_normals(polyverts)\n\n colors = self._shade_colors(color, normals)\n colors2 = self._shade_colors(color, normals)\n polycol = art3d.Poly3DCollection(polyverts,\n facecolors=colors,\n edgecolors=colors2)\n polycol.set_sort_zpos(z)\n self.add_collection3d(polycol)\n\n for col in colls:\n col.remove()\n\n def add_contour_set(\n self, cset, extend3d=False, stride=5, zdir='z', offset=None):\n zdir = '-' + zdir\n if extend3d:\n self._3d_extend_contour(cset, stride)\n else:\n for z, linec in zip(cset.levels, cset.collections):\n if offset is not None:\n z = offset\n art3d.line_collection_2d_to_3d(linec, z, zdir=zdir)\n\n def add_contourf_set(self, cset, zdir='z', offset=None):\n self._add_contourf_set(cset, zdir=zdir, offset=offset)\n\n def _add_contourf_set(self, cset, zdir='z', offset=None):\n \"\"\"\n Returns\n -------\n levels : numpy.ndarray\n Levels at which the filled contours are added.\n \"\"\"\n zdir = '-' + zdir\n\n midpoints = cset.levels[:-1] + np.diff(cset.levels) / 2\n # Linearly interpolate to get levels for any extensions\n if cset._extend_min:\n min_level = cset.levels[0] - np.diff(cset.levels[:2]) / 2\n midpoints = np.insert(midpoints, 0, min_level)\n if cset._extend_max:\n max_level = cset.levels[-1] + np.diff(cset.levels[-2:]) / 2\n midpoints = np.append(midpoints, max_level)\n\n for z, linec in zip(midpoints, cset.collections):\n if offset is not None:\n z = offset\n art3d.poly_collection_2d_to_3d(linec, z, zdir=zdir)\n linec.set_sort_zpos(z)\n return midpoints\n\n @_preprocess_data()\n def contour(self, X, Y, Z, *args,\n extend3d=False, stride=5, zdir='z', offset=None, **kwargs):\n \"\"\"\n Create a 3D contour plot.\n\n Parameters\n ----------\n X, Y, Z : array-like,\n Input data. See `~matplotlib.axes.Axes.contour` for acceptable\n data shapes.\n extend3d : bool, default: False\n Whether to extend contour in 3D.\n stride : int\n Step size for extending contour.\n zdir : {'x', 'y', 'z'}, default: 'z'\n The direction to use.\n offset : float, optional\n If specified, plot a projection of the contour lines at this\n position in a plane normal to zdir.\n data : indexable object, optional\n DATA_PARAMETER_PLACEHOLDER\n\n *args, **kwargs\n Other arguments are forwarded to `matplotlib.axes.Axes.contour`.\n\n Returns\n -------\n matplotlib.contour.QuadContourSet\n \"\"\"\n had_data = self.has_data()\n\n jX, jY, jZ = art3d.rotate_axes(X, Y, Z, zdir)\n cset = super().contour(jX, jY, jZ, *args, **kwargs)\n self.add_contour_set(cset, extend3d, stride, zdir, offset)\n\n self.auto_scale_xyz(X, Y, Z, had_data)\n return cset\n\n contour3D = contour\n\n @_preprocess_data()\n def tricontour(self, *args,\n extend3d=False, stride=5, zdir='z', offset=None, **kwargs):\n \"\"\"\n Create a 3D contour plot.\n\n .. note::\n This method currently produces incorrect output due to a\n longstanding bug in 3D PolyCollection rendering.\n\n Parameters\n ----------\n X, Y, Z : array-like\n Input data. See `~matplotlib.axes.Axes.tricontour` for acceptable\n data shapes.\n extend3d : bool, default: False\n Whether to extend contour in 3D.\n stride : int\n Step size for extending contour.\n zdir : {'x', 'y', 'z'}, default: 'z'\n The direction to use.\n offset : float, optional\n If specified, plot a projection of the contour lines at this\n position in a plane normal to zdir.\n data : indexable object, optional\n DATA_PARAMETER_PLACEHOLDER\n *args, **kwargs\n Other arguments are forwarded to `matplotlib.axes.Axes.tricontour`.\n\n Returns\n -------\n matplotlib.tri.tricontour.TriContourSet\n \"\"\"\n had_data = self.has_data()\n\n tri, args, kwargs = Triangulation.get_from_args_and_kwargs(\n *args, **kwargs)\n X = tri.x\n Y = tri.y\n if 'Z' in kwargs:\n Z = kwargs.pop('Z')\n else:\n # We do this so Z doesn't get passed as an arg to Axes.tricontour\n Z, *args = args\n\n jX, jY, jZ = art3d.rotate_axes(X, Y, Z, zdir)\n tri = Triangulation(jX, jY, tri.triangles, tri.mask)\n\n cset = super().tricontour(tri, jZ, *args, **kwargs)\n self.add_contour_set(cset, extend3d, stride, zdir, offset)\n\n self.auto_scale_xyz(X, Y, Z, had_data)\n return cset\n\n def _auto_scale_contourf(self, X, Y, Z, zdir, levels, had_data):\n # Autoscale in the zdir based on the levels added, which are\n # different from data range if any contour extensions are present\n dim_vals = {'x': X, 'y': Y, 'z': Z, zdir: levels}\n # Input data and levels have different sizes, but auto_scale_xyz\n # expected same-size input, so manually take min/max limits\n limits = [(np.nanmin(dim_vals[dim]), np.nanmax(dim_vals[dim]))\n for dim in ['x', 'y', 'z']]\n self.auto_scale_xyz(*limits, had_data)\n\n @_preprocess_data()\n def contourf(self, X, Y, Z, *args, zdir='z', offset=None, **kwargs):\n \"\"\"\n Create a 3D filled contour plot.\n\n Parameters\n ----------\n X, Y, Z : array-like\n Input data. See `~matplotlib.axes.Axes.contourf` for acceptable\n data shapes.\n zdir : {'x', 'y', 'z'}, default: 'z'\n The direction to use.\n offset : float, optional\n If specified, plot a projection of the contour lines at this\n position in a plane normal to zdir.\n data : indexable object, optional\n DATA_PARAMETER_PLACEHOLDER\n *args, **kwargs\n Other arguments are forwarded to `matplotlib.axes.Axes.contourf`.\n\n Returns\n -------\n matplotlib.contour.QuadContourSet\n \"\"\"\n had_data = self.has_data()\n\n jX, jY, jZ = art3d.rotate_axes(X, Y, Z, zdir)\n cset = super().contourf(jX, jY, jZ, *args, **kwargs)\n levels = self._add_contourf_set(cset, zdir, offset)\n\n self._auto_scale_contourf(X, Y, Z, zdir, levels, had_data)\n return cset\n\n contourf3D = contourf\n\n @_preprocess_data()\n def tricontourf(self, *args, zdir='z', offset=None, **kwargs):\n \"\"\"\n Create a 3D filled contour plot.\n\n .. note::\n This method currently produces incorrect output due to a\n longstanding bug in 3D PolyCollection rendering.\n\n Parameters\n ----------\n X, Y, Z : array-like\n Input data. See `~matplotlib.axes.Axes.tricontourf` for acceptable\n data shapes.\n zdir : {'x', 'y', 'z'}, default: 'z'\n The direction to use.\n offset : float, optional\n If specified, plot a projection of the contour lines at this\n position in a plane normal to zdir.\n data : indexable object, optional\n DATA_PARAMETER_PLACEHOLDER\n *args, **kwargs\n Other arguments are forwarded to\n `matplotlib.axes.Axes.tricontourf`.\n\n Returns\n -------\n matplotlib.tri.tricontour.TriContourSet\n \"\"\"\n had_data = self.has_data()\n\n tri, args, kwargs = Triangulation.get_from_args_and_kwargs(\n *args, **kwargs)\n X = tri.x\n Y = tri.y\n if 'Z' in kwargs:\n Z = kwargs.pop('Z')\n else:\n # We do this so Z doesn't get passed as an arg to Axes.tricontourf\n Z, *args = args\n\n jX, jY, jZ = art3d.rotate_axes(X, Y, Z, zdir)\n tri = Triangulation(jX, jY, tri.triangles, tri.mask)\n\n cset = super().tricontourf(tri, jZ, *args, **kwargs)\n levels = self._add_contourf_set(cset, zdir, offset)\n\n self._auto_scale_contourf(X, Y, Z, zdir, levels, had_data)\n return cset\n\n def add_collection3d(self, col, zs=0, zdir='z'):\n \"\"\"\n Add a 3D collection object to the plot.\n\n 2D collection types are converted to a 3D version by\n modifying the object and adding z coordinate information.\n\n Supported are:\n\n - PolyCollection\n - LineCollection\n - PatchCollection\n \"\"\"\n zvals = np.atleast_1d(zs)\n zsortval = (np.min(zvals) if zvals.size\n else 0) # FIXME: arbitrary default\n\n # FIXME: use issubclass() (although, then a 3D collection\n # object would also pass.) Maybe have a collection3d\n # abstract class to test for and exclude?\n if type(col) is mcoll.PolyCollection:\n art3d.poly_collection_2d_to_3d(col, zs=zs, zdir=zdir)\n col.set_sort_zpos(zsortval)\n elif type(col) is mcoll.LineCollection:\n art3d.line_collection_2d_to_3d(col, zs=zs, zdir=zdir)\n col.set_sort_zpos(zsortval)\n elif type(col) is mcoll.PatchCollection:\n art3d.patch_collection_2d_to_3d(col, zs=zs, zdir=zdir)\n col.set_sort_zpos(zsortval)\n\n collection = super().add_collection(col)\n return collection\n\n @_preprocess_data(replace_names=[\"xs\", \"ys\", \"zs\", \"s\",\n \"edgecolors\", \"c\", \"facecolor\",\n \"facecolors\", \"color\"])\n def scatter(self, xs, ys, zs=0, zdir='z', s=20, c=None, depthshade=True,\n *args, **kwargs):\n \"\"\"\n Create a scatter plot.\n\n Parameters\n ----------\n xs, ys : array-like\n The data positions.\n zs : float or array-like, default: 0\n The z-positions. Either an array of the same length as *xs* and\n *ys* or a single value to place all points in the same plane.\n zdir : {'x', 'y', 'z', '-x', '-y', '-z'}, default: 'z'\n The axis direction for the *zs*. This is useful when plotting 2D\n data on a 3D Axes. The data must be passed as *xs*, *ys*. Setting\n *zdir* to 'y' then plots the data to the x-z-plane.\n\n See also :doc:`/gallery/mplot3d/2dcollections3d`.\n\n s : float or array-like, default: 20\n The marker size in points**2. Either an array of the same length\n as *xs* and *ys* or a single value to make all markers the same\n size.\n c : color, sequence, or sequence of colors, optional\n The marker color. Possible values:\n\n - A single color format string.\n - A sequence of colors of length n.\n - A sequence of n numbers to be mapped to colors using *cmap* and\n *norm*.\n - A 2D array in which the rows are RGB or RGBA.\n\n For more details see the *c* argument of `~.axes.Axes.scatter`.\n depthshade : bool, default: True\n Whether to shade the scatter markers to give the appearance of\n depth. Each call to ``scatter()`` will perform its depthshading\n independently.\n data : indexable object, optional\n DATA_PARAMETER_PLACEHOLDER\n **kwargs\n All other arguments are passed on to `~.axes.Axes.scatter`.\n\n Returns\n -------\n paths : `~matplotlib.collections.PathCollection`\n \"\"\"\n\n had_data = self.has_data()\n zs_orig = zs\n\n xs, ys, zs = np.broadcast_arrays(\n *[np.ravel(np.ma.filled(t, np.nan)) for t in [xs, ys, zs]])\n s = np.ma.ravel(s) # This doesn't have to match x, y in size.\n\n xs, ys, zs, s, c = cbook.delete_masked_points(xs, ys, zs, s, c)\n\n # For xs and ys, 2D scatter() will do the copying.\n if np.may_share_memory(zs_orig, zs): # Avoid unnecessary copies.\n zs = zs.copy()\n\n patches = super().scatter(xs, ys, s=s, c=c, *args, **kwargs)\n art3d.patch_collection_2d_to_3d(patches, zs=zs, zdir=zdir,\n depthshade=depthshade)\n\n if self._zmargin < 0.05 and xs.size > 0:\n self.set_zmargin(0.05)\n\n self.auto_scale_xyz(xs, ys, zs, had_data)\n\n return patches\n\n scatter3D = scatter\n\n @_preprocess_data()\n def bar(self, left, height, zs=0, zdir='z', *args, **kwargs):\n \"\"\"\n Add 2D bar(s).\n\n Parameters\n ----------\n left : 1D array-like\n The x coordinates of the left sides of the bars.\n height : 1D array-like\n The height of the bars.\n zs : float or 1D array-like\n Z coordinate of bars; if a single value is specified, it will be\n used for all bars.\n zdir : {'x', 'y', 'z'}, default: 'z'\n When plotting 2D data, the direction to use as z ('x', 'y' or 'z').\n data : indexable object, optional\n DATA_PARAMETER_PLACEHOLDER\n **kwargs\n Other arguments are forwarded to `matplotlib.axes.Axes.bar`.\n\n Returns\n -------\n mpl_toolkits.mplot3d.art3d.Patch3DCollection\n \"\"\"\n had_data = self.has_data()\n\n patches = super().bar(left, height, *args, **kwargs)\n\n zs = np.broadcast_to(zs, len(left))\n\n verts = []\n verts_zs = []\n for p, z in zip(patches, zs):\n vs = art3d._get_patch_verts(p)\n verts += vs.tolist()\n verts_zs += [z] * len(vs)\n art3d.patch_2d_to_3d(p, z, zdir)\n if 'alpha' in kwargs:\n p.set_alpha(kwargs['alpha'])\n\n if len(verts) > 0:\n # the following has to be skipped if verts is empty\n # NOTE: Bugs could still occur if len(verts) > 0,\n # but the \"2nd dimension\" is empty.\n xs, ys = zip(*verts)\n else:\n xs, ys = [], []\n\n xs, ys, verts_zs = art3d.juggle_axes(xs, ys, verts_zs, zdir)\n self.auto_scale_xyz(xs, ys, verts_zs, had_data)\n\n return patches\n\n @_preprocess_data()\n def bar3d(self, x, y, z, dx, dy, dz, color=None,\n zsort='average', shade=True, lightsource=None, *args, **kwargs):\n \"\"\"\n Generate a 3D barplot.\n\n This method creates three dimensional barplot where the width,\n depth, height, and color of the bars can all be uniquely set.\n\n Parameters\n ----------\n x, y, z : array-like\n The coordinates of the anchor point of the bars.\n\n dx, dy, dz : float or array-like\n The width, depth, and height of the bars, respectively.\n\n color : sequence of colors, optional\n The color of the bars can be specified globally or\n individually. This parameter can be:\n\n - A single color, to color all bars the same color.\n - An array of colors of length N bars, to color each bar\n independently.\n - An array of colors of length 6, to color the faces of the\n bars similarly.\n - An array of colors of length 6 * N bars, to color each face\n independently.\n\n When coloring the faces of the boxes specifically, this is\n the order of the coloring:\n\n 1. -Z (bottom of box)\n 2. +Z (top of box)\n 3. -Y\n 4. +Y\n 5. -X\n 6. +X\n\n zsort : str, optional\n The z-axis sorting scheme passed onto `~.art3d.Poly3DCollection`\n\n shade : bool, default: True\n When true, this shades the dark sides of the bars (relative\n to the plot's source of light).\n\n lightsource : `~matplotlib.colors.LightSource`\n The lightsource to use when *shade* is True.\n\n data : indexable object, optional\n DATA_PARAMETER_PLACEHOLDER\n\n **kwargs\n Any additional keyword arguments are passed onto\n `~.art3d.Poly3DCollection`.\n\n Returns\n -------\n collection : `~.art3d.Poly3DCollection`\n A collection of three dimensional polygons representing\n the bars.\n \"\"\"\n\n had_data = self.has_data()\n\n x, y, z, dx, dy, dz = np.broadcast_arrays(\n np.atleast_1d(x), y, z, dx, dy, dz)\n minx = np.min(x)\n maxx = np.max(x + dx)\n miny = np.min(y)\n maxy = np.max(y + dy)\n minz = np.min(z)\n maxz = np.max(z + dz)\n\n # shape (6, 4, 3)\n # All faces are oriented facing outwards - when viewed from the\n # outside, their vertices are in a counterclockwise ordering.\n cuboid = np.array([\n # -z\n (\n (0, 0, 0),\n (0, 1, 0),\n (1, 1, 0),\n (1, 0, 0),\n ),\n # +z\n (\n (0, 0, 1),\n (1, 0, 1),\n (1, 1, 1),\n (0, 1, 1),\n ),\n # -y\n (\n (0, 0, 0),\n (1, 0, 0),\n (1, 0, 1),\n (0, 0, 1),\n ),\n # +y\n (\n (0, 1, 0),\n (0, 1, 1),\n (1, 1, 1),\n (1, 1, 0),\n ),\n # -x\n (\n (0, 0, 0),\n (0, 0, 1),\n (0, 1, 1),\n (0, 1, 0),\n ),\n # +x\n (\n (1, 0, 0),\n (1, 1, 0),\n (1, 1, 1),\n (1, 0, 1),\n ),\n ])\n\n # indexed by [bar, face, vertex, coord]\n polys = np.empty(x.shape + cuboid.shape)\n\n # handle each coordinate separately\n for i, p, dp in [(0, x, dx), (1, y, dy), (2, z, dz)]:\n p = p[..., np.newaxis, np.newaxis]\n dp = dp[..., np.newaxis, np.newaxis]\n polys[..., i] = p + dp * cuboid[..., i]\n\n # collapse the first two axes\n polys = polys.reshape((-1,) + polys.shape[2:])\n\n facecolors = []\n if color is None:\n color = [self._get_patches_for_fill.get_next_color()]\n\n color = list(mcolors.to_rgba_array(color))\n\n if len(color) == len(x):\n # bar colors specified, need to expand to number of faces\n for c in color:\n facecolors.extend([c] * 6)\n else:\n # a single color specified, or face colors specified explicitly\n facecolors = color\n if len(facecolors) < len(x):\n facecolors *= (6 * len(x))\n\n if shade:\n normals = self._generate_normals(polys)\n sfacecolors = self._shade_colors(facecolors, normals, lightsource)\n else:\n sfacecolors = facecolors\n\n col = art3d.Poly3DCollection(polys,\n zsort=zsort,\n facecolor=sfacecolors,\n *args, **kwargs)\n self.add_collection(col)\n\n self.auto_scale_xyz((minx, maxx), (miny, maxy), (minz, maxz), had_data)\n\n return col\n\n def set_title(self, label, fontdict=None, loc='center', **kwargs):\n # docstring inherited\n ret = super().set_title(label, fontdict=fontdict, loc=loc, **kwargs)\n (x, y) = self.title.get_position()\n self.title.set_y(0.92 * y)\n return ret\n\n @_preprocess_data()\n def quiver(self, *args,\n length=1, arrow_length_ratio=.3, pivot='tail', normalize=False,\n **kwargs):\n \"\"\"\n ax.quiver(X, Y, Z, U, V, W, /, length=1, arrow_length_ratio=.3, \\\npivot='tail', normalize=False, **kwargs)\n\n Plot a 3D field of arrows.\n\n The arguments could be array-like or scalars, so long as they\n they can be broadcast together. The arguments can also be\n masked arrays. If an element in any of argument is masked, then\n that corresponding quiver element will not be plotted.\n\n Parameters\n ----------\n X, Y, Z : array-like\n The x, y and z coordinates of the arrow locations (default is\n tail of arrow; see *pivot* kwarg).\n\n U, V, W : array-like\n The x, y and z components of the arrow vectors.\n\n length : float, default: 1\n The length of each quiver.\n\n arrow_length_ratio : float, default: 0.3\n The ratio of the arrow head with respect to the quiver.\n\n pivot : {'tail', 'middle', 'tip'}, default: 'tail'\n The part of the arrow that is at the grid point; the arrow\n rotates about this point, hence the name *pivot*.\n\n normalize : bool, default: False\n Whether all arrows are normalized to have the same length, or keep\n the lengths defined by *u*, *v*, and *w*.\n\n data : indexable object, optional\n DATA_PARAMETER_PLACEHOLDER\n\n **kwargs\n Any additional keyword arguments are delegated to\n :class:`~matplotlib.collections.LineCollection`\n \"\"\"\n\n def calc_arrows(UVW, angle=15):\n # get unit direction vector perpendicular to (u, v, w)\n x = UVW[:, 0]\n y = UVW[:, 1]\n norm = np.linalg.norm(UVW[:, :2], axis=1)\n x_p = np.divide(y, norm, where=norm != 0, out=np.zeros_like(x))\n y_p = np.divide(-x, norm, where=norm != 0, out=np.ones_like(x))\n # compute the two arrowhead direction unit vectors\n ra = math.radians(angle)\n c = math.cos(ra)\n s = math.sin(ra)\n # construct the rotation matrices of shape (3, 3, n)\n Rpos = np.array(\n [[c + (x_p ** 2) * (1 - c), x_p * y_p * (1 - c), y_p * s],\n [y_p * x_p * (1 - c), c + (y_p ** 2) * (1 - c), -x_p * s],\n [-y_p * s, x_p * s, np.full_like(x_p, c)]])\n # opposite rotation negates all the sin terms\n Rneg = Rpos.copy()\n Rneg[[0, 1, 2, 2], [2, 2, 0, 1]] *= -1\n # Batch n (3, 3) x (3) matrix multiplications ((3, 3, n) x (n, 3)).\n Rpos_vecs = np.einsum(\"ij...,...j->...i\", Rpos, UVW)\n Rneg_vecs = np.einsum(\"ij...,...j->...i\", Rneg, UVW)\n # Stack into (n, 2, 3) result.\n head_dirs = np.stack([Rpos_vecs, Rneg_vecs], axis=1)\n return head_dirs\n\n had_data = self.has_data()\n\n # handle args\n argi = 6\n if len(args) < argi:\n raise ValueError('Wrong number of arguments. Expected %d got %d' %\n (argi, len(args)))\n\n # first 6 arguments are X, Y, Z, U, V, W\n input_args = args[:argi]\n\n # extract the masks, if any\n masks = [k.mask for k in input_args\n if isinstance(k, np.ma.MaskedArray)]\n # broadcast to match the shape\n bcast = np.broadcast_arrays(*input_args, *masks)\n input_args = bcast[:argi]\n masks = bcast[argi:]\n if masks:\n # combine the masks into one\n mask = functools.reduce(np.logical_or, masks)\n # put mask on and compress\n input_args = [np.ma.array(k, mask=mask).compressed()\n for k in input_args]\n else:\n input_args = [np.ravel(k) for k in input_args]\n\n if any(len(v) == 0 for v in input_args):\n # No quivers, so just make an empty collection and return early\n linec = art3d.Line3DCollection([], *args[argi:], **kwargs)\n self.add_collection(linec)\n return linec\n\n shaft_dt = np.array([0., length], dtype=float)\n arrow_dt = shaft_dt * arrow_length_ratio\n\n _api.check_in_list(['tail', 'middle', 'tip'], pivot=pivot)\n if pivot == 'tail':\n shaft_dt -= length\n elif pivot == 'middle':\n shaft_dt -= length / 2\n\n XYZ = np.column_stack(input_args[:3])\n UVW = np.column_stack(input_args[3:argi]).astype(float)\n\n # Normalize rows of UVW\n norm = np.linalg.norm(UVW, axis=1)\n\n # If any row of UVW is all zeros, don't make a quiver for it\n mask = norm > 0\n XYZ = XYZ[mask]\n if normalize:\n UVW = UVW[mask] / norm[mask].reshape((-1, 1))\n else:\n UVW = UVW[mask]\n\n if len(XYZ) > 0:\n # compute the shaft lines all at once with an outer product\n shafts = (XYZ - np.multiply.outer(shaft_dt, UVW)).swapaxes(0, 1)\n # compute head direction vectors, n heads x 2 sides x 3 dimensions\n head_dirs = calc_arrows(UVW)\n # compute all head lines at once, starting from the shaft ends\n heads = shafts[:, :1] - np.multiply.outer(arrow_dt, head_dirs)\n # stack left and right head lines together\n heads = heads.reshape((len(arrow_dt), -1, 3))\n # transpose to get a list of lines\n heads = heads.swapaxes(0, 1)\n\n lines = [*shafts, *heads]\n else:\n lines = []\n\n linec = art3d.Line3DCollection(lines, *args[argi:], **kwargs)\n self.add_collection(linec)\n\n self.auto_scale_xyz(XYZ[:, 0], XYZ[:, 1], XYZ[:, 2], had_data)\n\n return linec\n\n quiver3D = quiver\n\n def voxels(self, *args, facecolors=None, edgecolors=None, shade=True,\n lightsource=None, **kwargs):\n \"\"\"\n ax.voxels([x, y, z,] /, filled, facecolors=None, edgecolors=None, \\\n**kwargs)\n\n Plot a set of filled voxels\n\n All voxels are plotted as 1x1x1 cubes on the axis, with\n ``filled[0, 0, 0]`` placed with its lower corner at the origin.\n Occluded faces are not plotted.\n\n Parameters\n ----------\n filled : 3D np.array of bool\n A 3D array of values, with truthy values indicating which voxels\n to fill\n\n x, y, z : 3D np.array, optional\n The coordinates of the corners of the voxels. This should broadcast\n to a shape one larger in every dimension than the shape of\n *filled*. These can be used to plot non-cubic voxels.\n\n If not specified, defaults to increasing integers along each axis,\n like those returned by :func:`~numpy.indices`.\n As indicated by the ``/`` in the function signature, these\n arguments can only be passed positionally.\n\n facecolors, edgecolors : array-like, optional\n The color to draw the faces and edges of the voxels. Can only be\n passed as keyword arguments.\n These parameters can be:\n\n - A single color value, to color all voxels the same color. This\n can be either a string, or a 1D rgb/rgba array\n - ``None``, the default, to use a single color for the faces, and\n the style default for the edges.\n - A 3D ndarray of color names, with each item the color for the\n corresponding voxel. The size must match the voxels.\n - A 4D ndarray of rgb/rgba data, with the components along the\n last axis.\n\n shade : bool, default: True\n Whether to shade the facecolors. Shading is always disabled when\n *cmap* is specified.\n\n lightsource : `~matplotlib.colors.LightSource`\n The lightsource to use when *shade* is True.\n\n **kwargs\n Additional keyword arguments to pass onto\n `~mpl_toolkits.mplot3d.art3d.Poly3DCollection`.\n\n Returns\n -------\n faces : dict\n A dictionary indexed by coordinate, where ``faces[i, j, k]`` is a\n `.Poly3DCollection` of the faces drawn for the voxel\n ``filled[i, j, k]``. If no faces were drawn for a given voxel,\n either because it was not asked to be drawn, or it is fully\n occluded, then ``(i, j, k) not in faces``.\n\n Examples\n --------\n .. plot:: gallery/mplot3d/voxels.py\n .. plot:: gallery/mplot3d/voxels_rgb.py\n .. plot:: gallery/mplot3d/voxels_torus.py\n .. plot:: gallery/mplot3d/voxels_numpy_logo.py\n \"\"\"\n\n # work out which signature we should be using, and use it to parse\n # the arguments. Name must be voxels for the correct error message\n if len(args) >= 3:\n # underscores indicate position only\n def voxels(__x, __y, __z, filled, **kwargs):\n return (__x, __y, __z), filled, kwargs\n else:\n def voxels(filled, **kwargs):\n return None, filled, kwargs\n\n xyz, filled, kwargs = voxels(*args, **kwargs)\n\n # check dimensions\n if filled.ndim != 3:\n raise ValueError(\"Argument filled must be 3-dimensional\")\n size = np.array(filled.shape, dtype=np.intp)\n\n # check xyz coordinates, which are one larger than the filled shape\n coord_shape = tuple(size + 1)\n if xyz is None:\n x, y, z = np.indices(coord_shape)\n else:\n x, y, z = (np.broadcast_to(c, coord_shape) for c in xyz)\n\n def _broadcast_color_arg(color, name):\n if np.ndim(color) in (0, 1):\n # single color, like \"red\" or [1, 0, 0]\n return np.broadcast_to(color, filled.shape + np.shape(color))\n elif np.ndim(color) in (3, 4):\n # 3D array of strings, or 4D array with last axis rgb\n if np.shape(color)[:3] != filled.shape:\n raise ValueError(\n \"When multidimensional, {} must match the shape of \"\n \"filled\".format(name))\n return color\n else:\n raise ValueError(\"Invalid {} argument\".format(name))\n\n # broadcast and default on facecolors\n if facecolors is None:\n facecolors = self._get_patches_for_fill.get_next_color()\n facecolors = _broadcast_color_arg(facecolors, 'facecolors')\n\n # broadcast but no default on edgecolors\n edgecolors = _broadcast_color_arg(edgecolors, 'edgecolors')\n\n # scale to the full array, even if the data is only in the center\n self.auto_scale_xyz(x, y, z)\n\n # points lying on corners of a square\n square = np.array([\n [0, 0, 0],\n [1, 0, 0],\n [1, 1, 0],\n [0, 1, 0],\n ], dtype=np.intp)\n\n voxel_faces = defaultdict(list)\n\n def permutation_matrices(n):\n \"\"\"Generate cyclic permutation matrices.\"\"\"\n mat = np.eye(n, dtype=np.intp)\n for i in range(n):\n yield mat\n mat = np.roll(mat, 1, axis=0)\n\n # iterate over each of the YZ, ZX, and XY orientations, finding faces\n # to render\n for permute in permutation_matrices(3):\n # find the set of ranges to iterate over\n pc, qc, rc = permute.T.dot(size)\n pinds = np.arange(pc)\n qinds = np.arange(qc)\n rinds = np.arange(rc)\n\n square_rot_pos = square.dot(permute.T)\n square_rot_neg = square_rot_pos[::-1]\n\n # iterate within the current plane\n for p in pinds:\n for q in qinds:\n # iterate perpendicularly to the current plane, handling\n # boundaries. We only draw faces between a voxel and an\n # empty space, to avoid drawing internal faces.\n\n # draw lower faces\n p0 = permute.dot([p, q, 0])\n i0 = tuple(p0)\n if filled[i0]:\n voxel_faces[i0].append(p0 + square_rot_neg)\n\n # draw middle faces\n for r1, r2 in zip(rinds[:-1], rinds[1:]):\n p1 = permute.dot([p, q, r1])\n p2 = permute.dot([p, q, r2])\n\n i1 = tuple(p1)\n i2 = tuple(p2)\n\n if filled[i1] and not filled[i2]:\n voxel_faces[i1].append(p2 + square_rot_pos)\n elif not filled[i1] and filled[i2]:\n voxel_faces[i2].append(p2 + square_rot_neg)\n\n # draw upper faces\n pk = permute.dot([p, q, rc-1])\n pk2 = permute.dot([p, q, rc])\n ik = tuple(pk)\n if filled[ik]:\n voxel_faces[ik].append(pk2 + square_rot_pos)\n\n # iterate over the faces, and generate a Poly3DCollection for each\n # voxel\n polygons = {}\n for coord, faces_inds in voxel_faces.items():\n # convert indices into 3D positions\n if xyz is None:\n faces = faces_inds\n else:\n faces = []\n for face_inds in faces_inds:\n ind = face_inds[:, 0], face_inds[:, 1], face_inds[:, 2]\n face = np.empty(face_inds.shape)\n face[:, 0] = x[ind]\n face[:, 1] = y[ind]\n face[:, 2] = z[ind]\n faces.append(face)\n\n # shade the faces\n facecolor = facecolors[coord]\n edgecolor = edgecolors[coord]\n if shade:\n normals = self._generate_normals(faces)\n facecolor = self._shade_colors(facecolor, normals, lightsource)\n if edgecolor is not None:\n edgecolor = self._shade_colors(\n edgecolor, normals, lightsource\n )\n\n poly = art3d.Poly3DCollection(\n faces, facecolors=facecolor, edgecolors=edgecolor, **kwargs)\n self.add_collection3d(poly)\n polygons[coord] = poly\n\n return polygons\n\n @_preprocess_data(replace_names=[\"x\", \"y\", \"z\", \"xerr\", \"yerr\", \"zerr\"])\n def errorbar(self, x, y, z, zerr=None, yerr=None, xerr=None, fmt='',\n barsabove=False, errorevery=1, ecolor=None, elinewidth=None,\n capsize=None, capthick=None, xlolims=False, xuplims=False,\n ylolims=False, yuplims=False, zlolims=False, zuplims=False,\n **kwargs):\n \"\"\"\n Plot lines and/or markers with errorbars around them.\n\n *x*/*y*/*z* define the data locations, and *xerr*/*yerr*/*zerr* define\n the errorbar sizes. By default, this draws the data markers/lines as\n well the errorbars. Use fmt='none' to draw errorbars only.\n\n Parameters\n ----------\n x, y, z : float or array-like\n The data positions.\n\n xerr, yerr, zerr : float or array-like, shape (N,) or (2, N), optional\n The errorbar sizes:\n\n - scalar: Symmetric +/- values for all data points.\n - shape(N,): Symmetric +/-values for each data point.\n - shape(2, N): Separate - and + values for each bar. First row\n contains the lower errors, the second row contains the upper\n errors.\n - *None*: No errorbar.\n\n Note that all error arrays should have *positive* values.\n\n fmt : str, default: ''\n The format for the data points / data lines. See `.plot` for\n details.\n\n Use 'none' (case insensitive) to plot errorbars without any data\n markers.\n\n ecolor : color, default: None\n The color of the errorbar lines. If None, use the color of the\n line connecting the markers.\n\n elinewidth : float, default: None\n The linewidth of the errorbar lines. If None, the linewidth of\n the current style is used.\n\n capsize : float, default: :rc:`errorbar.capsize`\n The length of the error bar caps in points.\n\n capthick : float, default: None\n An alias to the keyword argument *markeredgewidth* (a.k.a. *mew*).\n This setting is a more sensible name for the property that\n controls the thickness of the error bar cap in points. For\n backwards compatibility, if *mew* or *markeredgewidth* are given,\n then they will over-ride *capthick*. This may change in future\n releases.\n\n barsabove : bool, default: False\n If True, will plot the errorbars above the plot\n symbols. Default is below.\n\n xlolims, ylolims, zlolims : bool, default: False\n These arguments can be used to indicate that a value gives only\n lower limits. In that case a caret symbol is used to indicate\n this. *lims*-arguments may be scalars, or array-likes of the same\n length as the errors. To use limits with inverted axes,\n `~.Axes.set_xlim` or `~.Axes.set_ylim` must be called before\n :meth:`errorbar`. Note the tricky parameter names: setting e.g.\n *ylolims* to True means that the y-value is a *lower* limit of the\n True value, so, only an *upward*-pointing arrow will be drawn!\n\n xuplims, yuplims, zuplims : bool, default: False\n Same as above, but for controlling the upper limits.\n\n errorevery : int or (int, int), default: 1\n draws error bars on a subset of the data. *errorevery* =N draws\n error bars on the points (x[::N], y[::N], z[::N]).\n *errorevery* =(start, N) draws error bars on the points\n (x[start::N], y[start::N], z[start::N]). e.g. errorevery=(6, 3)\n adds error bars to the data at (x[6], x[9], x[12], x[15], ...).\n Used to avoid overlapping error bars when two series share x-axis\n values.\n\n Returns\n -------\n errlines : list\n List of `~mpl_toolkits.mplot3d.art3d.Line3DCollection` instances\n each containing an errorbar line.\n caplines : list\n List of `~mpl_toolkits.mplot3d.art3d.Line3D` instances each\n containing a capline object.\n limmarks : list\n List of `~mpl_toolkits.mplot3d.art3d.Line3D` instances each\n containing a marker with an upper or lower limit.\n\n Other Parameters\n ----------------\n data : indexable object, optional\n DATA_PARAMETER_PLACEHOLDER\n\n **kwargs\n All other keyword arguments for styling errorbar lines are passed\n `~mpl_toolkits.mplot3d.art3d.Line3DCollection`.\n\n Examples\n --------\n .. plot:: gallery/mplot3d/errorbar3d.py\n \"\"\"\n had_data = self.has_data()\n\n kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)\n # Drop anything that comes in as None to use the default instead.\n kwargs = {k: v for k, v in kwargs.items() if v is not None}\n kwargs.setdefault('zorder', 2)\n\n self._process_unit_info([(\"x\", x), (\"y\", y), (\"z\", z)], kwargs,\n convert=False)\n\n # make sure all the args are iterable; use lists not arrays to\n # preserve units\n x = x if np.iterable(x) else [x]\n y = y if np.iterable(y) else [y]\n z = z if np.iterable(z) else [z]\n\n if not len(x) == len(y) == len(z):\n raise ValueError(\"'x', 'y', and 'z' must have the same size\")\n\n if isinstance(errorevery, Integral):\n errorevery = (0, errorevery)\n if isinstance(errorevery, tuple):\n if (len(errorevery) == 2 and\n isinstance(errorevery[0], Integral) and\n isinstance(errorevery[1], Integral)):\n errorevery = slice(errorevery[0], None, errorevery[1])\n else:\n raise ValueError(\n f'errorevery={errorevery!r} is a not a tuple of two '\n f'integers')\n\n elif isinstance(errorevery, slice):\n pass\n\n elif not isinstance(errorevery, str) and np.iterable(errorevery):\n # fancy indexing\n try:\n x[errorevery]\n except (ValueError, IndexError) as err:\n raise ValueError(\n f\"errorevery={errorevery!r} is iterable but not a valid \"\n f\"NumPy fancy index to match \"\n f\"'xerr'/'yerr'/'zerr'\") from err\n else:\n raise ValueError(\n f\"errorevery={errorevery!r} is not a recognized value\")\n\n label = kwargs.pop(\"label\", None)\n kwargs['label'] = '_nolegend_'\n\n # Create the main line and determine overall kwargs for child artists.\n # We avoid calling self.plot() directly, or self._get_lines(), because\n # that would call self._process_unit_info again, and do other indirect\n # data processing.\n (data_line, base_style), = self._get_lines._plot_args(\n (x, y) if fmt == '' else (x, y, fmt), kwargs, return_kwargs=True)\n art3d.line_2d_to_3d(data_line, zs=z)\n\n # Do this after creating `data_line` to avoid modifying `base_style`.\n if barsabove:\n data_line.set_zorder(kwargs['zorder'] - .1)\n else:\n data_line.set_zorder(kwargs['zorder'] + .1)\n\n # Add line to plot, or throw it away and use it to determine kwargs.\n if fmt.lower() != 'none':\n self.add_line(data_line)\n else:\n data_line = None\n # Remove alpha=0 color that _process_plot_format returns.\n base_style.pop('color')\n\n if 'color' not in base_style:\n base_style['color'] = 'C0'\n if ecolor is None:\n ecolor = base_style['color']\n\n # Eject any line-specific information from format string, as it's not\n # needed for bars or caps.\n for key in ['marker', 'markersize', 'markerfacecolor',\n 'markeredgewidth', 'markeredgecolor', 'markevery',\n 'linestyle', 'fillstyle', 'drawstyle', 'dash_capstyle',\n 'dash_joinstyle', 'solid_capstyle', 'solid_joinstyle']:\n base_style.pop(key, None)\n\n # Make the style dict for the line collections (the bars).\n eb_lines_style = {**base_style, 'color': ecolor}\n\n if elinewidth:\n eb_lines_style['linewidth'] = elinewidth\n elif 'linewidth' in kwargs:\n eb_lines_style['linewidth'] = kwargs['linewidth']\n\n for key in ('transform', 'alpha', 'zorder', 'rasterized'):\n if key in kwargs:\n eb_lines_style[key] = kwargs[key]\n\n # Make the style dict for caps (the \"hats\").\n eb_cap_style = {**base_style, 'linestyle': 'None'}\n if capsize is None:\n capsize = rcParams[\"errorbar.capsize\"]\n if capsize > 0:\n eb_cap_style['markersize'] = 2. * capsize\n if capthick is not None:\n eb_cap_style['markeredgewidth'] = capthick\n eb_cap_style['color'] = ecolor\n\n everymask = np.zeros(len(x), bool)\n everymask[errorevery] = True\n\n def _apply_mask(arrays, mask):\n # Return, for each array in *arrays*, the elements for which *mask*\n # is True, without using fancy indexing.\n return [[*itertools.compress(array, mask)] for array in arrays]\n\n def _extract_errs(err, data, lomask, himask):\n # For separate +/- error values we need to unpack err\n if len(err.shape) == 2:\n low_err, high_err = err\n else:\n low_err, high_err = err, err\n\n lows = np.where(lomask | ~everymask, data, data - low_err)\n highs = np.where(himask | ~everymask, data, data + high_err)\n\n return lows, highs\n\n # collect drawn items while looping over the three coordinates\n errlines, caplines, limmarks = [], [], []\n\n # list of endpoint coordinates, used for auto-scaling\n coorderrs = []\n\n # define the markers used for errorbar caps and limits below\n # the dictionary key is mapped by the `i_xyz` helper dictionary\n capmarker = {0: '|', 1: '|', 2: '_'}\n i_xyz = {'x': 0, 'y': 1, 'z': 2}\n\n # Calculate marker size from points to quiver length. Because these are\n # not markers, and 3D Axes do not use the normal transform stack, this\n # is a bit involved. Since the quiver arrows will change size as the\n # scene is rotated, they are given a standard size based on viewing\n # them directly in planar form.\n quiversize = eb_cap_style.get('markersize',\n rcParams['lines.markersize']) ** 2\n quiversize *= self.figure.dpi / 72\n quiversize = self.transAxes.inverted().transform([\n (0, 0), (quiversize, quiversize)])\n quiversize = np.mean(np.diff(quiversize, axis=0))\n # quiversize is now in Axes coordinates, and to convert back to data\n # coordinates, we need to run it through the inverse 3D transform. For\n # consistency, this uses a fixed azimuth and elevation.\n with cbook._setattr_cm(self, azim=0, elev=0):\n invM = np.linalg.inv(self.get_proj())\n # azim=elev=0 produces the Y-Z plane, so quiversize in 2D 'x' is 'y' in\n # 3D, hence the 1 index.\n quiversize = np.dot(invM, np.array([quiversize, 0, 0, 0]))[1]\n # Quivers use a fixed 15-degree arrow head, so scale up the length so\n # that the size corresponds to the base. In other words, this constant\n # corresponds to the equation tan(15) = (base / 2) / (arrow length).\n quiversize *= 1.8660254037844388\n eb_quiver_style = {**eb_cap_style,\n 'length': quiversize, 'arrow_length_ratio': 1}\n eb_quiver_style.pop('markersize', None)\n\n # loop over x-, y-, and z-direction and draw relevant elements\n for zdir, data, err, lolims, uplims in zip(\n ['x', 'y', 'z'], [x, y, z], [xerr, yerr, zerr],\n [xlolims, ylolims, zlolims], [xuplims, yuplims, zuplims]):\n\n dir_vector = art3d.get_dir_vector(zdir)\n i_zdir = i_xyz[zdir]\n\n if err is None:\n continue\n\n if not np.iterable(err):\n err = [err] * len(data)\n\n err = np.atleast_1d(err)\n\n # arrays fine here, they are booleans and hence not units\n lolims = np.broadcast_to(lolims, len(data)).astype(bool)\n uplims = np.broadcast_to(uplims, len(data)).astype(bool)\n\n # a nested list structure that expands to (xl,xh),(yl,yh),(zl,zh),\n # where x/y/z and l/h correspond to dimensions and low/high\n # positions of errorbars in a dimension we're looping over\n coorderr = [\n _extract_errs(err * dir_vector[i], coord, lolims, uplims)\n for i, coord in enumerate([x, y, z])]\n (xl, xh), (yl, yh), (zl, zh) = coorderr\n\n # draws capmarkers - flat caps orthogonal to the error bars\n nolims = ~(lolims | uplims)\n if nolims.any() and capsize > 0:\n lo_caps_xyz = _apply_mask([xl, yl, zl], nolims & everymask)\n hi_caps_xyz = _apply_mask([xh, yh, zh], nolims & everymask)\n\n # setting '_' for z-caps and '|' for x- and y-caps;\n # these markers will rotate as the viewing angle changes\n cap_lo = art3d.Line3D(*lo_caps_xyz, ls='',\n marker=capmarker[i_zdir],\n **eb_cap_style)\n cap_hi = art3d.Line3D(*hi_caps_xyz, ls='',\n marker=capmarker[i_zdir],\n **eb_cap_style)\n self.add_line(cap_lo)\n self.add_line(cap_hi)\n caplines.append(cap_lo)\n caplines.append(cap_hi)\n\n if lolims.any():\n xh0, yh0, zh0 = _apply_mask([xh, yh, zh], lolims & everymask)\n self.quiver(xh0, yh0, zh0, *dir_vector, **eb_quiver_style)\n if uplims.any():\n xl0, yl0, zl0 = _apply_mask([xl, yl, zl], uplims & everymask)\n self.quiver(xl0, yl0, zl0, *-dir_vector, **eb_quiver_style)\n\n errline = art3d.Line3DCollection(np.array(coorderr).T,\n **eb_lines_style)\n self.add_collection(errline)\n errlines.append(errline)\n coorderrs.append(coorderr)\n\n coorderrs = np.array(coorderrs)\n\n def _digout_minmax(err_arr, coord_label):\n return (np.nanmin(err_arr[:, i_xyz[coord_label], :, :]),\n np.nanmax(err_arr[:, i_xyz[coord_label], :, :]))\n\n minx, maxx = _digout_minmax(coorderrs, 'x')\n miny, maxy = _digout_minmax(coorderrs, 'y')\n minz, maxz = _digout_minmax(coorderrs, 'z')\n self.auto_scale_xyz((minx, maxx), (miny, maxy), (minz, maxz), had_data)\n\n # Adapting errorbar containers for 3d case, assuming z-axis points \"up\"\n errorbar_container = mcontainer.ErrorbarContainer(\n (data_line, tuple(caplines), tuple(errlines)),\n has_xerr=(xerr is not None or yerr is not None),\n has_yerr=(zerr is not None),\n label=label)\n self.containers.append(errorbar_container)\n\n return errlines, caplines, limmarks\n\n def get_tightbbox(self, renderer, call_axes_locator=True,\n bbox_extra_artists=None, *, for_layout_only=False):\n ret = super().get_tightbbox(renderer,\n call_axes_locator=call_axes_locator,\n bbox_extra_artists=bbox_extra_artists,\n for_layout_only=for_layout_only)\n batch = [ret]\n if self._axis3don:\n for axis in self._get_axis_list():\n if axis.get_visible():\n try:\n axis_bb = axis.get_tightbbox(\n renderer,\n for_layout_only=for_layout_only\n )\n except TypeError:\n # in case downstream library has redefined axis:\n axis_bb = axis.get_tightbbox(renderer)\n if axis_bb:\n batch.append(axis_bb)\n return mtransforms.Bbox.union(batch)\n\n @_preprocess_data()\n def stem(self, x, y, z, *, linefmt='C0-', markerfmt='C0o', basefmt='C3-',\n bottom=0, label=None, orientation='z'):\n \"\"\"\n Create a 3D stem plot.\n\n A stem plot draws lines perpendicular to a baseline, and places markers\n at the heads. By default, the baseline is defined by *x* and *y*, and\n stems are drawn vertically from *bottom* to *z*.\n\n Parameters\n ----------\n x, y, z : array-like\n The positions of the heads of the stems. The stems are drawn along\n the *orientation*-direction from the baseline at *bottom* (in the\n *orientation*-coordinate) to the heads. By default, the *x* and *y*\n positions are used for the baseline and *z* for the head position,\n but this can be changed by *orientation*.\n\n linefmt : str, default: 'C0-'\n A string defining the properties of the vertical lines. Usually,\n this will be a color or a color and a linestyle:\n\n ========= =============\n Character Line Style\n ========= =============\n ``'-'`` solid line\n ``'--'`` dashed line\n ``'-.'`` dash-dot line\n ``':'`` dotted line\n ========= =============\n\n Note: While it is technically possible to specify valid formats\n other than color or color and linestyle (e.g. 'rx' or '-.'), this\n is beyond the intention of the method and will most likely not\n result in a reasonable plot.\n\n markerfmt : str, default: 'C0o'\n A string defining the properties of the markers at the stem heads.\n\n basefmt : str, default: 'C3-'\n A format string defining the properties of the baseline.\n\n bottom : float, default: 0\n The position of the baseline, in *orientation*-coordinates.\n\n label : str, default: None\n The label to use for the stems in legends.\n\n orientation : {'x', 'y', 'z'}, default: 'z'\n The direction along which stems are drawn.\n\n data : indexable object, optional\n DATA_PARAMETER_PLACEHOLDER\n\n Returns\n -------\n `.StemContainer`\n The container may be treated like a tuple\n (*markerline*, *stemlines*, *baseline*)\n\n Examples\n --------\n .. plot:: gallery/mplot3d/stem3d_demo.py\n \"\"\"\n\n from matplotlib.container import StemContainer\n\n had_data = self.has_data()\n\n _api.check_in_list(['x', 'y', 'z'], orientation=orientation)\n\n xlim = (np.min(x), np.max(x))\n ylim = (np.min(y), np.max(y))\n zlim = (np.min(z), np.max(z))\n\n # Determine the appropriate plane for the baseline and the direction of\n # stemlines based on the value of orientation.\n if orientation == 'x':\n basex, basexlim = y, ylim\n basey, baseylim = z, zlim\n lines = [[(bottom, thisy, thisz), (thisx, thisy, thisz)]\n for thisx, thisy, thisz in zip(x, y, z)]\n elif orientation == 'y':\n basex, basexlim = x, xlim\n basey, baseylim = z, zlim\n lines = [[(thisx, bottom, thisz), (thisx, thisy, thisz)]\n for thisx, thisy, thisz in zip(x, y, z)]\n else:\n basex, basexlim = x, xlim\n basey, baseylim = y, ylim\n lines = [[(thisx, thisy, bottom), (thisx, thisy, thisz)]\n for thisx, thisy, thisz in zip(x, y, z)]\n\n # Determine style for stem lines.\n linestyle, linemarker, linecolor = _process_plot_format(linefmt)\n if linestyle is None:\n linestyle = rcParams['lines.linestyle']\n\n # Plot everything in required order.\n baseline, = self.plot(basex, basey, basefmt, zs=bottom,\n zdir=orientation, label='_nolegend_')\n stemlines = art3d.Line3DCollection(\n lines, linestyles=linestyle, colors=linecolor, label='_nolegend_')\n self.add_collection(stemlines)\n markerline, = self.plot(x, y, z, markerfmt, label='_nolegend_')\n\n stem_container = StemContainer((markerline, stemlines, baseline),\n label=label)\n self.add_container(stem_container)\n\n jx, jy, jz = art3d.juggle_axes(basexlim, baseylim, [bottom, bottom],\n orientation)\n self.auto_scale_xyz([*jx, *xlim], [*jy, *ylim], [*jz, *zlim], had_data)\n\n return stem_container\n\n stem3D = stem\n\n\ndef get_test_data(delta=0.05):\n \"\"\"Return a tuple X, Y, Z with a test data set.\"\"\"\n x = y = np.arange(-3.0, 3.0, delta)\n X, Y = np.meshgrid(x, y)\n\n Z1 = np.exp(-(X**2 + Y**2) / 2) / (2 * np.pi)\n Z2 = (np.exp(-(((X - 1) / 1.5)**2 + ((Y - 1) / 0.5)**2) / 2) /\n (2 * np.pi * 0.5 * 1.5))\n Z = Z2 - Z1\n\n X = X * 10\n Y = Y * 10\n Z = Z * 500\n return X, Y, Z\n" ]
[ [ "numpy.dtype", "pandas._libs.missing.is_matching_na", "pandas.DataFrame" ], [ "pandas._testing.assert_numpy_array_equal", "pandas._testing.assert_equal", "pandas.Timestamp", "numpy.isnan", "numpy.shares_memory", "pandas.DataFrame", "numpy.concatenate", "pandas.date_range", "numpy.array" ], [ "numpy.testing.assert_equal" ], [ "pandas.to_datetime", "pandas.Series", "pandas.core.dtypes.dtypes.DatetimeTZDtype", "pandas.DataFrame", "numpy.dtype", "numpy.random.randn", "pandas._testing.assert_frame_equal", "pandas.io.json._table_schema.convert_json_field_to_pandas_type", "pandas.Timestamp", "pandas.Index", "pandas._testing.assert_produces_warning", "pandas.io.json._table_schema.set_default_names", "pandas.Categorical", "pandas.Timedelta", "pandas.MultiIndex.from_product", "pandas.read_json", "pandas.date_range", "pandas.core.dtypes.dtypes.CategoricalDtype", "pandas.core.dtypes.dtypes.PeriodDtype", "numpy.array", "pandas.io.json._table_schema.convert_pandas_type_to_json_field", "pandas.io.json._table_schema.build_table_schema", "pandas.CategoricalIndex", "pandas.timedelta_range", "pandas.period_range", "pandas.MultiIndex.from_arrays", "pandas.io.json._table_schema.as_json_table_type" ], [ "pandas.tseries.offsets.Day", "pandas.Series", "numpy.linspace", "numpy.random.randn", "pandas.isna", "numpy.allclose", "numpy.unique", "numpy.arange", "pandas.DatetimeIndex", "pandas.cut", "pandas._testing.assert_series_equal", "pandas._testing.assert_index_equal", "pandas.Categorical", "numpy.quantile", "pandas.Interval", "pandas.date_range", "pandas.timedelta_range", "pandas.api.types.CategoricalDtype", "pandas.TimedeltaIndex", "pandas.tseries.offsets.Nano", "pandas._testing.assert_categorical_equal", "pandas.Timestamp", "pandas.qcut", "numpy.loadtxt" ], [ "pandas.core.tools.times.to_time", "pandas._testing.assert_produces_warning", "pandas.Series", "pandas.core.tools.datetimes.to_time", "numpy.array" ], [ "numpy._pytesttester.PytestTester", "numpy.distutils.fcompiler.new_fcompiler" ], [ "numpy.distutils.misc_util.make_temp_file", "numpy.distutils.log.debug", "numpy.distutils.misc_util.is_sequence", "numpy.distutils.log.warn", "numpy.distutils.log.info" ], [ "numpy.dot", "sklearn.decomposition.SparsePCA", "sklearn.utils._testing.assert_allclose", "sklearn.decomposition.MiniBatchSparsePCA", "numpy.eye", "numpy.linalg.norm", "numpy.sign", "numpy.all", "sklearn.utils._testing.assert_array_almost_equal", "numpy.random.RandomState", "sklearn.decomposition.PCA", "sklearn.utils.check_random_state", "numpy.zeros" ], [ "pandas.io.excel.ExcelWriter", "pandas._testing.assert_produces_warning", "pandas.DataFrame", "pandas._testing.ensure_clean" ], [ "numpy.array", "pandas.CategoricalIndex", "pandas.MultiIndex.from_frame", "pandas.Series", "pandas.MultiIndex.from_tuples", "pandas.DataFrame", "pandas.MultiIndex.from_arrays", "pandas.Index", "pandas._testing.assert_series_equal", "pandas._testing.assert_frame_equal", "numpy.where" ], [ "numpy.asarray", "numpy.array", "pandas._libs.lib.is_list_like", "pandas.core.dtypes.missing.notna" ], [ "pandas.util._exceptions.find_stack_level", "pandas.compat._optional.import_optional_dependency", "pandas.core.dtypes.common.is_file_like", "pandas.compat.get_lzma_file", "pandas.util._decorators.doc" ], [ "numpy.log", "scipy.fft._fftlog.ifht", "numpy.logspace", "scipy.fft._fftlog.fht", "scipy.fft._fftlog.fhtoffset", "numpy.testing.assert_allclose", "numpy.exp", "numpy.random.RandomState", "scipy.special.poch" ], [ "numpy.arange", "pandas.Index", "pandas.DataFrame", "pandas.date_range", "pandas._testing.assert_series_equal", "pandas._testing.assert_frame_equal", "pandas._testing.assert_index_equal" ], [ "pandas.offsets.Hour", "pandas._testing.assert_numpy_array_equal", "pandas.Series", "pandas.to_datetime", "pandas.Timestamp", "numpy.isnan", "pandas.offsets.Day", "numpy.uint8", "numpy.int32", "numpy.arange", "pandas.Timedelta", "numpy.datetime64", "numpy.timedelta64", "numpy.int64", "pandas.offsets.Minute", "numpy.float64", "pandas.offsets.Second", "numpy.array" ], [ "pandas._testing.ensure_safe_environment_variables", "pandas.compat.is_platform_arm", "pandas.compat.is_platform_windows", "pandas.compat.is_platform_mac", "pandas.compat.is_ci_environment", "pandas.util._test_decorators.skip_if_no" ], [ "numpy.asarray", "numpy.array", "numpy.unique" ], [ "numpy.sqrt", "numpy.abs", "numpy.finfo", "numpy.ones", "numpy.any", "numpy.log1p", "numpy.average" ], [ "numpy.testing.assert_" ], [ "pandas.Series", "pandas.MultiIndex.from_tuples", "pandas.DataFrame", "numpy.random.randn", "pandas.isna", "numpy.random.randint", "pandas._testing.assert_numpy_array_equal", "numpy.arange", "pandas.Index", "pandas.util.version.Version", "numpy.interp", "pandas._testing.assert_series_equal", "pandas._testing.assert_produces_warning", "pandas.interval_range", "numpy.random.rand", "pandas.date_range", "pandas.timedelta_range", "pandas.DateOffset", "pandas.period_range", "pandas.to_timedelta", "numpy.random.uniform" ], [ "numpy.nanmax", "pandas.plotting._matplotlib.tools.set_ticks_props", "numpy.nanmin", "scipy.stats.gaussian_kde", "pandas.plotting._matplotlib.tools.create_subplots", "pandas.plotting._matplotlib.groupby.create_iter_data_given_by", "pandas.core.dtypes.missing.remove_na_arraylike", "matplotlib.pyplot.gcf", "numpy.ravel", "matplotlib.pyplot.figure", "pandas.core.dtypes.common.is_list_like", "pandas.plotting._matplotlib.core.MPLPlot._plot", "pandas.plotting._matplotlib.groupby.reformat_hist_y_given_by", "pandas.plotting._matplotlib.tools.flatten_axes", "numpy.ndim", "pandas.plotting._matplotlib.tools.maybe_adjust_figure", "matplotlib.pyplot.get_fignums", "numpy.array", "pandas.plotting._matplotlib.core.MPLPlot.__init__", "pandas.core.dtypes.common.is_integer", "pandas.core.dtypes.missing.isna", "pandas.io.formats.printing.pprint_thing" ], [ "pandas.DataFrame", "numpy.random.randint" ], [ "numpy.product", "numpy.dtype", "numpy.broadcast", "numpy.zeros_like", "numpy.any", "numpy.ravel_multi_index", "numpy.str_", "numpy.bool_", "numpy.random.default_rng", "numpy.testing.assert_equal", "numpy.may_share_memory", "numpy.arange", "numpy.full", "numpy.zeros", "numpy.testing.assert_raises_regex", "numpy.nonzero", "numpy.rec.array", "numpy.int_", "numpy.testing.assert_raises", "numpy.testing.assert_", "numpy.array", "numpy.testing.assert_warns", "numpy.intp", "numpy.ones", "numpy.testing.assert_array_equal", "numpy.broadcast_to", "numpy.float64", "numpy.float_", "numpy.prod", "numpy.random.uniform", "numpy.empty" ], [ "pandas.Categorical", "pandas._testing.assert_series_equal", "pandas.Series" ], [ "numpy.nanmax", "numpy.exp", "numpy.where", "numpy.sin", "numpy.multiply.outer", "numpy.ceil", "numpy.asanyarray", "numpy.diff", "numpy.insert", "numpy.zeros", "matplotlib.cbook.delete_masked_points", "matplotlib.cbook._array_patch_perimeters", "matplotlib.colors.LightSource", "numpy.full_like", "numpy.append", "numpy.array", "numpy.indices", "numpy.shape", "matplotlib.axes._base._axis_method_wrapper", "matplotlib.colors.to_rgba_array", "matplotlib.transforms.Bbox.union", "numpy.asarray", "matplotlib.cbook._to_unmasked_float_array", "matplotlib._api.rename_parameter", "numpy.hypot", "matplotlib.tri.triangulation.Triangulation.get_from_args_and_kwargs", "matplotlib.cbook.normalize_kwargs", "numpy.may_share_memory", "numpy.ma.ravel", "matplotlib.cbook._array_perimeter", "numpy.atleast_1d", "matplotlib.transforms.Bbox.from_bounds", "matplotlib._api.warn_deprecated", "numpy.min", "numpy.ndim", "numpy.errstate", "numpy.ma.filled", "matplotlib._preprocess_data", "matplotlib.axes._base._process_plot_format", "numpy.empty", "numpy.zeros_like", "numpy.roll", "numpy.eye", "numpy.column_stack", "matplotlib.cbook._define_aliases", "matplotlib._api.warn_external", "numpy.isnan", "numpy.deg2rad", "numpy.broadcast_arrays", "numpy.iterable", "numpy.transpose", "numpy.linalg.norm", "numpy.cos", "matplotlib.colors.Normalize", "numpy.broadcast_to", "numpy.dot", "matplotlib._api.delete_parameter", "matplotlib.transforms.Bbox.unit", "matplotlib._api.check_in_list", "numpy.einsum", "matplotlib.cbook._setattr_cm", "matplotlib.colors.to_rgba", "numpy.nanmin", "matplotlib._api.check_getitem", "numpy.max", "matplotlib.scale.get_scale_names", "numpy.cross", "numpy.ma.array", "numpy.ones_like", "numpy.arange", "matplotlib.cbook.Grouper", "numpy.stack", "numpy.ravel", "matplotlib.container.StemContainer", "numpy.meshgrid", "matplotlib.tri.triangulation.Triangulation", "matplotlib._api.deprecated" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] }, { "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": [ "0.23", "0.21", "1.4", "1.3", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [ "1.11", "1.19", "1.24", "1.16", "1.23", "1.20", "1.7", "1.12", "1.21", "1.22", "1.14", "1.6", "1.13", "1.9", "1.17", "1.10", "1.18", "1.15", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [ "1.24", "1.22", "1.23" ], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.1", "1.5", "1.2", "0.24", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.12", "0.10" ], "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": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "0.24", "0.20", "1.0", "0.25" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "1.1", "1.5", "0.24", "1.0", "0.25", "1.2" ], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] }, { "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": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ssh0/growing-string
[ "2e43916e91157dfb4253775149b35ec9d81ef14d", "2e43916e91157dfb4253775149b35ec9d81ef14d", "2e43916e91157dfb4253775149b35ec9d81ef14d", "2e43916e91157dfb4253775149b35ec9d81ef14d" ]
[ "triangular_lattice/diecutting/result_n2.py", "triangular_lattice/fractal_dim_from_mass2.py", "triangular_lattice/fill_bucket.py", "triangular_lattice/diecutting/result_count_on_edge.py" ]
[ "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n#\n# written by Shotaro Fujimoto\n# 2016-12-07\n\nimport matplotlib.pyplot as plt\n# from mpl_toolkits.mplot3d.axes3d import Axes3D\nimport matplotlib.cm as cm\nimport numpy as np\nfrom scipy.optimize import curve_fit\nfrom scipy.stats import gamma\nimport set_data_path\n\n\ndef load_data(_path):\n data = np.load(_path)\n beta = data['beta']\n try:\n size_dist_ave = data['size_dist_ave']\n return load_data_averaged(_path)\n except KeyError:\n pass\n\n num_of_strings = data['num_of_strings']\n frames = data['frames']\n Ls = data['Ls'].astype(np.float)\n # Ls = (3 * Ls * (Ls + 1) + 1)\n size_dist = data['size_dist']\n\n N0 = np.array([l[1] for l in size_dist], dtype=np.float) / num_of_strings\n n0 = N0[1:]\n S = np.array([np.sum(l) for l in size_dist], dtype=np.float) / num_of_strings\n n1 = (S[1:] - n0) * 2.\n\n N = []\n for l in size_dist:\n dot = np.dot(np.arange(len(l)), np.array(l).T)\n N.append(dot)\n # N = np.array([np.dot(np.arange(len(l)), np.array(l).T) for l in size_dist])\n N_all = 3. * Ls * (Ls + 1.) + 1\n N = np.array(N, dtype=np.float) / num_of_strings\n N_minus = N_all - N\n\n N_minus_rate = N_minus / N_all\n\n n_minus = N_minus[1:] - N_minus[:-1]\n\n n1_ave = n1 / np.sum(n1)\n\n n2 = (6 * Ls[1:]) - (n0 + n1 + n_minus)\n\n return {\n 'beta': beta,\n 'num_of_strings': num_of_strings,\n 'frames': frames,\n 'Ls': Ls,\n 'N_minus': N_minus,\n 'N_minus_rate': N_minus_rate,\n 'S': S,\n 'n0': n0,\n 'n1': n1,\n 'n2': n2,\n 'n_minus': n_minus,\n 'n1_ave': n1_ave,\n }\n\ndef load_data_averaged(_path):\n data = np.load(_path)\n beta = data['beta']\n num_of_strings = data['num_of_strings']\n frames = data['frames']\n Ls = data['Ls'].astype(np.float)\n # Ls = (3 * Ls * (Ls + 1) + 1)\n # size_dist = data['size_dist']\n size_dist_ave = data['size_dist_ave']\n\n N0 = np.array([l[1] for l in size_dist_ave], dtype=np.float)\n n0 = N0[1:]\n S = np.array([np.sum(l) for l in size_dist_ave], dtype=np.float)\n n1 = (S[1:] - n0) * 2.\n\n N = []\n for l in size_dist_ave:\n dot = np.dot(np.arange(len(l)), np.array(l).T)\n N.append(dot)\n # N = np.array([np.dot(np.arange(len(l)), np.array(l).T) for l in size_dist_ave])\n N_all = 3. * Ls * (Ls + 1.) + 1\n N = np.array(N, dtype=np.float)\n N_minus = N_all - N\n\n N_minus_rate = N_minus / N_all\n\n n_minus = N_minus[1:] - N_minus[:-1]\n\n n1_ave = n1 / np.sum(n1)\n\n n2 = (6 * Ls[1:]) - (n0 + n1 + n_minus)\n\n return {\n 'beta': beta,\n 'num_of_strings': num_of_strings,\n 'frames': frames,\n 'Ls': Ls,\n 'N_minus': N_minus,\n 'N_minus_rate': N_minus_rate,\n 'S': S,\n 'n0': n0,\n 'n1': n1,\n 'n2': n2,\n 'n_minus': n_minus,\n 'n1_ave': n1_ave,\n }\n\ndef result_n2(path):\n fig, ax = plt.subplots()\n for i, result_data_path in enumerate(path):\n globals().update(load_data(result_data_path))\n ax.plot(Ls[1:], n2, '.', label=r'$\\beta = %2.2f$' % beta,\n color=cm.viridis(float(i) / len(path)))\n ax.legend(loc='best')\n ax.set_title('Averaged number of the sites on the cutting edges which \\\n is connected to two neighbors.' + \n ' (sample: {})'.format(num_of_strings))\n ax.set_xlabel(r'Cutting size $L$')\n ax.set_ylabel(r'$n_{2}$')\n plt.show()\n\n\nif __name__ == '__main__':\n result_n2(set_data_path.data_path)\n", "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n#\n# written by Shotaro Fujimoto\n# 2017-01-22\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport fractal_dim_from_mass as fd\n\n\ndef read_from_csv(fn):\n data = np.loadtxt(fn, delimiter=',', skiprows=1)\n return data\n\n\ndef manual_data():\n Ds = []\n for beta_i in range(6):\n result_data_paths = fd.get_paths(fix='beta', beta_num=beta_i, ver=1)\n _Ds = []\n for path in result_data_paths:\n _Ds.append(fd.get_fractal_dim(path))\n #Ds = [\n # [200, 400, ..., 2000], # 0.\n # [200, 400, ..., 2000], # 2.\n # ...\n # [200, 400, ..., 2000], # 10.\n # ]\n Ds = np.array(Ds)\n return Ds\n\n\nif __name__ == '__main__':\n frames_list = [200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000]\n ## 0 1 2 3 4 5 6 7 8 9\n beta_list = [0, 2, 4, 6, 8, 10]\n ## 0 1 2 3 4 5\n\n Ds = read_from_csv('./results/img/mass_in_r/data_170122.csv').T\n # Ds = manual_data()\n\n markers = ['o', 'v', '^', 's', 'D', 'h']\n\n fig, ax = plt.subplots()\n for i, beta in enumerate(beta_list):\n color = cm.viridis(float(i) / (len(beta_list) - 1))\n ax.plot(frames_list, Ds[i], marker=markers[i % len(markers)],\n ls='', color=color, label=r'$\\beta = %2.2f$' % beta)\n # ax.legend(loc='best')\n ax.legend(bbox_to_anchor=(1.02, 1), loc='upper left', borderaxespad=0, numpoints=1)\n fig.subplots_adjust(right=0.8)\n ax.set_title(r'Fractal dimension $D$')\n ax.set_xlabel(r'$T$')\n ax.set_ylabel(r'$D$')\n ax.set_xlim(0, 2200)\n ax.set_ylim(1., 2.)\n plt.show()\n", "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n#\n# written by Shotaro Fujimoto\n\n\nfrom growing_string import Main\nfrom triangular import LatticeTriangular as LT\nfrom strings import String\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.tri as tri\nfrom matplotlib.patches import Polygon\nfrom matplotlib.collections import PatchCollection\n\n\nclass FillBucket(object):\n def __init__(self, main, plot_type='fill'):\n self.lattice = main.lattice\n self.lattice_X = main.lattice_X\n self.lattice_Y = main.lattice_Y\n self.doubled_lattice = np.zeros((self.lattice.Lx * 2, self.lattice.Ly),\n dtype=np.bool)\n self.define_kagome_lattice()\n self.string = main.strings[0]\n self.plot_type = plot_type\n\n doubled_lattice = self.create_doubled_lattice()\n self.doubled_lattice = self.fill_inside(doubled_lattice)\n\n def create_doubled_lattice(self):\n str_pos = self.string.pos.tolist()\n check_index = [(i, j)\n for i in range(self.lattice.Lx)\n for j in range(self.lattice.Ly)\n if [i, j] in str_pos]\n\n for i, j in check_index:\n k = str_pos.index([i, j])\n vec = self.string.vec[k]\n if vec in [0, 3]:\n continue\n\n if vec == 1:\n x = 2 * i\n y = j\n elif vec == 2:\n x = 2 * i - 1\n y = j\n elif vec == 4:\n x = 2 * i\n y = j - 1\n elif vec == 5:\n x = 2 * i + 1\n y = j - 1\n\n self.doubled_lattice[x, y] = True\n return self.doubled_lattice\n\n def fill_inside(self, arr):\n \"\"\"Fill inside\n\n arr: (m x n: boolean ndarray)\n \"\"\"\n size_x, size_y = arr.shape\n ret_arr = np.zeros((size_x, size_y), dtype=np.bool)\n for j in range(size_y):\n flag = False\n for i in range(size_x):\n tf = arr[i, j]\n if flag ^ tf:\n ret_arr[i, j] = True\n\n if tf:\n flag = not flag\n return ret_arr\n\n def define_kagome_lattice(self):\n size_x, size_y = self.lattice.Lx, self.lattice.Ly\n x_even = self.lattice_X + 0.5 * self.lattice.dx\n y_even = self.lattice_Y + self.lattice.dy / 3.\n x_odd = np.roll(self.lattice_X, -1, axis=0)\n y_odd = np.roll(self.lattice_Y, -1, axis=0) + (2 * self.lattice.dy) / 3.\n self.kagome_X = np.hstack((x_even, x_odd)).reshape(2 * size_x, size_y)\n self.kagome_Y = np.hstack((y_even, y_odd)).reshape(2 * size_x, size_y)\n\n def plot_all(self, plot_type=None):\n if plot_type is None:\n plot_type = self.plot_type\n\n self.fig, self.ax = plt.subplots(figsize=(8, 8))\n\n lattice_X = self.lattice.coordinates_x\n lattice_Y = self.lattice.coordinates_y\n X_min, X_max = min(lattice_X) - 0.1, max(lattice_X) + 0.1\n Y_min, Y_max = min(lattice_Y) - 0.1, max(lattice_Y) + 0.1\n self.ax.set_xlim([X_min, X_max])\n self.ax.set_ylim([Y_min, Y_max])\n self.ax.set_xticklabels([])\n self.ax.set_yticklabels([])\n self.ax.set_aspect('equal')\n\n triang = tri.Triangulation(lattice_X, lattice_Y)\n self.ax.triplot(triang, color='#d5d5d5', lw=0.5)\n\n self.lines = [self.ax.plot([], [], linestyle='-',\n color='black',\n markerfacecolor='black',\n markeredgecolor='black')[0]\n for i in range(self.lattice.Lx)]\n\n i = 0\n s = self.string\n start = 0\n for j, pos1, pos2 in zip(range(len(s.pos) - 1), s.pos[:-1], s.pos[1:]):\n dist_x = abs(self.lattice_X[pos1[0], pos1[1]] -\n self.lattice_X[pos2[0], pos2[1]])\n dist_y = abs(self.lattice_Y[pos1[0], pos1[1]] -\n self.lattice_Y[pos2[0], pos2[1]])\n if dist_x > 1.5 * self.lattice.dx or dist_y > 1.5 * self.lattice.dy:\n x = s.pos_x[start:j + 1]\n y = s.pos_y[start:j + 1]\n X = [self.lattice_X[_x, _y] for _x, _y in zip(x, y)]\n Y = [self.lattice_Y[_x, _y] for _x, _y in zip(x, y)]\n self.lines[i].set_data(X, Y)\n start = j + 1\n i += 1\n else:\n x = s.pos_x[start:]\n y = s.pos_y[start:]\n X = [self.lattice_X[_x, _y] for _x, _y in zip(x, y)]\n Y = [self.lattice_Y[_x, _y] for _x, _y in zip(x, y)]\n self.lines[i].set_data(X, Y)\n i += 1\n\n dx = self.lattice.dx\n dy = self.lattice.dy\n if plot_type == 'fill':\n X = [self.lattice_X[_x, _y] for _x, _y in zip(s.pos_x, s.pos_y)]\n Y = [self.lattice_Y[_x, _y] for _x, _y in zip(s.pos_x, s.pos_y)]\n patches = [Polygon(np.array([X, Y]).T.tolist())]\n p = PatchCollection(patches, color='green')\n self.ax.add_collection(p)\n elif plot_type == 'point':\n # # plot by Point\n index = np.where(self.doubled_lattice)\n X = self.kagome_X[index]\n Y = self.kagome_Y[index]\n self.ax.plot(X, Y, 'r.', alpha=0.5)\n plt.show()\n\n\nif __name__ == '__main__':\n L = 100\n frames = 1000\n\n params = {\n 'Lx': L,\n 'Ly': L,\n 'frames': frames,\n 'beta': 2.,\n 'weight_const': 0.5,\n 'boundary': {'h': 'periodic', 'v': 'periodic'},\n # 'boundary': {'h': 'reflective', 'v': 'reflective'},\n 'plot': False,\n 'plot_surface': False,\n 'interval': 0,\n }\n\n # loop\n main = Main(strings=[{'id': 1, 'x': L / 4, 'y': L / 2, 'vec': [0, 4, 2]}],\n **params\n )\n bucket = FillBucket(main, plot_type='fill')\n # bucket.plot_all(plot_type='point')\n bucket.plot_all(plot_type='fill')\n\n", "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n#\n# written by Shotaro Fujimoto\n# 2016-12-16\n\n\nimport matplotlib.pyplot as plt\n# from mpl_toolkits.mplot3d.axes3d import Axes3D\nimport matplotlib.cm as cm\nimport numpy as np\nimport set_data_path\n\n\nclass Visualizer(object):\n def __init__(self, subjects):\n self.data_path_list = set_data_path.data_path\n if len(subjects) != 0:\n for subject in subjects:\n getattr(self, 'result_' + subject)()\n\n def load_data(self, _path):\n data = np.load(_path)\n beta = data['beta']\n try:\n size_dist_ave = data['size_dist_ave']\n if len(size_dist_ave) == 0:\n raise KeyError\n return self.load_data_averaged(_path)\n except KeyError:\n pass\n\n num_of_strings = data['num_of_strings']\n frames = data['frames']\n Ls = data['Ls'].astype(np.float)\n # Ls = (3 * Ls * (Ls + 1) + 1)\n size_dist = data['size_dist']\n\n N0 = np.array([l[1] for l in size_dist], dtype=np.float) / num_of_strings\n n0 = N0[1:]\n S = np.array([np.sum(l) for l in size_dist], dtype=np.float) / num_of_strings\n n1 = (S[1:] - n0) * 2.\n\n N = []\n for l in size_dist:\n dot = np.dot(np.arange(len(l)), np.array(l).T)\n N.append(dot)\n # N = np.array([np.dot(np.arange(len(l)), np.array(l).T) for l in size_dist])\n N_all = 3. * Ls * (Ls + 1.) + 1\n N = np.array(N, dtype=np.float) / num_of_strings\n N_minus = N_all - N\n N_minus_rate = N_minus / N_all\n n_minus = N_minus[1:] - N_minus[:-1]\n n1_ave = n1 / np.sum(n1)\n n2 = (6 * Ls[1:]) - (n0 + n1 + n_minus)\n\n self.beta = beta\n self.num_of_strings = num_of_strings\n self.frames = frames\n self.Ls = Ls\n self.N = N\n self.N_minus = N_minus\n self.N_minus_rate = N_minus_rate\n self.S = S\n self.n0 = n0\n self.n1 = n1\n self.n2 = n2\n self.n_minus = n_minus\n self.n1_ave = n1_ave\n\n def load_data_averaged(self, _path):\n data = np.load(_path)\n beta = data['beta']\n num_of_strings = data['num_of_strings']\n frames = data['frames']\n Ls = data['Ls'].astype(np.float)\n # Ls = (3 * Ls * (Ls + 1) + 1)\n # size_dist = data['size_dist']\n size_dist_ave = data['size_dist_ave']\n\n N0 = np.array([l[1] for l in size_dist_ave], dtype=np.float)\n n0 = N0[1:]\n S = np.array([np.sum(l) for l in size_dist_ave], dtype=np.float)\n n1 = (S[1:] - n0) * 2.\n\n N = []\n for l in size_dist_ave:\n dot = np.dot(np.arange(len(l)), np.array(l).T)\n N.append(dot)\n # N = np.array([np.dot(np.arange(len(l)), np.array(l).T) for l in size_dist_ave])\n N_all = 3. * Ls * (Ls + 1.) + 1\n N = np.array(N, dtype=np.float)\n N_minus = N_all - N\n N_minus_rate = N_minus / N_all\n n_minus = N_minus[1:] - N_minus[:-1]\n n1_ave = n1 / np.sum(n1)\n n2 = (6 * Ls[1:]) - (n0 + n1 + n_minus)\n\n self.beta = beta\n self.num_of_strings = num_of_strings\n self.frames = frames\n self.Ls = Ls\n self.N = N\n self.N_all = N_all\n self.N_minus = N_minus\n self.N_minus_rate = N_minus_rate\n self.S = S\n self.n_all = 6 * Ls[1:]\n self.n0 = n0\n self.n1 = n1\n self.n2 = n2\n self.n_minus = n_minus\n self.n1_ave = n1_ave\n\n def result_N(self):\n fig, ax = plt.subplots()\n for i, result_data_path in enumerate(self.data_path_list):\n self.load_data(result_data_path)\n ax.plot(self.Ls[1:], self.N[1:], '.',\n label=r'$\\beta = %2.2f$' % self.beta,\n color=cm.viridis(float(i) / len(self.data_path_list)))\n ax.legend(loc='best')\n ax.set_title('Occupied points in the cutting region' +\n ' (sample: {})'.format(self.num_of_strings))\n ax.set_xlabel(r'Cutting size $L$')\n ax.set_ylabel(r'$N$')\n plt.show()\n\n def result_N_minus_rate(self):\n fig, ax = plt.subplots()\n for i, result_data_path in enumerate(self.data_path_list):\n self.load_data(result_data_path)\n ax.plot(self.Ls[1:], self.N_minus_rate[1:], '.',\n label=r'$\\beta = %2.2f$' % self.beta,\n color=cm.viridis(float(i) / len(self.data_path_list)))\n ax.legend(loc='best')\n ax.set_title('The rate of not occupied site in all N' +\n ' (sample: {})'.format(self.num_of_strings))\n ax.set_xlabel(r'Cutting size $L$')\n ax.set_ylabel(r'$N_{-1} / N_{\\mathrm{all}}$')\n plt.show()\n\n def result_n0(self):\n fig, ax = plt.subplots()\n for i, result_data_path in enumerate(self.data_path_list):\n self.load_data(result_data_path)\n ax.plot(self.Ls[1:], self.n0, '.',\n label=r'$\\beta = %2.2f$' % self.beta,\n color=cm.viridis(float(i) / len(self.data_path_list)))\n ax.legend(loc='best')\n ax.set_title('Averaged number of the sites which is the only member of \\\n a subcluster on the cutting edges.' +\n ' (sample: {})'.format(self.num_of_strings))\n ax.set_xlabel(r'Cutting size $L$')\n ax.set_ylabel(r'$n_{0}$')\n plt.show()\n\n def result_n1(self):\n fig, ax = plt.subplots()\n for i, result_data_path in enumerate(self.data_path_list):\n self.load_data(result_data_path)\n ax.plot(self.Ls[1:], self.n1, '.',\n label=r'$\\beta = %2.2f$' % self.beta,\n color=cm.viridis(float(i) / len(self.data_path_list)))\n ax.legend(loc='best')\n ax.set_title('Averaged number of the sites which is connected to a \\\n existing subcluster on the cutting edges.' +\n ' (sample: {})'.format(self.num_of_strings))\n ax.set_xlabel(r'Cutting size $L$')\n ax.set_ylabel(r'$n_{1}$')\n plt.show()\n\n def result_n2(self):\n fig, ax = plt.subplots()\n for i, result_data_path in enumerate(self.data_path_list):\n self.load_data(result_data_path)\n ax.plot(self.Ls[1:], self.n2, '.',\n label=r'$\\beta = %2.2f$' % self.beta,\n color=cm.viridis(float(i) / len(self.data_path_list)))\n ax.legend(loc='best')\n ax.set_title('Averaged number of the sites on the cutting edges which \\\n is connected to two neighbors.' + \n ' (sample: {})'.format(self.num_of_strings))\n ax.set_xlabel(r'Cutting size $L$')\n ax.set_ylabel(r'$n_{2}$')\n plt.show()\n\n def result_n_minus(self):\n fig, ax = plt.subplots()\n for i, result_data_path in enumerate(self.data_path_list):\n self.load_data(result_data_path)\n ax.plot(self.Ls[1:], self.n_minus, '.',\n label=r'$\\beta = %2.2f$' % self.beta,\n color=cm.viridis(float(i) / len(self.data_path_list)))\n ax.legend(loc='best')\n ax.set_title('Averaged number of the sites which is not occupied on \\\n the cutting edges.' + \n ' (sample: {})'.format(self.num_of_strings))\n ax.set_xlabel(r'Cutting size $L$')\n ax.set_ylabel(r'$n_{-1}$')\n plt.show()\n\n def result_S(self):\n fig, ax = plt.subplots()\n for i, result_data_path in enumerate(self.data_path_list):\n self.load_data(result_data_path)\n ax.plot(self.Ls[1:], self.S[1:] / np.sum(self.S[1:]), '.',\n label=r'$\\beta = %2.2f$' % self.beta,\n color=cm.viridis(float(i) / len(self.data_path_list)))\n ax.legend(loc='best')\n ax.set_ylim([0, ax.get_ylim()[1]])\n ax.set_title('Averaged number of the subclusters in the cutted region.'\n + ' (sample: {})'.format(self.num_of_strings))\n ax.set_xlabel(r'Cutting size $L$')\n ax.set_ylabel(r'$S$')\n plt.show()\n\n def result_S_rate(self):\n fig, ax = plt.subplots()\n for i, result_data_path in enumerate(self.data_path_list):\n self.load_data(result_data_path)\n # ax.plot(self.Ls[1:], self.S[1:] / np.sum(self.S[1:]), '.',\n # ax.plot(self.Ls[1:], self.S[1:] / self.n_all, '.',\n ax.plot(self.Ls[1:], self.S[1:] / self.N[1:], '.',\n label=r'$\\beta = %2.2f$' % self.beta,\n color=cm.viridis(float(i) / len(self.data_path_list)))\n ax.legend(loc='best')\n ax.set_ylim([0, ax.get_ylim()[1]])\n ax.set_title('Averaged number of the subclusters in the cutted region'\n + ' (normalized)'\n + ' (sample: {})'.format(self.num_of_strings))\n ax.set_xlabel(r'Cutting size $L$')\n ax.set_ylabel(r'$S$')\n plt.show()\n\n\nif __name__ == '__main__':\n # subject: 'N', 'N_minus_rate', 'n0', 'n1', 'n2', 'n_minus', 'S'\n main = Visualizer(\n [\n # 'N',\n # 'N_minus_rate',\n # 'n0',\n # 'n1',\n # 'n2',\n # 'n_minus',\n 'S',\n # 'S_rate'\n ]\n )\n" ]
[ [ "matplotlib.pyplot.subplots", "numpy.load", "numpy.array", "numpy.sum", "matplotlib.pyplot.show" ], [ "matplotlib.pyplot.show", "numpy.array", "matplotlib.pyplot.subplots", "numpy.loadtxt" ], [ "numpy.hstack", "matplotlib.collections.PatchCollection", "matplotlib.pyplot.subplots", "numpy.where", "numpy.array", "matplotlib.pyplot.show", "matplotlib.tri.Triangulation", "numpy.roll", "numpy.zeros" ], [ "matplotlib.pyplot.subplots", "numpy.load", "numpy.array", "numpy.sum", "matplotlib.pyplot.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
bilgetutak/pyroms
[ "cd0fe39075825f97a7caf64e2c4c5a19f23302fd", "cd0fe39075825f97a7caf64e2c4c5a19f23302fd", "cd0fe39075825f97a7caf64e2c4c5a19f23302fd", "a4f6547bce872068a5bb5751231017bc3e4a4503", "cd0fe39075825f97a7caf64e2c4c5a19f23302fd", "cd0fe39075825f97a7caf64e2c4c5a19f23302fd", "cd0fe39075825f97a7caf64e2c4c5a19f23302fd", "cd0fe39075825f97a7caf64e2c4c5a19f23302fd" ]
[ "examples/Yellow_Sea/make_YELLOW_grd_v1.py", "pyroms_toolbox/pyroms_toolbox/Grid_HYCOM/make_remap_grid_file.py", "examples/Arctic_runoff/addto_runoff_file.py", "pyroms_toolbox/pyroms_toolbox/rvalue.py", "examples/make_tide/CGrid_TPXO8/CGrid_TPXO8.py", "bathy_smoother/setup.py", "examples/make_tide/CGrid_TPXO8/make_remap_grid_file.py", "examples/NWGOA3/Fetch_Pacific/get_pacific_3d.py" ]
[ "import os\nfrom pyroms import _iso\nimport numpy as np\nfrom mpl_toolkits.basemap import Basemap, shiftgrid\nfrom scipy.interpolate import griddata\nimport matplotlib.colors as colors\nfrom scipy.signal import medfilt2d\nimport netCDF4\n\nimport pyroms\nfrom bathy_smoother import *\n\n# Grid dimension\nLm = 140\nMm = 120\n\nlon0=117.5 ; lat0 = 41.\nlon1=117.5 ; lat1 = 34.5\nlon2 = 127. ; lat2 = 34.5\nlon3 = 127. ; lat3 = 41.\nmap = Basemap(projection='lcc', lat_0=35., lat_1=30., lat_2=40, lon_0 =123, \\\n width=2000000, height=2000000, resolution='i')\n\nlonp = np.array([lon0, lon1, lon2, lon3])\nlatp = np.array([lat0, lat1, lat2, lat3])\nbeta = np.array([1, 1, 1, 1])\n\n#generate the new grid\n# Do this if you aren't going to move the grid corners interactively.\nhgrd = pyroms.grid.Gridgen(lonp, latp, beta, (Mm+3, Lm+3), proj=map)\n# Do this if you are going to use the Boundary Interactor\n#map.drawcoastlines()\n#xp, yp = map(lonp, latp)\n#bry = pyroms.hgrid.BoundaryInteractor(xp, yp, beta, shp=(Mm+3,Lm+3), proj=map)\n#hgrd=bry.grd\n\nlonv, latv = list(map(hgrd.x_vert, hgrd.y_vert, inverse=True))\nhgrd = pyroms.grid.CGrid_geo(lonv, latv, map)\n\n# generate the mask\n#for verts in map.coastsegs:\n# hgrd.mask_polygon(verts)\n# alternate version from johan.navarro.padron\n\nfor xx,yy in map.coastpolygons:\n xa = np.array(xx, np.float32)\n ya = np.array(yy,np.float32)\n vv = np.zeros((xa.shape[0],2))\n vv[:, 0] = xa\n vv[:, 1] = ya\n hgrd.mask_polygon(vv,mask_value=0)\n\n# Edit the land mask interactively.\n#pyroms.grid.edit_mask_mesh(hgrd, proj=map)\n#edit_mask_mesh_ij is a faster version using imshow... but no map projection.\ncoast = pyroms.utility.get_coast_from_map(map)\npyroms.grid.edit_mask_mesh_ij(hgrd, coast=coast)\n\n\n#### Use the following to interpolate from etopo2 bathymetry.\n# generate the bathy\n# read in topo data (on a regular lat/lon grid)\n# this topo come with basemap so you should have it on your laptop.\n# just update datadir with the appropriate path\n# you can get this data from matplolib svn with\n# svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk/htdocs/screenshots/data/\"\n\ndatadir = 'data/'\ntopo = np.loadtxt(os.path.join(datadir, 'etopo20data.gz'))\nlons = np.loadtxt(os.path.join(datadir, 'etopo20lons.gz'))\nlats = np.loadtxt(os.path.join(datadir, 'etopo20lats.gz'))\n\n# depth positive\ntopo = -topo\n\n# fix minimum depth\nhmin = 5\ntopo = np.where(topo < hmin, hmin, topo)\n\n# interpolate new bathymetry\nlon, lat = np.meshgrid(lons, lats)\nh = griddata((lon.flat,lat.flat),topo.flat,(hgrd.lon_rho,hgrd.lat_rho), method='linear')\n\n# insure that depth is always deeper than hmin\nh = np.where(h < hmin, hmin, h)\n\n# set depth to hmin where masked\nidx = np.where(hgrd.mask_rho == 0)\nh[idx] = hmin\n\n# save raw bathymetry\nhraw = h.copy()\n\n# check bathymetry roughness\nRoughMat = bathy_tools.RoughnessMatrix(h, hgrd.mask_rho)\nprint('Max Roughness value is: ', RoughMat.max())\n\n# smooth the raw bathy using the direct iterative method from Martinho and Batteen (2006)\nrx0_max = 0.35\nh = bathy_smoothing.smoothing_Positive_rx0(hgrd.mask_rho, h, rx0_max)\n\n# check bathymetry roughness again\nRoughMat = bathy_tools.RoughnessMatrix(h, hgrd.mask_rho)\nprint('Max Roughness value is: ', RoughMat.max())\n\n# vertical coordinate\ntheta_b = 2\ntheta_s = 7.0\nTcline = 50\nN = 30\nvgrd = pyroms.vgrid.s_coordinate_4(h, theta_b, theta_s, Tcline, N, hraw=hraw)\n\n# ROMS grid\ngrd_name = 'YELLOW'\ngrd = pyroms.grid.ROMS_Grid(grd_name, hgrd, vgrd)\n\n# write grid to netcdf file\npyroms.grid.write_ROMS_grid(grd, filename='YELLOW_grd_v1.nc')\n", "import numpy as np\nfrom mpl_toolkits.basemap import pyproj\nfrom datetime import datetime\ntry:\n import netCDF4 as netCDF\nexcept:\n import netCDF3 as netCDF\n\n\ndef make_remap_grid_file(grd):\n\n #create remap file\n remap_filename = 'remap_grid_' + grd.name + '_t.nc'\n nc = netCDF.Dataset(remap_filename, 'w', format='NETCDF3_64BIT')\n nc.Description = 'remap grid file for HYCOM'\n nc.Author = 'pyroms_toolbox.Grid_HYCOM.make_remap_grid_file'\n nc.Created = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n nc.title = grd.name\n\n lon_corner = grd.lon_vert\n lat_corner = grd.lat_vert\n grid_center_lon = grd.lon_t.flatten()\n grid_center_lat = grd.lat_t.flatten()\n Mp, Lp = grd.lon_t.shape\n grid_imask = grd.mask_t[0,:].flatten()\n\n grid_size = Lp * Mp\n\n grid_corner_lon = np.zeros((grid_size, 4))\n grid_corner_lat = np.zeros((grid_size, 4))\n k = 0\n for j in range(Mp):\n for i in range(Lp):\n grid_corner_lon[k,0] = lon_corner[j,i]\n grid_corner_lat[k,0] = lat_corner[j,i]\n grid_corner_lon[k,1] = lon_corner[j,i+1]\n grid_corner_lat[k,1] = lat_corner[j,i+1]\n grid_corner_lon[k,2] = lon_corner[j+1,i+1]\n grid_corner_lat[k,2] = lat_corner[j+1,i+1]\n grid_corner_lon[k,3] = lon_corner[j+1,i]\n grid_corner_lat[k,3] = lat_corner[j+1,i]\n k = k + 1\n\n\n #Write netcdf file\n nc.createDimension('grid_size', grid_size)\n nc.createDimension('grid_corners', 4)\n nc.createDimension('grid_rank', 2)\n\n nc.createVariable('grid_dims', 'i4', ('grid_rank'))\n nc.variables['grid_dims'].long_name = 'grid size along x and y axis'\n nc.variables['grid_dims'].units = 'None'\n nc.variables['grid_dims'][:] = [(Lp, Mp)]\n\n nc.createVariable('grid_center_lon', 'f8', ('grid_size'))\n nc.variables['grid_center_lon'].long_name = 'longitude of cell center'\n nc.variables['grid_center_lon'].units = 'degrees'\n nc.variables['grid_center_lon'][:] = grid_center_lon\n\n nc.createVariable('grid_center_lat', 'f8', ('grid_size'))\n nc.variables['grid_center_lat'].long_name = 'latitude of cell center'\n nc.variables['grid_center_lat'].units = 'degrees'\n nc.variables['grid_center_lat'][:] = grid_center_lat\n\n nc.createVariable('grid_imask', 'i4', ('grid_size'))\n nc.variables['grid_imask'].long_name = 'mask'\n nc.variables['grid_imask'].units = 'None'\n nc.variables['grid_imask'][:] = grid_imask\n\n nc.createVariable('grid_corner_lon', 'f8', ('grid_size', 'grid_corners'))\n nc.variables['grid_corner_lon'].long_name = 'longitude of cell corner'\n nc.variables['grid_corner_lon'].units = 'degrees'\n nc.variables['grid_corner_lon'][:] = grid_corner_lon\n\n nc.createVariable('grid_corner_lat', 'f8', ('grid_size', 'grid_corners'))\n nc.variables['grid_corner_lat'].long_name = 'latitude of cell corner'\n nc.variables['grid_corner_lat'].units = 'degrees'\n nc.variables['grid_corner_lat'][:] = grid_corner_lat\n\n nc.close()\n\n", "import numpy as np\nimport netCDF4 as netCDF\nfrom datetime import datetime\n\nimport pyroms\nimport pyroms_toolbox\n\n#You need to edit and run compute_daitren_remap_weights.py first\n#then edit and run make_ARCTIC2_runoff.py to generate the runoff file.\n#In make_ARCTIC2_runoff.py you can tune the number of cell defining the\n#littoral band where you will have a runoff value (look for \"width\"\n#variable) and the area over which the runoff is spread in order\n#homogenize and to avoid large runoff value (variable \"rspread\").\n\n# load 2-dimentional interannual discharge data \n# from 1948-2007. See Dai and Trenberth (2002) and Dai et al. (2009)\nprint('Load interannual discharge data')\nnc_data = netCDF.Dataset('/archive/u1/uaf/kate/CORE2/runoff.daitren.iaf.10FEB2011.nc', 'r')\ndata = nc_data.variables['runoff'][:]\n# time with leap year\ntime = np.zeros(data.shape[0])\nt0 = 17530 #12/31/1947\ntidx=0\nfor year in range(1948,2008):\n if year%4 == 0:\n daysinmonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n else :\n daysinmonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n for month in range(12):\n if tidx == 0:\n time[tidx] = t0 + daysinmonth[month]/2.\n else:\n if month == 0:\n time[tidx] = time[tidx-1] + daysinmonth[month]/2. + 31/2.\n else :\n time[tidx] = time[tidx-1] + daysinmonth[month]/2. + daysinmonth[month-1]/2.\n tidx = tidx + 1\n\n\n# load ARCTIC2 grid object\ngrd = pyroms.grid.get_ROMS_grid('ARCTIC2')\n\n\n# define some variables\nwts_file = 'remap_weights_daitren_to_ARCTIC2_conservative_nomask.nc'\nnt = data.shape[0]\nMp, Lp = grd.hgrid.mask_rho.shape\nspval = -1e30\nrunoff_raw = np.zeros((Mp,Lp))\nrunoff = np.zeros((Mp,Lp))\nrspread = 6\n\n# create runoff file\n#runoff_file = 'runoff_ARCTIC2_daitren_inter_annual_2002-2004.nc'\nrunoff_file = 'runoff_ARCTIC2_daitren_inter_annual_1948-2007.nc'\nnc = netCDF.Dataset(runoff_file, 'a', format='NETCDF3_CLASSIC')\n#nc.Description = 'Dai & Trenberth Interannual monthly river discharge, 1948-2007'\n#nc.Author = 'make_ARCTIC2_runoff.py'\n#nc.Created = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n#nc.title = 'Dai & Trenberth river discharge'\n\n# creat dimensions and variables\n#nc.createDimension('xi_rho', np.size(grd.hgrid.mask_rho,1))\n#nc.createDimension('eta_rho', np.size(grd.hgrid.mask_rho,0))\n#nc.createDimension('runoff_time', None)\n#\n#nc.createVariable('lon_rho', 'f8', ('eta_rho', 'xi_rho'))\n#nc.variables['lon_rho'].long_name = 'longitude of RHO-points'\n#nc.variables['lon_rho'].units = 'degree_east'\n#nc.variables['lon_rho'].field = 'lon_rho, scalar'\n#nc.variables['lon_rho'][:] = grd.hgrid.lon_rho\n#\n#nc.createVariable('lat_rho', 'f8', ('eta_rho', 'xi_rho'))\n#nc.variables['lat_rho'].long_name = 'latitude of RHO-points'\n#nc.variables['lat_rho'].units = 'degree_north'\n#nc.variables['lat_rho'].field = 'lat_rho, scalar'\n#nc.variables['lat_rho'][:] = grd.hgrid.lat_rho\n\n#nc.createVariable('runoff_time', 'f8', ('runoff_time'))\n#nc.variables['runoff_time'].long_name = 'time'\n#nc.variables['runoff_time'].units = 'days since 1900-01-01 00:00:00'\n#nc.variables['runoff_time'][:] = time\n#\n#nc.createVariable('Runoff_raw', 'f8', ('runoff_time', 'eta_rho', 'xi_rho'))\n#nc.variables['Runoff_raw'].long_name = 'Dai_Trenberth River Runoff raw'\n#nc.variables['Runoff_raw'].missing_value = str(spval)\n#nc.variables['Runoff_raw'].units = 'kg/s/m^2'\n#\n#nc.createVariable('Runoff', 'f8', ('runoff_time', 'eta_rho', 'xi_rho'))\n#nc.variables['Runoff'].long_name = 'Dai_Trenberth River Runoff'\n#nc.variables['Runoff'].missing_value = str(spval)\n#nc.variables['Runoff'].units = 'kg/s/m^2'\n\n\n# get littoral (here 4 cells width)\nwidth = 4\nidx = []\nidy = []\nmaskl = grd.hgrid.mask_rho.copy()\nfor w in range(width):\n lit = pyroms_toolbox.get_littoral(maskl)\n idx.extend(lit[0])\n idy.extend(lit[1])\n maskl[lit] = 0\n\nlittoral_idx = (np.array(idx), np.array(idy))\nmaskl = np.zeros(grd.hgrid.mask_rho.shape)\nmaskl[littoral_idx] = 1\n\nmask_idx = np.where(grd.hgrid.mask_rho == 0)\n\nnct=0\nfor t in range(374,376):\n#for t in range(nt):\n print('Remapping runoff for time %f' %time[t])\n # conservative horizontal interpolation using scrip\n runoff_raw = pyroms.remapping.remap(data[t,:,:], wts_file, \\\n spval=spval)\n idx = np.where(runoff_raw != 0)\n runoff = pyroms_toolbox.move_runoff(runoff_raw, \\\n np.array(idx).T + 1, np.array(littoral_idx).T + 1, maskl, \\\n grd.hgrid.x_rho, grd.hgrid.y_rho, grd.hgrid.dx, grd.hgrid.dy)\n\n # spread the runoff within the littoral band\n runoff_spread = np.zeros((Mp,Lp))\n idx = np.where(runoff != 0)\n for p in range(np.size(idx,1)):\n j = list(range(max(0,idx[0][p]-rspread), min(Mp-1,idx[0][p]+rspread+1)))\n i = list(range(max(0,idx[1][p]-rspread), min(Lp-1,idx[1][p]+rspread+1)))\n ji = np.meshgrid(j,i)\n sidx = np.where(maskl[ji] == 1)\n nbpt = np.size(sidx) / 2\n rpt = runoff[idx[0][p],idx[1][p]] * grd.hgrid.dx[idx[0][p],idx[1][p]] * grd.hgrid.dy[idx[0][p],idx[1][p]]\n rpt = rpt / nbpt\n for pa in range(nbpt):\n pai = sidx[0][pa] + ji[1].min()\n paj = sidx[1][pa] + ji[0].min()\n runoff_spread[paj, pai] = runoff_spread[paj, pai] + \\\n rpt / (grd.hgrid.dx[paj, pai] * grd.hgrid.dy[paj, pai])\n\n\n # spval\n runoff_spread[mask_idx] = spval\n\n # write data in destination file\n nc.variables['Runoff'][t] = runoff_spread\n nc.variables['Runoff_raw'][t] = runoff_raw\n\n nct = nct + 1\n\n# close netcdf file\nnc.close()\n", "import numpy as np\n\ndef rvalue(h):\n \"\"\"\n function rv = rvalue(h)\n\n This function compute ROMS stiffness parameter \n (ripped from John Wilkin rvalue.m)\n\n On Input:\n h bathymetry at RHO-points.\n \n On Output:\n rv ROMS stiffness parameter.\n \"\"\"\n #check that h is 2D\n if (len(h.squeeze().shape)!=2):\n raise ValueError('h must be two dimensions')\n\n #check whether h contains any NaNs\n if np.isnan(h).any(): raise Warning('the height array contains NaNs')\n\n #compute diff(h)/2*mean(h) at each velocity grid point\n dhdx_u = np.diff(h, axis=1)\n dhdy_v = np.diff(h, axis=0)\n th_u = 2 * 0.5*(h[:,1:] + h[:,:-1])\n th_v = 2 * 0.5*(h[1:,:] + h[:-1,:])\n r_u = abs(dhdx_u / th_u)\n r_v = abs(dhdy_v / th_v)\n\n #for each rho point, find the maximum rvalue at the 4 \n #surrounding u,v points\n r_u = np.maximum(r_u[:,1:],r_u[:,:-1])\n r_v = np.maximum(r_v[1:,:],r_v[:-1,:])\n\n # pad rows and columns to give a result the same size as the input h\n r_u = np.c_[r_u[:,0], r_u, r_u[:,-1]]\n r_v = np.r_[np.tile(r_v[0,:], (1, 1)), r_v, np.tile(r_v[-1,:], (1, 1))]\n\n rv = np.maximum(r_u,r_v)\n\n return rv\n", "import numpy as np\nfrom mpl_toolkits.basemap import pyproj\nfrom datetime import datetime\ntry:\n import netCDF4 as netCDF\nexcept:\n import netCDF3 as netCDF\n import pyroms\n\nclass CGrid_TPXO8(object):\n\n # CGrid object for TPXO8 v1\n\n def __init__(self, lon_t, lat_t, lon_u, lat_u, lon_v, lat_v, \\\n mask_t, mask_u, mask_v, z_t, z_u, z_v, missing_value, name, xrange, yrange):\n\n self.name = name\n\n self.missing_value = -9999.\n\n self.xrange = xrange\n self.yrange = yrange\n\n self.z_t = z_t[yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]\n\n self.z_u = z_u[yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]\n self.z_v = z_v[yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]\n\n self.lon_t = lon_t[yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]\n self.lat_t = lat_t[yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]\n\n self.lon_u = lon_u[yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]\n self.lat_u = lat_u[yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]\n self.lon_v = lon_v[yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]\n self.lat_v = lat_v[yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]\n\n self.lon_t_vert = 0.5 * (lon_t[yrange[0]-1:yrange[1]+1, xrange[0]-1:xrange[1]+1] + \\\n lon_t[yrange[0]:yrange[1]+2, xrange[0]:xrange[1]+2])\n self.lat_t_vert = 0.5 * (lat_t[yrange[0]-1:yrange[1]+1, xrange[0]-1:xrange[1]+1] + \\\n lat_t[yrange[0]:yrange[1]+2, xrange[0]:xrange[1]+2])\n\n self.lon_u_vert = 0.5 * (lon_u[yrange[0]-1:yrange[1]+1, xrange[0]-1:xrange[1]+1] + \\\n lon_u[yrange[0]:yrange[1]+2, xrange[0]:xrange[1]+2])\n self.lat_u_vert = 0.5 * (lat_u[yrange[0]-1:yrange[1]+1, xrange[0]-1:xrange[1]+1] + \\\n lat_u[yrange[0]:yrange[1]+2, xrange[0]:xrange[1]+2])\n self.lon_v_vert = 0.5 * (lon_v[yrange[0]-1:yrange[1]+1, xrange[0]-1:xrange[1]+1] + \\\n lon_v[yrange[0]:yrange[1]+2, xrange[0]:xrange[1]+2])\n self.lat_v_vert = 0.5 * (lat_v[yrange[0]-1:yrange[1]+1, xrange[0]-1:xrange[1]+1] + \\\n lat_v[yrange[0]:yrange[1]+2, xrange[0]:xrange[1]+2])\n\n self.mask_t = mask_t[yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]\n self.mask_u = mask_u[yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]\n self.mask_v = mask_v[yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]\n\n ones = np.ones(self.z_t.shape)\n a1 = lat_u[yrange[0]:yrange[1]+1, xrange[0]+1:xrange[1]+2] - \\\n lat_u[yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]\n a2 = lon_u[yrange[0]:yrange[1]+1, xrange[0]+1:xrange[1]+2] - \\\n lon_u[yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1]\n a3 = 0.5*(lat_u[yrange[0]:yrange[1]+1, xrange[0]+1:xrange[1]+2] + \\\n lat_u[yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1])\n a2 = np.where(a2 > 180*ones, a2 - 360*ones, a2)\n a2 = np.where(a2 < -180*ones, a2 + 360*ones, a2)\n a2 = a2 * np.cos(np.pi/180.*a3)\n self.angle = np.arctan2(a1, a2)\n", "\"\"\"\nbathy_smoother is a suite of tools for working with ROMS bathymetry.\n(ripped from matlab script LP_bathymetry)\n\nRequires:\n NumPy (http://numpy.scipy.org)\n lpsolve (http://lpsolve.sourceforge.net/)\n\nContains:\n bathy_smoothing - Tools for smoothing the bathymetry\n\n bathy_tools - Various bathymetry tools\n\n LP_bathy_smoothing - Tools for smoothing the bathymetry using LP\n\n LP_bathy_tools - LP tools for smoothing the bathymetry\n\n LP_tools - Various LP tools\n\n\"\"\"\n\ndoclines = __doc__.split(\"\\n\")\n\ndef configuration(parent_package='',top_path=None):\n from numpy.distutils.misc_util import Configuration\n config = Configuration('bathy_smoother',parent_package,top_path,\n package_path='bathy_smoother')\n config.set_options(ignore_setup_xxx_py=True,\n assume_default_configuration=True,\n delegate_options_to_subpackages=True)\n# quiet=True)\n return config\n\nif __name__ == '__main__':\n from numpy.distutils.core import setup\n setup(name = '',\n version = '0.2.0',\n description = doclines[0],\n long_description = \"\\n\".join(doclines[2:]),\n url = 'https://github.com/ESMG/pyroms',\n license = 'BSD',\n platforms = [\"any\"],\n configuration=configuration,\n )\n", "import numpy as np\nfrom mpl_toolkits.basemap import pyproj\nfrom datetime import datetime\ntry:\n import netCDF4 as netCDF\nexcept:\n import netCDF3 as netCDF\nimport pyroms\n\n\ndef make_remap_grid_file(Cgrd, Cpos='t'):\n\n #create remap file\n remap_filename = 'remap_grid_' + Cgrd.name + '_' + Cpos + '.nc'\n nc = netCDF.Dataset(remap_filename, 'w', format='NETCDF3_CLASSIC')\n nc.Description = 'remap grid file for TPXO8'\n nc.Author = 'pyroms_toolbox.CGrid_TPXO8.make_remap_grid_file'\n nc.Created = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n nc.title = Cgrd.name\n\n lon_corner = Cgrd.lon_t_vert\n lat_corner = Cgrd.lat_t_vert\n grid_center_lon = Cgrd.lon_t.flatten()\n grid_center_lat = Cgrd.lat_t.flatten()\n Mp, Lp = Cgrd.lon_t.shape\n if Cpos == 't':\n grid_imask = Cgrd.mask_t.flatten()\n elif Cpos == 'u':\n grid_imask = Cgrd.mask_u.flatten()\n elif Cpos == 'v':\n grid_imask = Cgrd.mask_v.flatten()\n\n grid_size = Lp * Mp\n\n grid_corner_lon = np.zeros((grid_size, 4))\n grid_corner_lat = np.zeros((grid_size, 4))\n k = 0\n for j in range(Mp):\n for i in range(Lp):\n grid_corner_lon[k,0] = lon_corner[j,i]\n grid_corner_lat[k,0] = lat_corner[j,i]\n grid_corner_lon[k,1] = lon_corner[j,i+1]\n grid_corner_lat[k,1] = lat_corner[j,i+1]\n grid_corner_lon[k,2] = lon_corner[j+1,i+1]\n grid_corner_lat[k,2] = lat_corner[j+1,i+1]\n grid_corner_lon[k,3] = lon_corner[j+1,i]\n grid_corner_lat[k,3] = lat_corner[j+1,i]\n k = k + 1\n\n\n #Write netcdf file\n nc.createDimension('grid_size', grid_size)\n nc.createDimension('grid_corners', 4)\n nc.createDimension('grid_rank', 2)\n\n nc.createVariable('grid_dims', 'i4', ('grid_rank'))\n nc.variables['grid_dims'].long_name = 'grid size along x and y axis'\n nc.variables['grid_dims'].units = 'None'\n nc.variables['grid_dims'][:] = [(Lp, Mp)]\n\n nc.createVariable('grid_center_lon', 'f8', ('grid_size'))\n nc.variables['grid_center_lon'].long_name = 'longitude of cell center'\n nc.variables['grid_center_lon'].units = 'degrees'\n nc.variables['grid_center_lon'][:] = grid_center_lon\n\n nc.createVariable('grid_center_lat', 'f8', ('grid_size'))\n nc.variables['grid_center_lat'].long_name = 'latitude of cell center'\n nc.variables['grid_center_lat'].units = 'degrees'\n nc.variables['grid_center_lat'][:] = grid_center_lat\n\n nc.createVariable('grid_imask', 'i4', ('grid_size'))\n nc.variables['grid_imask'].long_name = 'mask'\n nc.variables['grid_imask'].units = 'None'\n nc.variables['grid_imask'][:] = grid_imask\n\n nc.createVariable('grid_corner_lon', 'f8', ('grid_size', 'grid_corners'))\n nc.variables['grid_corner_lon'].long_name = 'longitude of cell corner'\n nc.variables['grid_corner_lon'].units = 'degrees'\n nc.variables['grid_corner_lon'][:] = grid_corner_lon\n\n nc.createVariable('grid_corner_lat', 'f8', ('grid_size', 'grid_corners'))\n nc.variables['grid_corner_lat'].long_name = 'latitude of cell corner'\n nc.variables['grid_corner_lat'].units = 'degrees'\n nc.variables['grid_corner_lat'][:] = grid_corner_lat\n\n nc.close()\n\n", "import matplotlib\nmatplotlib.use('Agg')\n\nimport numpy as np\nimport netCDF4\nfrom datetime import datetime\nimport pyroms\nimport pyroms_toolbox\nimport sys\n\n'''\nUsage: python get_pacific_3d.py [year] [field]\n For instance: python get_pacific_3d.py 1991 sio4\n'''\n\nyear = int(sys.argv[1])\nfield = sys.argv[2]\n\ninvarname = field\noutvarname = field\n\ndef create_HYCOM_file(name):\n global nc\n print('Creating file %s' %name)\n\n #create netCDF file\n nc = netCDF4.Dataset(name, 'w', format='NETCDF3_64BIT')\n nc.Author = sys._getframe().f_code.co_name\n nc.Created = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n nc.title = 'ROMS + CoSiNE Pacific (U Maine)'\n\n #create dimensions\n Mp, Lp = zeta0.shape\n N = 20\n theta_s = 5\n theta_b = 0\n Tcline = 50\n nc.createDimension('xi_rho', Lp)\n nc.createDimension('eta_rho', Mp)\n nc.createDimension('s_rho', N)\n nc.createDimension('ocean_time', None)\n\n #create variables \n# nc.createVariable('lon_rho', 'f', ('eta_rho', 'xi_rho'))\n# nc.variables['lon_rho'].long_name = 'longitude'\n# nc.variables['lon_rho'].units = 'degrees_east'\n# nc.variables['lon_rho'][:] = lon\n#\n# nc.createVariable('lat_rho', 'f', ('eta_rho', 'xi_rho'))\n# nc.variables['lat_rho'].long_name = 'latitude'\n# nc.variables['lat_rho'].units = 'degrees_north'\n# nc.variables['lat_rho'][:] = lat\n#\n# nc.createVariable('s_rho', 'f', ('s_rho'))\n# nc.variables['s_rho'].standard_name = 'ocean_s_coordinate'\n# nc.variables['s_rho'].formula_terms = 's: s_rho eta: zeta depth: h a: theta_s b: theta_b depth_c: Tcline'\n# nc.variables['s_rho'][:] = s_rho\n\n nc.createVariable('theta_s', 'f')\n nc.variables['theta_s'][:] = theta_s\n\n nc.createVariable('theta_b', 'f')\n nc.variables['theta_b'][:] = theta_b\n\n nc.createVariable('Tcline', 'f')\n nc.variables['Tcline'][:] = Tcline\n\n nc.createVariable('ocean_time', 'f', ('ocean_time'))\n nc.variables['ocean_time'].units = 'days since 1900-01-01 00:00:00'\n nc.variables['ocean_time'].calendar = 'LEAP'\n nc.variables['ocean_time'].long_name = 'ocean time'\n# nc.variables['ocean_time'][:] = time\n\n nc.createVariable(outvarname, 'f', ('ocean_time', 's_rho', 'eta_rho', 'xi_rho'), fill_value=spval)\n nc.variables[outvarname].long_name = long_name\n nc.variables[outvarname].units = units\n nc.variables[outvarname].field = field\n nc.variables[outvarname].time = 'ocean_time'\n nc.variables[outvarname].coordinates = 'ocean_time s_rho lon_rho lat_rho'\n\n\n print('Done with header for file %s' %name)\n\n\n\n# get Pacific data from 1991 to 2008\n\n#year = 1991\nretry='True'\nspval = 1.e30\nrec_start = (year-1948)*120\nrec_end = rec_start + 120\n\n#read grid and variable attributes from the first file\n#url='http://viz.clusters.umaine.edu:8080/thredds/dodsC/pacific/1991-2008'\nurl='http://viz.clusters.umaine.edu:8080/thredds/dodsC/pacific/roms50-avg'\ndataset = netCDF4.Dataset(url)\nzeta0 = dataset.variables['zeta'][0,170:215,195:265]\n#lon = dataset.variables['lon_rho'][170:215,195:265]\n#lat = dataset.variables['lat_rho'][170:215,195:265]\n#h = dataset.variables['h'][170:215,195:265]\n#theta_s = dataset.variables['theta_s'][:]\n#theta_b = dataset.variables['theta_b'][:]\n#Tcline = dataset.variables['Tcline'][:]\n#s_rho = dataset.variables['s_rho'][:]\ntime = dataset.variables['scrum_time'][:]\n#spval = dataset.variables[invarname]._FillValue\nunits = dataset.variables[invarname].units\nfield = dataset.variables[invarname].field\nlong_name = dataset.variables[invarname].long_name\n#dataset.close()\n\n\nretry_day = []\n\n# loop over records, 73 hours apart\noutfile = 'data/Pacific_%s_%04d.nc' %(outvarname,year)\ncreate_HYCOM_file(outfile)\nday_out = 0\nfor day in range(rec_start,rec_end):\n print('Processing file for %s, day %d, year %04d' %(invarname, day_out*3, year))\n #get data from server\n try:\n var = dataset.variables[invarname][day,:,170:215,195:265]\n# spval = var.get_fill_value()\n# dataset.close()\n print('Got %s from server...' %invarname)\n except:\n print('No file on the server... We skip this day.')\n retry_day.append((day,day_out))\n continue\n\n #create netCDF file\n nc.variables[outvarname][day_out] = var\n jday = pyroms_toolbox.date2jday(datetime(year, 1, 1)) + day_out*73/24.\n nc.variables['ocean_time'][day_out] = jday\n day_out += 1\n\n\nif retry == 'True':\n if len(retry_day) != 0:\n print(\"Some file have not been downloded... Let's try again\")\n while len(retry_day) != 0:\n for (day,day_out) in retry_day:\n print('Retry file for %s, day %03d, year %04d' %(invarname, day_out, year))\n #get data from server\n try:\n var = dataset.variables[invarname][day,:,170:215,195:265]\n# spval = var.get_fill_value()\n print('Got %s from server...' %invarname)\n except:\n print('No file on the server... We skip this day.')\n continue\n\n #create netCDF file\n jday = pyroms_toolbox.date2jday(datetime(year, 1, 1)) + day_out*73/24.\n nc.variables[outvarname][day_out] = var\n nc.variables['ocean_time'][day_out] = jday\n\n retry_day.remove((day,day_out))\n\n\ndataset.close()\nnc.close()\n" ]
[ [ "numpy.meshgrid", "scipy.interpolate.griddata", "numpy.array", "numpy.where", "numpy.zeros" ], [ "numpy.zeros" ], [ "numpy.meshgrid", "numpy.size", "numpy.array", "numpy.zeros", "numpy.where" ], [ "numpy.isnan", "numpy.maximum", "numpy.diff", "numpy.tile" ], [ "numpy.arctan2", "numpy.where", "numpy.cos", "numpy.ones" ], [ "numpy.distutils.misc_util.Configuration" ], [ "numpy.zeros" ], [ "matplotlib.use" ] ]
[ { "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": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [ "1.11", "1.19", "1.24", "1.16", "1.23", "1.20", "1.7", "1.12", "1.21", "1.22", "1.14", "1.6", "1.13", "1.9", "1.17", "1.10", "1.18", "1.15", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
alinaselega/gap_statistic
[ "2b94c46b676eef839f7709441a89bdc5796b2d31" ]
[ "tests/test_optimalK.py" ]
[ "# -*- coding: utf-8 -*-\nimport os\nimport pytest\n\nimport numpy as np\nfrom sklearn.datasets import make_blobs\nfrom sklearn.cluster import KMeans, MeanShift\n\nfrom gap_statistic import OptimalK\n\n\ndef test_bad_init_config():\n \"\"\"\n Cannot define own clustering function and try to use Rust backend\n \"\"\"\n with pytest.raises(ValueError):\n OptimalK(parallel_backend=\"rust\", clusterer=lambda x, k: print(\"just testing\"))\n\n\[email protected](\"ClusterModel\", [KMeans, MeanShift])\ndef test_alternative_clusting_method(ClusterModel):\n \"\"\"\n Test that users can supply alternative clustering method as dep injection\n \"\"\"\n\n def clusterer(X: np.ndarray, k: int, another_test_arg):\n \"\"\"\n Function to wrap a sklearn model as a clusterer for OptimalK\n First two arguments are always the data matrix, and k, and can supply\n \"\"\"\n m = ClusterModel()\n m.fit(X)\n assert another_test_arg == \"test\"\n return m.cluster_centers_, m.predict(X)\n\n optimalk = OptimalK(\n n_jobs=-1,\n parallel_backend=\"joblib\",\n clusterer=clusterer,\n clusterer_kwargs={\"another_test_arg\": \"test\"},\n )\n X, y = make_blobs(n_samples=50, n_features=2, centers=3)\n n_clusters = optimalk(X, n_refs=3, cluster_array=np.arange(1, 5))\n assert isinstance(n_clusters, int)\n\n\[email protected](\n \"parallel_backend, n_jobs, n_clusters\",\n [\n pytest.param(\n \"joblib\", 1, 3, id=\"parallel_backend='joblib', n_jobs=1, n_clusters=3\"\n ),\n pytest.param(None, 1, 3, id=\"parallel_backend=None, n_jobs=1, n_clusters=3\"),\n # TODO: Add back this test param in rust side extension\n # pytest.param(\n # \"rust\", 1, 3, id=\"parallel_backend='rust', n_jobs=1, n_clusters=3\"\n # ),\n ],\n)\ndef test_optimalk(parallel_backend, n_jobs, n_clusters):\n \"\"\"\n Test core functionality of OptimalK using all backends.\n \"\"\"\n\n # Create optimalK instance\n optimalK = OptimalK(parallel_backend=parallel_backend, n_jobs=n_jobs)\n\n # Create data\n X, y = make_blobs(n_samples=int(1e3), n_features=2, centers=3)\n\n suggested_clusters = optimalK(X, n_refs=3, cluster_array=np.arange(1, 10))\n\n assert np.allclose(\n suggested_clusters, n_clusters, 2\n ), \"Correct clusters is {}, OptimalK suggested {}\".format(\n n_clusters, suggested_clusters\n )\n\n\[email protected](\n \"TEST_RUST_EXT\" not in os.environ, reason=\"Rust extension not built.\"\n)\ndef test_optimalk_rust_ext():\n \"\"\"\n Test core functionality of OptimalK using all backends.\n \"\"\"\n\n # Create optimalK instance\n optimalK = OptimalK(parallel_backend=\"rust\", n_jobs=1)\n\n # Create data\n X, y = make_blobs(n_samples=int(1e3), n_features=2, centers=3)\n\n suggested_clusters = optimalK(X, n_refs=3, cluster_array=np.arange(1, 10))\n\n assert np.allclose(\n suggested_clusters, 3, 2\n ), \"Correct clusters is {}, OptimalK suggested {}\".format(3, suggested_clusters)\n\n\ndef test_optimalk_cluster_array_vs_data_sizes_error():\n \"\"\"\n Test ValueError when cluster_array is larger than dataset.\n \"\"\"\n import numpy as np\n from gap_statistic import OptimalK\n\n # Create optimalK instance\n optimalK = OptimalK(parallel_backend=None, n_jobs=-1)\n\n # Create data\n X, y = make_blobs(n_samples=5, n_features=2, centers=3)\n\n with pytest.raises(ValueError) as excinfo:\n optimalK(X, cluster_array=np.arange(1, 10))\n assert \"The number of suggested clusters to try\" in str(excinfo.value)\n\n\ndef test_optimalk_cluster_array_values_error():\n \"\"\"\n Test ValueError when cluster_array contains values less than 1\n \"\"\"\n from gap_statistic import OptimalK\n\n # Create optimalK instance\n optimalK = OptimalK(parallel_backend=None, n_jobs=-1)\n\n # Create data\n X, y = make_blobs(n_samples=int(1e3), n_features=2, centers=3)\n\n with pytest.raises(ValueError) as excinfo:\n optimalK(X, cluster_array=[0, -1, 1, 2, 3])\n assert \"cluster_array contains values less than 1\" in str(excinfo.value)\n\n\ndef test_optimalk_cluster_array_empty_error():\n \"\"\"\n Test ValueError when cluster_array is empty.\n \"\"\"\n from gap_statistic import OptimalK\n\n # Create optimalK instance\n optimalK = OptimalK(parallel_backend=None, n_jobs=-1)\n\n # Create data\n X, y = make_blobs(n_samples=int(1e3), n_features=2, centers=3)\n\n with pytest.raises(ValueError) as excinfo:\n optimalK(X, cluster_array=[])\n assert \"The supplied cluster_array has no values.\" in str(excinfo.value)\n\n\ndef test_dunders():\n \"\"\"\n Test that implemented dunder methods don't return errors\n \"\"\"\n from gap_statistic import OptimalK\n\n optimalK = OptimalK()\n optimalK.__str__()\n optimalK.__repr__()\n optimalK._repr_html_()\n" ]
[ [ "numpy.arange", "numpy.allclose", "sklearn.datasets.make_blobs" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
noushadkhan01/my_methods
[ "fc467d5c34b9b5dd105e32cc5aad218d3f6408a8" ]
[ "my_methods/my_cap_curve.py" ]
[ "def my_cap_curve(model, X, y, figsize = (10, 5),legend_font_size = 10,loc = 'best',\n linewidth = 2,label_font_size = 10, poly_features = False, extra_name = None):\n import matplotlib.pyplot as plt\n import numpy as np\n import my_global_variables\n from sklearn.metrics import roc_curve, auc\n class_name = model.__class__.__name__\n if poly_features:\n class_name = class_name + '_poly'\n if extra_name:\n class_name += '_' + extra_name\n total = len(y)\n class_1_count = np.sum(y)\n class_0_count = total - class_1_count\n probs = model.predict_proba(X)\n probs = probs[:, 1]\n model_y = [y for _, y in sorted(zip(probs, y), reverse = True)]\n y_values = np.append([0], np.cumsum(model_y))\n x_values = np.arange(0, total + 1)\n # Area under Random Model\n a = auc([0, total], [0, class_1_count])\n\n # Area between Perfect and Random Model\n aP = auc([0, class_1_count, total], [0, class_1_count, class_1_count]) - a\n\n # Area between Trained and Random Model\n aR = auc(x_values, y_values) - a\n plt.figure(figsize = (figsize))\n plt.plot([0, total], [0, class_1_count], c = 'r', linestyle = '--', label = 'Random Model')\n plt.plot([0, class_1_count, total], [0, class_1_count, class_1_count], c = 'grey', linewidth = linewidth, label = 'Perfect Model')\n plt.plot(x_values, y_values, c = 'b', label = f'{class_name} Classifier Accuracy Rate = {aR/aP}', linewidth = linewidth)\n plt.xlabel('Total observations', fontsize = label_font_size)\n plt.ylabel('Class 1 observations', fontsize = label_font_size)\n plt.title('Cumulative Accuracy Profile', fontsize = label_font_size)\n plt.legend(loc = loc, fontsize = legend_font_size)\n plt.show()\n my_global_variables.model_cap_scores[class_name] = aR/aP\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.title", "numpy.arange", "numpy.cumsum", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "sklearn.metrics.auc", "matplotlib.pyplot.show", "numpy.sum", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
akurniawan/jina-hub
[ "d89bc5e8f527f1212c3228a15775e222983c0087" ]
[ "encoders/audio/Wav2VecSpeechEncoder/__init__.py" ]
[ "__copyright__ = \"Copyright (c) 2020 Jina AI Limited. All rights reserved.\"\n__license__ = \"Apache-2.0\"\n\nimport os\nfrom typing import Optional\n\nimport numpy as np\n\nfrom jina.executors.decorators import batching, as_ndarray\nfrom jina.executors.encoders import BaseAudioEncoder\nfrom jina.executors.encoders.frameworks import BaseTorchEncoder\nfrom jina.excepts import PretrainedModelFileDoesNotExist\nfrom jina.helper import cached_property\n\n\nclass Wav2VecSpeechEncoder(BaseTorchEncoder, BaseAudioEncoder):\n \"\"\"\n Use a pre-trained model (`wav2vec`) to encode audio signal.\n\n :class:`Wav2VecSpeechEncoder` is a speech encoder based on `wav2vec`,\n an unsupervised pre-trained model for speech recognition presented and implemented\n by Facebook: https://github.com/pytorch/fairseq/tree/master/examples/wav2vec\n It uses a pre-trained model to encode an audio signal from\n a `Batch x Signal Length` ndarray into a `Batch x Concatenated Features` ndarray,\n and produces a representation for each time step at a rate of 100 Hz.\n\n :param model_path: the path of the pre-trained model.\n The pre-trained model can be downloaded at\n https://github.com/pytorch/fairseq/tree/master/examples/wav2vec/README.md#wav2vec\n :param input_sample_rate: input sampling rate in Hz (22050 by default)\n \"\"\"\n\n def __init__(self,\n model_path: Optional[str] = '/tmp/wav2vec_large.pt',\n input_sample_rate: int = 22050,\n *args,\n **kwargs):\n \"\"\"Set Constructor\"\"\"\n super().__init__(*args, **kwargs)\n self.model_path = model_path\n self.input_sample_rate = input_sample_rate\n\n def post_init(self):\n super().post_init()\n if self.model_path and os.path.exists(self.model_path):\n import torch\n from fairseq.models.wav2vec import Wav2VecModel\n cp = torch.load(self.model_path, map_location=torch.device('cpu'))\n self.model = Wav2VecModel.build_model(cp['args'], task=None)\n self.model.load_state_dict(cp['model'])\n self.model.eval()\n self.to_device(self.model)\n self._tensor_func = torch.tensor\n else:\n raise PretrainedModelFileDoesNotExist(f'model at {self.model_path} does not exist')\n\n @batching\n @as_ndarray\n def encode(self, data: np.ndarray, *args, **kwargs) -> np.ndarray:\n \"\"\"\n Resample input audio signal to 16kHz.\n\n Segments the resampled signal of each Doc into `wav2vec` frames,\n encodes the frames and concatenates Doc frame embeddings into a\n single Doc embedding.\n\n :param data: A`Batch x Signal Length` ndarray, where\n `Signal Length` is a number of samples\n :return: A `Batch x Concatenated Features` ndarray,\n where `Concatenated Features` is a 512-dimensional feature\n vector times the number of the wav2vec frames.\n \"\"\"\n assert data.shape[1] >= 465, 'the signal must have at least 465 samples'\n from librosa import resample\n embeds = []\n with self.session():\n for chunk_data in data:\n resampled_signal = resample(chunk_data, self.input_sample_rate, 16000)\n signal_tensor = self.array2tensor(resampled_signal.reshape(1, -1))\n features = self.model.feature_extractor(signal_tensor)\n embed_tensor = self.model.feature_aggregator(features)[0]\n chunk_embed = self.tensor2array(embed_tensor).T.flatten()\n embeds.append(chunk_embed)\n return embeds\n\n def array2tensor(self, array):\n tensor = self._tensor_func(array)\n return tensor.cuda() if self.on_gpu else tensor\n\n def tensor2array(self, tensor):\n return tensor.cuda().numpy() if self.on_gpu else tensor.numpy()\n\n @cached_property\n def session(self):\n return self.get_session()\n\n def get_session(self):\n from torch import no_grad\n return no_grad" ]
[ [ "torch.device" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
vigneshyaadav27/Grid-world
[ "a5c4cab46cdafc6458526593ae31ac19a152001d" ]
[ "grid_world.py" ]
[ "#######################################################################\r\n# Copyright (C) #\r\n# 2016-2018 Shangtong Zhang([email protected]) #\r\n# 2016 Kenta Shimada([email protected]) #\r\n# Permission given to modify the code as long as you keep this #\r\n# declaration at the top #\r\n#######################################################################\r\n\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom matplotlib.table import Table\r\n\r\nmatplotlib.use('Agg')\r\n\r\nWORLD_SIZE = 5\r\nA_POS = [0, 1]\r\nA_PRIME_POS = [4, 1]\r\nB_POS = [0, 3]\r\nB_PRIME_POS = [2, 3]\r\nDISCOUNT = 0.9\r\n\r\n# left, up, right, down\r\nACTIONS = [np.array([0, -1]),\r\n np.array([-1, 0]),\r\n np.array([0, 1]),\r\n np.array([1, 0])]\r\nACTIONS_FIGS=[ '←', '↑', '→', '↓']\r\n\r\n\r\nACTION_PROB = 0.25\r\n\r\n\r\ndef step(state, action):\r\n if state == A_POS:\r\n return A_PRIME_POS, 10\r\n if state == B_POS:\r\n return B_PRIME_POS, 5\r\n\r\n next_state = (np.array(state) + action).tolist()\r\n x, y = next_state\r\n if x < 0 or x >= WORLD_SIZE or y < 0 or y >= WORLD_SIZE:\r\n reward = -1.0\r\n next_state = state\r\n else:\r\n reward = 0\r\n return next_state, reward\r\n\r\n\r\ndef draw_image(image):\r\n fig, ax = plt.subplots()\r\n ax.set_axis_off()\r\n tb = Table(ax, bbox=[0, 0, 1, 1])\r\n\r\n nrows, ncols = image.shape\r\n width, height = 1.0 / ncols, 1.0 / nrows\r\n\r\n # Add cells\r\n for (i, j), val in np.ndenumerate(image):\r\n\r\n # add state labels\r\n if [i, j] == A_POS:\r\n val = str(val) + \" (A)\"\r\n if [i, j] == A_PRIME_POS:\r\n val = str(val) + \" (A')\"\r\n if [i, j] == B_POS:\r\n val = str(val) + \" (B)\"\r\n if [i, j] == B_PRIME_POS:\r\n val = str(val) + \" (B')\"\r\n \r\n tb.add_cell(i, j, width, height, text=val,\r\n loc='center', facecolor='white')\r\n \r\n\r\n # Row and column labels...\r\n for i in range(len(image)):\r\n tb.add_cell(i, -1, width, height, text=i+1, loc='right',\r\n edgecolor='none', facecolor='none')\r\n tb.add_cell(-1, i, width, height/2, text=i+1, loc='center',\r\n edgecolor='none', facecolor='none')\r\n\r\n ax.add_table(tb)\r\n\r\ndef draw_policy(optimal_values):\r\n fig, ax = plt.subplots()\r\n ax.set_axis_off()\r\n tb = Table(ax, bbox=[0, 0, 1, 1])\r\n\r\n nrows, ncols = optimal_values.shape\r\n width, height = 1.0 / ncols, 1.0 / nrows\r\n\r\n # Add cells\r\n for (i, j), val in np.ndenumerate(optimal_values):\r\n next_vals=[]\r\n for action in ACTIONS:\r\n next_state, _ = step([i, j], action)\r\n next_vals.append(optimal_values[next_state[0],next_state[1]])\r\n\r\n best_actions=np.where(next_vals == np.max(next_vals))[0]\r\n val=''\r\n for ba in best_actions:\r\n val+=ACTIONS_FIGS[ba]\r\n \r\n # add state labels\r\n if [i, j] == A_POS:\r\n val = str(val) + \" (A)\"\r\n if [i, j] == A_PRIME_POS:\r\n val = str(val) + \" (A')\"\r\n if [i, j] == B_POS:\r\n val = str(val) + \" (B)\"\r\n if [i, j] == B_PRIME_POS:\r\n val = str(val) + \" (B')\"\r\n \r\n tb.add_cell(i, j, width, height, text=val,\r\n loc='center', facecolor='white')\r\n\r\n # Row and column labels...\r\n for i in range(len(optimal_values)):\r\n tb.add_cell(i, -1, width, height, text=i+1, loc='right',\r\n edgecolor='none', facecolor='none')\r\n tb.add_cell(-1, i, width, height/2, text=i+1, loc='center',\r\n edgecolor='none', facecolor='none')\r\n\r\n ax.add_table(tb)\r\n\r\n\r\ndef figure_3_2():\r\n value = np.zeros((WORLD_SIZE, WORLD_SIZE))\r\n while True:\r\n # keep iteration until convergence\r\n new_value = np.zeros_like(value)\r\n for i in range(WORLD_SIZE):\r\n for j in range(WORLD_SIZE):\r\n for action in ACTIONS:\r\n (next_i, next_j), reward = step([i, j], action)\r\n # bellman equation\r\n new_value[i, j] += ACTION_PROB * (reward + DISCOUNT * value[next_i, next_j])\r\n if np.sum(np.abs(value - new_value)) < 1e-4:\r\n draw_image(np.round(new_value, decimals=2))\r\n plt.savefig('../images/figure_3_2.png')\r\n plt.close()\r\n break\r\n value = new_value\r\n\r\ndef figure_3_2_linear_system():\r\n '''\r\n Here we solve the linear system of equations to find the exact solution.\r\n We do this by filling the coefficients for each of the states with their respective right side constant.\r\n '''\r\n A = -1 * np.eye(WORLD_SIZE * WORLD_SIZE)\r\n b = np.zeros(WORLD_SIZE * WORLD_SIZE)\r\n for i in range(WORLD_SIZE):\r\n for j in range(WORLD_SIZE):\r\n s = [i, j] # current state\r\n index_s = np.ravel_multi_index(s, (WORLD_SIZE, WORLD_SIZE))\r\n for a in ACTIONS:\r\n s_, r = step(s, a)\r\n index_s_ = np.ravel_multi_index(s_, (WORLD_SIZE, WORLD_SIZE))\r\n\r\n A[index_s, index_s_] += ACTION_PROB * DISCOUNT\r\n b[index_s] -= ACTION_PROB * r\r\n\r\n x = np.linalg.solve(A, b)\r\n draw_image(np.round(x.reshape(WORLD_SIZE, WORLD_SIZE), decimals=2))\r\n plt.savefig('../images/figure_3_2_linear_system.png')\r\n plt.close()\r\n\r\ndef figure_3_5():\r\n value = np.zeros((WORLD_SIZE, WORLD_SIZE))\r\n while True:\r\n # keep iteration until convergence\r\n new_value = np.zeros_like(value)\r\n for i in range(WORLD_SIZE):\r\n for j in range(WORLD_SIZE):\r\n values = []\r\n for action in ACTIONS:\r\n (next_i, next_j), reward = step([i, j], action)\r\n # value iteration\r\n values.append(reward + DISCOUNT * value[next_i, next_j])\r\n new_value[i, j] = np.max(values)\r\n if np.sum(np.abs(new_value - value)) < 1e-4:\r\n draw_image(np.round(new_value, decimals=2))\r\n plt.savefig('../images/figure_3_5.png')\r\n plt.close()\r\n draw_policy(new_value)\r\n plt.savefig('../images/figure_3_5_policy.png')\r\n plt.close()\r\n break\r\n value = new_value\r\n\r\n\r\nif __name__ == '__main__':\r\n figure_3_2_linear_system()\r\n figure_3_2()\r\n figure_3_5()\r\n" ]
[ [ "numpy.linalg.solve", "numpy.abs", "matplotlib.use", "numpy.eye", "matplotlib.pyplot.subplots", "matplotlib.pyplot.savefig", "numpy.round", "matplotlib.table.Table", "numpy.max", "numpy.zeros_like", "matplotlib.pyplot.close", "numpy.ravel_multi_index", "numpy.ndenumerate", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
seiyab/chainer
[ "39fffb9597a6e9646307fba27ad3233c65d38632" ]
[ "chainer/training/extensions/variable_statistics_plot.py" ]
[ "from __future__ import division\nimport os\nimport warnings\n\nimport numpy\nimport six\n\nimport chainer\nfrom chainer import backend\nfrom chainer.backends import cuda\nfrom chainer.training import extension\nfrom chainer.training import trigger as trigger_module\nfrom chainer.utils import argument\n\n\n_available = None\n\n\ndef _try_import_matplotlib():\n global matplotlib, _available\n global _plot_color, _plot_color_trans, _plot_common_kwargs\n try:\n import matplotlib\n _available = True\n except ImportError:\n _available = False\n\n if _available:\n if hasattr(matplotlib.colors, 'to_rgba'):\n _to_rgba = matplotlib.colors.to_rgba\n else:\n # For matplotlib 1.x\n _to_rgba = matplotlib.colors.ColorConverter().to_rgba\n _plot_color = _to_rgba('#1f77b4') # C0 color\n _plot_color_trans = _plot_color[:3] + (0.2,) # apply alpha\n _plot_common_kwargs = {\n 'alpha': 0.2, 'linewidth': 0, 'color': _plot_color_trans}\n\n\ndef _check_available():\n if _available is None:\n _try_import_matplotlib()\n\n if not _available:\n warnings.warn('matplotlib is not installed on your environment, '\n 'so nothing will be plotted at this time. '\n 'Please install matplotlib to plot figures.\\n\\n'\n ' $ pip install matplotlib\\n')\n\n\ndef _unpack_variables(x, memo=None):\n if memo is None:\n memo = ()\n if isinstance(x, chainer.Variable):\n memo += (x,)\n elif isinstance(x, chainer.Link):\n memo += tuple(x.params(include_uninit=True))\n elif isinstance(x, (list, tuple)):\n for xi in x:\n memo += _unpack_variables(xi)\n return memo\n\n\nclass Reservoir(object):\n\n \"\"\"Reservoir sample with a fixed sized buffer.\"\"\"\n\n def __init__(self, size, data_shape, dtype=numpy.float32):\n self.size = size\n self.data = numpy.zeros((size,) + data_shape, dtype=dtype)\n self.idxs = numpy.zeros((size,), dtype=numpy.int32)\n self.counter = 0\n\n def add(self, x, idx=None):\n if self.counter < self.size:\n self.data[self.counter] = x\n self.idxs[self.counter] = idx or self.counter\n elif self.counter >= self.size and \\\n numpy.random.random() < self.size / float(self.counter + 1):\n i = numpy.random.randint(self.size)\n self.data[i] = x\n self.idxs[i] = idx or self.counter\n self.counter += 1\n\n def get_data(self):\n idxs = self.idxs[:min(self.counter, self.size)]\n sorted_args = numpy.argsort(idxs)\n return idxs[sorted_args], self.data[sorted_args]\n\n\nclass Statistician(object):\n\n \"\"\"Helper to compute basic NumPy-like statistics.\"\"\"\n\n def __init__(self, collect_mean, collect_std, percentile_sigmas):\n self.collect_mean = collect_mean\n self.collect_std = collect_std\n self.percentile_sigmas = percentile_sigmas\n\n def __call__(self, x, axis=0, dtype=None, xp=None):\n if axis is None:\n axis = tuple(range(x.ndim))\n elif not isinstance(axis, (tuple, list)):\n axis = axis,\n\n return self.collect(x, axis)\n\n def collect(self, x, axis):\n out = dict()\n\n if self.collect_mean:\n out['mean'] = x.mean(axis=axis)\n\n if self.collect_std:\n out['std'] = x.std(axis=axis)\n\n if self.percentile_sigmas:\n xp = cuda.get_array_module(x)\n p = xp.percentile(x, self.percentile_sigmas, axis=axis)\n out['percentile'] = p\n\n return out\n\n\nclass VariableStatisticsPlot(extension.Extension):\n\n \"\"\"__init__(\\\n targets, max_sample_size=1000, report_data=True,\\\n report_grad=True, plot_mean=True, plot_std=True,\\\n percentile_sigmas=(0, 0.13, 2.28, 15.87, 50, 84.13, 97.72, 99.87,\\\n 100), trigger=(1, 'epoch'), filename='statistics.png',\\\n figsize=None, marker=None, grid=True)\n\n Trainer extension to plot statistics for :class:`Variable`\\\\s.\n\n This extension collects statistics for a single :class:`Variable`, a list\n of :class:`Variable`\\\\s or similarly a single or a list of\n :class:`Link`\\\\s containing one or more :class:`Variable`\\\\s. In case\n multiple :class:`Variable`\\\\s are found, the means are computed. The\n collected statistics are plotted and saved as an image in the directory\n specified by the :class:`Trainer`.\n\n Statistics include mean, standard deviation and percentiles.\n\n This extension uses reservoir sampling to preserve memory, using a fixed\n size running sample. This means that collected items in the sample are\n discarded uniformly at random when the number of items becomes larger\n than the maximum sample size, but each item is expected to occur in the\n sample with equal probability.\n\n Args:\n targets (:class:`Variable`, :class:`Link` or list of either):\n Parameters for which statistics are collected.\n max_sample_size (int):\n Maximum number of running samples.\n report_data (bool):\n If ``True``, data (e.g. weights) statistics are plotted. If\n ``False``, they are neither computed nor plotted.\n report_grad (bool):\n If ``True``, gradient statistics are plotted. If ``False``, they\n are neither computed nor plotted.\n plot_mean (bool):\n If ``True``, means are plotted. If ``False``, they are\n neither computed nor plotted.\n plot_std (bool):\n If ``True``, standard deviations are plotted. If ``False``, they\n are neither computed nor plotted.\n percentile_sigmas (float or tuple of floats):\n Percentiles to plot in the range :math:`[0, 100]`.\n trigger:\n Trigger that decides when to save the plots as an image. This is\n distinct from the trigger of this extension itself. If it is a\n tuple in the form ``<int>, 'epoch'`` or ``<int>, 'iteration'``, it\n is passed to :class:`IntervalTrigger`.\n filename (str):\n Name of the output image file under the output directory.\n For historical reasons ``file_name`` is also accepted as an alias\n of this argument.\n figsize (tuple of int):\n Matlotlib ``figsize`` argument that specifies the size of the\n output image.\n marker (str):\n Matplotlib ``marker`` argument that specified the marker style of\n the plots.\n grid (bool):\n Matplotlib ``grid`` argument that specifies whether grids are\n rendered in in the plots or not.\n \"\"\"\n\n def __init__(self, targets, max_sample_size=1000,\n report_data=True, report_grad=True,\n plot_mean=True, plot_std=True,\n percentile_sigmas=(\n 0, 0.13, 2.28, 15.87, 50, 84.13, 97.72, 99.87, 100),\n trigger=(1, 'epoch'), filename=None,\n figsize=None, marker=None, grid=True, **kwargs):\n\n file_name, = argument.parse_kwargs(\n kwargs, ('file_name', 'statistics.png')\n )\n if filename is None:\n filename = file_name\n del file_name # avoid accidental use\n\n self._vars = _unpack_variables(targets)\n if not self._vars:\n raise ValueError(\n 'Need at least one variables for which to collect statistics.'\n '\\nActual: 0 <= 0')\n\n if not any((plot_mean, plot_std, bool(percentile_sigmas))):\n raise ValueError('Nothing to plot')\n\n self._keys = []\n if report_data:\n self._keys.append('data')\n if report_grad:\n self._keys.append('grad')\n\n self._report_data = report_data\n self._report_grad = report_grad\n\n self._statistician = Statistician(\n collect_mean=plot_mean, collect_std=plot_std,\n percentile_sigmas=percentile_sigmas)\n\n self._plot_mean = plot_mean\n self._plot_std = plot_std\n self._plot_percentile = bool(percentile_sigmas)\n\n self._trigger = trigger_module.get_trigger(trigger)\n self._filename = filename\n self._figsize = figsize\n self._marker = marker\n self._grid = grid\n\n if not self._plot_percentile:\n n_percentile = 0\n else:\n if not isinstance(percentile_sigmas, (list, tuple)):\n n_percentile = 1 # scalar, single percentile\n else:\n n_percentile = len(percentile_sigmas)\n self._data_shape = (\n len(self._keys), int(plot_mean) + int(plot_std) + n_percentile)\n self._samples = Reservoir(max_sample_size, data_shape=self._data_shape)\n\n @staticmethod\n def available():\n _check_available()\n return _available\n\n def __call__(self, trainer):\n if self.available():\n # Dynamically import pyplot to call matplotlib.use()\n # after importing chainer.training.extensions\n import matplotlib.pyplot as plt\n else:\n return\n\n xp = backend.get_array_module(self._vars[0].data)\n stats = xp.zeros(self._data_shape, dtype=xp.float32)\n for i, k in enumerate(self._keys):\n xs = []\n for var in self._vars:\n x = getattr(var, k, None)\n if x is not None:\n xs.append(x.ravel())\n if xs:\n stat_dict = self._statistician(\n xp.concatenate(xs, axis=0), axis=0, xp=xp)\n stat_list = []\n if self._plot_mean:\n stat_list.append(xp.atleast_1d(stat_dict['mean']))\n if self._plot_std:\n stat_list.append(xp.atleast_1d(stat_dict['std']))\n if self._plot_percentile:\n stat_list.append(xp.atleast_1d(stat_dict['percentile']))\n stats[i] = xp.concatenate(stat_list, axis=0)\n\n if xp == cuda.cupy:\n stats = cuda.to_cpu(stats)\n self._samples.add(stats, idx=trainer.updater.iteration)\n\n if self._trigger(trainer):\n file_path = os.path.join(trainer.out, self._filename)\n self.save_plot_using_module(file_path, plt)\n\n def save_plot_using_module(self, file_path, plt):\n nrows = int(self._plot_mean or self._plot_std) \\\n + int(self._plot_percentile)\n ncols = len(self._keys)\n\n fig, axes = plt.subplots(\n nrows, ncols, figsize=self._figsize, sharex=True)\n\n if not isinstance(axes, numpy.ndarray): # single subplot\n axes = numpy.asarray([axes])\n if nrows == 1:\n axes = axes[None, :]\n elif ncols == 1:\n axes = axes[:, None]\n assert axes.ndim == 2\n\n idxs, data = self._samples.get_data()\n\n # Offset to access percentile data from `data`\n offset = int(self._plot_mean) + int(self._plot_std)\n n_percentile = data.shape[-1] - offset\n n_percentile_mid_floor = n_percentile // 2\n n_percentile_odd = n_percentile % 2 == 1\n\n for col in six.moves.range(ncols):\n row = 0\n ax = axes[row, col]\n ax.set_title(self._keys[col]) # `data` or `grad`\n\n if self._plot_mean or self._plot_std:\n if self._plot_mean and self._plot_std:\n ax.errorbar(\n idxs, data[:, col, 0], data[:, col, 1],\n color=_plot_color, ecolor=_plot_color_trans,\n label='mean, std', marker=self._marker)\n else:\n if self._plot_mean:\n label = 'mean'\n elif self._plot_std:\n label = 'std'\n ax.plot(\n idxs, data[:, col, 0], color=_plot_color, label=label,\n marker=self._marker)\n row += 1\n\n if self._plot_percentile:\n ax = axes[row, col]\n for i in six.moves.range(n_percentile_mid_floor + 1):\n if n_percentile_odd and i == n_percentile_mid_floor:\n # Enters at most once per sub-plot, in case there is\n # only a single percentile to plot or when this\n # percentile is the mid percentile and the number of\n # percentiles are odd\n ax.plot(\n idxs, data[:, col, offset + i], color=_plot_color,\n label='percentile', marker=self._marker)\n else:\n if i == n_percentile_mid_floor:\n # Last percentiles and the number of all\n # percentiles are even\n label = 'percentile'\n else:\n label = '_nolegend_'\n ax.fill_between(\n idxs,\n data[:, col, offset + i],\n data[:, col, -i - 1],\n label=label,\n **_plot_common_kwargs)\n ax.set_xlabel('iteration')\n\n for ax in axes.ravel():\n ax.legend()\n if self._grid:\n ax.grid()\n ax.set_axisbelow(True)\n\n fig.savefig(file_path)\n plt.close()\n" ]
[ [ "numpy.random.random", "numpy.asarray", "matplotlib.pyplot.subplots", "matplotlib.colors.ColorConverter", "matplotlib.pyplot.close", "numpy.argsort", "numpy.zeros", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Gikiman/executors
[ "98658b4136859164390cfccbde8cf0f7cf843593" ]
[ "jinahub/encoders/audio/VGGISHAudioEncoder/vggish_audio_encoder.py" ]
[ "__copyright__ = \"Copyright (c) 2021 Jina AI Limited. All rights reserved.\"\n__license__ = \"Apache-2.0\"\n\nimport os\nfrom pathlib import Path\nfrom typing import Any, Optional, List, Iterable\n\nfrom jina import Executor, requests, DocumentArray\nfrom jina.logging.logger import JinaLogger\nimport requests as _requests\nimport tensorflow as tf\n\ntf.compat.v1.disable_eager_execution()\n\nfrom .vggish.vggish_postprocess import *\nfrom .vggish.vggish_slim import *\n\ncur_dir = os.path.dirname(os.path.abspath(__file__))\n\n\nclass VggishAudioEncoder(Executor):\n \"\"\"\n Encode audio data with Vggish embeddings\n\n :param model_path: path of the models directory\n :param default_traversal_paths: fallback batch size in case there is not batch size sent in the request\n \"\"\"\n\n def __init__(self,\n model_path: str = Path(cur_dir) / 'models',\n default_traversal_paths: Optional[Iterable[str]] = None,\n *args, **kwargs):\n\n super().__init__(*args, **kwargs)\n self.default_traversal_paths = default_traversal_paths or ['r']\n self.logger = JinaLogger(self.__class__.__name__)\n\n self.model_path = Path(model_path)\n self.vgg_model_path = self.model_path / 'vggish_model.ckpt'\n self.pca_model_path = self.model_path / 'vggish_pca_params.ckpt'\n self.model_path.mkdir(exist_ok=True) # Create the model directory if it does not exist yet\n\n if not self.vgg_model_path.exists():\n self.logger.info('VGGish model cannot be found from the given model path, downloading a new one...')\n try:\n r = _requests.get('https://storage.googleapis.com/audioset/vggish_model.ckpt')\n r.raise_for_status()\n except _requests.exceptions.HTTPError:\n self.logger.error('received HTTP error response, cannot download vggish model')\n raise\n except _requests.exceptions.RequestException:\n self.logger.error('Connection error, cannot download vggish model')\n raise\n\n with open(self.vgg_model_path, 'wb') as f:\n f.write(r.content)\n\n if not self.pca_model_path.exists():\n self.logger.info('PCA model cannot be found from the given model path, downloading a new one...')\n try:\n r = _requests.get('https://storage.googleapis.com/audioset/vggish_pca_params.npz')\n r.raise_for_status()\n except _requests.exceptions.HTTPError:\n self.logger.error('received HTTP error response, cannot download pca model')\n raise\n except _requests.exceptions.RequestException:\n self.logger.error('Connection error, cannot download pca model')\n raise\n\n with open(self.pca_model_path, 'wb') as f:\n f.write(r.content)\n\n\n self.sess = tf.compat.v1.Session()\n define_vggish_slim()\n load_vggish_slim_checkpoint(self.sess, str(self.vgg_model_path))\n self.feature_tensor = self.sess.graph.get_tensor_by_name(\n INPUT_TENSOR_NAME)\n self.embedding_tensor = self.sess.graph.get_tensor_by_name(\n OUTPUT_TENSOR_NAME)\n self.post_processor = Postprocessor(str(self.pca_model_path))\n\n @requests\n def encode(self, docs: Optional[DocumentArray], parameters: dict, **kwargs):\n \"\"\"\n Compute embeddings and store them in the `docs` array.\n\n :param docs: documents sent to the encoder. The docs must have `text`.\n By default, the input `text` must be a `list` of `str`.\n :param parameters: dictionary to define the `traversal_paths` and the `batch_size`. For example,\n `parameters={'traversal_paths': ['r'], 'batch_size': 10}`.\n :param kwargs: Additional key value arguments.\n :return:\n \"\"\"\n if docs:\n cleaned_document_array = self._get_input_data(docs, parameters)\n self._create_embeddings(cleaned_document_array)\n\n def _get_input_data(self, docs: DocumentArray, parameters: dict):\n \"\"\"Create a filtered set of Documents to iterate over.\"\"\"\n\n traversal_paths = parameters.get('traversal_paths', self.default_traversal_paths)\n\n # traverse thought all documents which have to be processed\n flat_docs = docs.traverse_flat(traversal_paths)\n\n # filter out documents without images\n filtered_docs = DocumentArray([doc for doc in flat_docs if doc.blob is not None])\n\n return filtered_docs\n\n def _create_embeddings(self, filtered_docs: Iterable):\n \"\"\"Update the documents with the embeddings generated by VGGISH\"\"\"\n\n for d in filtered_docs:\n # Vggish broadcasts across different length audios, not batches\n [embedding] = self.sess.run([self.embedding_tensor], feed_dict={self.feature_tensor: d.blob})\n result = self.post_processor.postprocess(embedding)\n d.embedding = np.mean((np.float32(result) - 128.) / 128., axis=0)\n\n def close(self):\n self.sess.close()\n" ]
[ [ "tensorflow.compat.v1.Session", "tensorflow.compat.v1.disable_eager_execution" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
iguarna/uwb-ieee
[ "782813b8a6fc9effeb076c47cd5d497b6e62b330" ]
[ "uwb_channel.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef gen_channel(parameters, fc=5E9, fs=2E9, dynamic_range=30):\n\n # Calculate samples/nanosec ratio\n nanosec_to_samples = int(1E-9 * fs)\n\n #####################################\n # Unpack parameters and convert units\n\n cluster_rate = parameters['cluster_rate'] / nanosec_to_samples\n inter_cluster_rate_1 = parameters['inter_cluster_rate_1'] / nanosec_to_samples\n inter_cluster_rate_2 = parameters['inter_cluster_rate_2'] / nanosec_to_samples\n beta = parameters['beta']\n cluster_decay = parameters['cluster_decay'] * nanosec_to_samples\n inter_cluster_decay = parameters['inter_cluster_decay'] * nanosec_to_samples\n mean_m = parameters['mean_m']\n std_m = parameters['std_m']\n std_cluster_shadowing = parameters['std_cluster_shadowing']\n kf = parameters['kf']\n\n #########################\n # Obtain impulse response\n\n if inter_cluster_decay > cluster_decay:\n raise ValueError(\"Inter cluster decay cannot be larger than cluster decay.\")\n\n max_t = int(dynamic_range * cluster_decay * np.log(10) / 10)\n\n h = np.zeros(max_t, dtype=complex)\n\n t = 0\n\n while t < max_t:\n tau = 0\n\n max_tau = int((max_t - t) * inter_cluster_decay / cluster_decay)\n\n cluster_power = np.exp(-t / cluster_decay) * np.random.lognormal(mean=0, sigma=std_cluster_shadowing)\n\n while tau < max_tau:\n\n # Mean power for this ray\n mean_power = cluster_power * np.exp(-tau / inter_cluster_decay)\n\n # Nakagami m-factor is log normally distributed\n m = np.random.lognormal(mean_m, std_m)\n\n # Compute amplitude as Nakagami distributed\n a = np.sqrt(np.random.gamma(shape=m, scale=mean_power / m))\n\n # Compute phase as uniformly distributed\n phi = np.random.uniform(0, 2 * np.pi)\n\n h[t + tau] = np.array([a * np.exp(-1j * phi)])[0]\n\n if np.random.uniform(0, 1) < beta:\n inter_cluster_rate = inter_cluster_rate_1\n else:\n inter_cluster_rate = inter_cluster_rate_2\n\n tau += round(np.random.exponential(1 / inter_cluster_rate))\n\n t += round(np.random.exponential(1 / cluster_rate))\n\n ##########################\n # Add frequency dependency\n\n # Zero padding before FFT to avoid artifacts\n h = np.append(h, np.zeros(h.size, dtype=complex))\n\n H = np.fft.fft(h, norm='ortho')\n\n # Get frequency array in the same order as produced by the FFT\n freq = np.linspace(fc - fs / 2, fc + fs / 2, num=h.size)\n freq = np.append(freq[freq.size // 2:], freq[:freq.size // 2])\n\n # Calculate frequency dependency and apply\n Gf = np.power(freq, -2 * kf)\n H = np.multiply(Gf, H)\n\n # Inverse FFT\n h = np.fft.ifft(H, norm='ortho')\n\n # Remove padding\n h = h[:h.size // 2]\n\n ###############\n # Normalization\n\n h = normalize(h)\n\n return h\n\n\ndef normalize(s):\n return s / np.sqrt(energy(s))\n\n\ndef energy(s):\n return np.sum(np.square(np.abs(s)))\n\n\nif __name__ == '__main__':\n parameters_cm1 = {\n 'cluster_rate': 0.047,\n 'inter_cluster_rate_1': 1.54,\n 'inter_cluster_rate_2': 0.15,\n 'beta': 0.095,\n 'cluster_decay': 22.61,\n 'inter_cluster_decay': 12.53,\n 'mean_m': 0.67,\n 'std_m': 0.28,\n 'std_cluster_shadowing': 2.75,\n 'kf': 1.12,\n 'kd': 1.79,\n 'std_path_shadowing': 2.22\n\n }\n\n h = gen_channel(parameters=parameters_cm1,\n fc=(10.6E9 + 3.1E9) / 2,\n fs=6E9,\n dynamic_range=30)\n\n plt.plot(np.abs(h))\n plt.show()\n" ]
[ [ "numpy.random.lognormal", "numpy.log", "numpy.abs", "numpy.fft.fft", "numpy.power", "numpy.linspace", "numpy.multiply", "numpy.random.exponential", "numpy.fft.ifft", "numpy.append", "numpy.random.gamma", "numpy.exp", "numpy.random.uniform", "matplotlib.pyplot.show", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cbarros7/holbertonschool-machine_learning
[ "1edb4c253441f6319b86c9c590d1e7dd3fc32bf4", "1edb4c253441f6319b86c9c590d1e7dd3fc32bf4", "1edb4c253441f6319b86c9c590d1e7dd3fc32bf4", "1edb4c253441f6319b86c9c590d1e7dd3fc32bf4" ]
[ "supervised_learning/0x03-optimization/12-learning_rate_decay.py", "unsupervised_learning/0x03-hyperparameter_tuning/4-bayes_opt.py", "supervised_learning/0x01-classification/1-neuron.py", "supervised_learning/0x03-optimization/test/9-main.py" ]
[ "#!/usr/bin/env python3\n\"\"\"Learning Rate Decay Upgraded\"\"\"\nimport tensorflow as tf\n\n\ndef learning_rate_decay(alpha, decay_rate, global_step, decay_step):\n \"\"\"learning_rate_decay: creates a learning rate decay operation in\n tensorflow using inverse time decay:\n\n Args:\n alpha: is the original learning rate\n decay_rate: is the weight used to determine the rate at\n which alpha will decay\n global_step: is the number of passes of gradient descent\n that have elapsed\n decay_step: is the number of passes of gradient descent\n that should occur before alpha is decayed further\n\n Returns: the learning rate decay operation\n \"\"\"\n return tf.train.inverse_time_decay(\n learning_rate=alpha, global_step=global_step, decay_steps=decay_step,\n decay_rate=decay_rate, staircase=True, name=None\n )\n", "#!/usr/bin/env python3\n\"\"\"\n4-bayes_opt.py\n\"\"\"\nimport numpy as np\nfrom scipy.stats import norm\nGP = __import__('2-gp').GaussianProcess\n\n\nclass BayesianOptimization:\n \"\"\"\n Class that instantiates a Bayesian optimization\n on a noiseless 1D Gaussian process\n \"\"\"\n\n def __init__(self, f, X_init, Y_init, bounds,\n ac_samples, l=1, sigma_f=1, xsi=0.01, minimize=True):\n \"\"\"define and initialize variables and methods\"\"\"\n\n self.f = f\n self.gp = GP(X_init, Y_init, l, sigma_f)\n self.X_s = np.linspace(bounds[0], bounds[1],\n num=ac_samples)[..., np.newaxis]\n self.xsi = xsi\n self.minimize = minimize\n\n def acquisition(self):\n \"\"\"function that calculates the next best sample location\"\"\"\n\n # Compute mu and sigma in a call to predict() on gp\n mu, sigma = self.gp.predict(self.X_s)\n # print(\"mu:\", mu, mu.shape)\n # print(\"sigma:\", sigma, sigma.shape)\n\n # Note: sigma of shape (s,)\n Z = np.zeros(sigma.shape)\n if self.minimize is True:\n f_plus = np.min(self.gp.Y)\n Z_NUM = f_plus - mu - self.xsi\n else:\n f_plus = np.max(self.gp.Y)\n Z_NUM = mu - f_plus - self.xsi\n\n for i in range(sigma.shape[0]):\n if sigma[i] > 0:\n Z[i] = Z_NUM[i] / sigma[i]\n else:\n Z[i] = 0\n\n # Compute the Expected Improvement (EI)\n EI = np.zeros(sigma.shape)\n for i in range(sigma.shape[0]):\n if sigma[i] > 0:\n EI[i] = Z_NUM[i] * norm.cdf(Z[i]) + sigma[i] * norm.pdf(Z[i])\n else:\n EI[i] = 0\n X_next = self.X_s[np.argmax(EI)]\n\n # print(\"EI:\", EI)\n # print(\"self.X_s:\", self.X_s)\n return X_next, EI\n", "#!/usr/bin/env python3\n\"\"\"Classification\"\"\"\nimport numpy as np\n\n\nclass Neuron():\n \"\"\"Single neuron performing binary classification\"\"\"\n\n def __init__(self, nx):\n \"\"\"Constructor\"\"\"\n if not isinstance(nx, int):\n raise TypeError(\"nx must be an integer\")\n if nx < 1:\n raise ValueError(\"nx must be a positive integer\")\n\n self.__W = np.random.normal(0, 1, (1, nx))\n self.__b = 0\n self.__A = 0\n\n @property\n def W(self):\n \"\"\"W: The weights vector for the neuron.\n\n Returns:\n W: int\n \"\"\"\n return self.__W\n\n @property\n def b(self):\n \"\"\"b: The bias for the neuron. Upon instantiation\n\n Returns:\n b: int\n \"\"\"\n return self.__b\n\n @property\n def A(self):\n \"\"\"A: The activated output of the neuron (prediction).\n\n Returns:\n A: int\n \"\"\"\n return self.__A\n", "#!/usr/bin/env python3\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nupdate_variables_Adam = __import__('9-Adam').update_variables_Adam\n\ndef forward_prop(X, W, b):\n Z = np.matmul(X, W) + b\n A = 1 / (1 + np.exp(-Z))\n return A\n\ndef calculate_grads(Y, A, W, b):\n m = Y.shape[0]\n dZ = A - Y\n dW = np.matmul(X.T, dZ) / m\n db = np.sum(dZ, axis=1, keepdims=True) / m\n return dW, db\n\ndef calculate_cost(Y, A):\n m = Y.shape[0]\n loss = - (Y * np.log(A) + (1 - Y) * np.log(1 - A))\n cost = np.sum(loss) / m\n\n return cost\n\nif __name__ == '__main__':\n lib_train = np.load('../data/Binary_Train.npz')\n X_3D, Y = lib_train['X'], lib_train['Y'].T\n X = X_3D.reshape((X_3D.shape[0], -1))\n\n nx = X.shape[1]\n np.random.seed(0)\n W = np.random.randn(nx, 1)\n b = 0\n dW_prev1 = np.zeros((nx, 1))\n db_prev1 = 0\n dW_prev2 = np.zeros((nx, 1))\n db_prev2 = 0\n for i in range(1000):\n A = forward_prop(X, W, b)\n if not (i % 100):\n cost = calculate_cost(Y, A)\n print('Cost after {} iterations: {}'.format(i, cost))\n dW, db = calculate_grads(Y, A, W, b)\n W, dW_prev1, dW_prev2 = update_variables_Adam(0.001, 0.9, 0.99, 1e-8, W, dW, dW_prev1, dW_prev2, i + 1)\n b, db_prev1, db_prev2 = update_variables_Adam(0.001, 0.9, 0.99, 1e-8, b, db, db_prev1, db_prev2, i + 1)\n A = forward_prop(X, W, b)\n cost = calculate_cost(Y, A)\n print('Cost after {} iterations: {}'.format(1000, cost))\n\n Y_pred = np.where(A >= 0.5, 1, 0)\n fig = plt.figure(figsize=(10, 10))\n for i in range(100):\n fig.add_subplot(10, 10, i + 1)\n plt.imshow(X_3D[i])\n plt.title(str(Y_pred[i, 0]))\n plt.axis('off')\n plt.tight_layout()\n plt.show()" ]
[ [ "tensorflow.train.inverse_time_decay" ], [ "scipy.stats.norm.cdf", "numpy.linspace", "numpy.min", "scipy.stats.norm.pdf", "numpy.max", "numpy.argmax", "numpy.zeros" ], [ "numpy.random.normal" ], [ "matplotlib.pyplot.imshow", "matplotlib.pyplot.tight_layout", "numpy.log", "numpy.random.seed", "numpy.matmul", "numpy.random.randn", "matplotlib.pyplot.axis", "numpy.exp", "numpy.load", "matplotlib.pyplot.show", "numpy.where", "numpy.sum", "numpy.zeros", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
raphaottoni/youtube-hatespeech
[ "4467d065c2bddd86feec673ad74670c4c975f017" ]
[ "analyses/weat.py" ]
[ "from gensim import corpora, models, similarities\nimport json\nimport numpy\nimport random\nimport csv\nimport itertools\nimport gensim, copy\nfrom collections import defaultdict\nimport glob, os\n\ntarget_words = {}\nattribute_words= {}\nweats_name = []\n\n# 1 WEAT Immigrants\ntarget_words[\"1_a\"] = [\"immigrant\", \"migrant\"]\ntarget_words[\"1_b\"] = [\"citizen\", \"native\"]\nattribute_words[\"1_a\"] = [\"bad\", \"burden\", \"pirate\", \"plague\", \"taker\", \"thief\"]\nattribute_words[\"1_b\"] = [\"good\", \"honest\", \"maker\", \"rightful\"]\nweats_name.append(\"Immigrants\")\n\n# 2 WEAT Muslims\ntarget_words[\"2_a\"] = [\"islamism\", \"muhammed\", \"muslim\", \"quran\"]\ntarget_words[\"2_b\"] = [\"bible\", \"christian\", \"christianity\", \"jesus\"]\nattribute_words[\"2_a\"] = [\"assassin\", \"attack\", \"bomb\", \"death\", \"murder\", \"radical\", \"terrorist\"]\nattribute_words[\"2_b\"] = [\"compassionate\", \"gentle\", \"humane\", \"kind\", \"tolerant\"]\nweats_name.append(\"Muslims\")\n\n# 3 WEAT LGBT people\ntarget_words[\"3_a\"] = [\"bisexual\", \"gay\", \"homosexual\", \"lesbian\"]\ntarget_words[\"3_b\"] = [\"het\", \"hetero\", \"heterosexual\", \"straight\"]\nattribute_words[\"3_a\"] = [\"immoral\", \"outrageous\", \"promiscuous\", \"revolting\", \"sinner\"]\nattribute_words[\"3_b\"] = [\"moral\", \"natural\", \"normal\"]\nweats_name.append(\"LGBT People\")\n\n# 4 WEAT math arts male_female\ntarget_words[\"4_a\"] = [\"math\",\"algebra\",\"geometry\",\"calculus\",\"equations\",\"computation\",\"numbers\" ]\ntarget_words[\"4_b\"] = [\"poetry\",\"art\",\"dance\",\"literature\",\"novel\",\"symphony\",\"drama\",\"sculpture\" ]\nattribute_words[\"4_a\"] = [\"male\",\"man\",\"boy\",\"brother\",\"he\",\"him\",\"his\", \"son\"]\nattribute_words[\"4_b\"] = [\"female\",\"woman\",\"girl\",\"sister\",\"she\",\"her\",\"hers\", \"daughter\"]\nweats_name.append(\"Math Arts\")\n\n# 5 WEAT Judaism and Christianity\n# Religious Judaism Christianity\ntarget_words[\"5_a\"] = [\"church\",\"bible\",\"christian\",\"christianity\"]\ntarget_words[\"5_b\"] = [\"synagogue\",\"torah\",\"jew\",\"judaism\"]\nattribute_words[\"5_a\"] = [\"terrific\",\"delight\",\"celebrate\",\"glad\",\"beautiful\",\"appealing\", \"pleasure\", \"enjoy\" ]\nattribute_words[\"5_b\"] = [\"hate\",\"angry\",\"detest\",\"despise\",\"dirty\",\"humiliate\",\"pain\", \"horrible\"]\nweats_name.append(\"Jewish\")\n\n# 6 WEAT African American 1\ntarget_words[\"6_a\"] = [\"brad\", \"brendan\", \"geoffrey\", \"greg\", \"brett\", \"jay\",\n \"matthew\", \"neil\", \"todd\", \"allison\", \"anne\", \"carrie\",\n \"emily\", \"jill\", \"laurie\", \"kristen\", \"meredith\", \"sarah\"]\n\ntarget_words[\"6_b\"] = [\"darnell\", \"hakim\", \"jermaine\", \"kareem\", \"jamal\",\n \"leroy\", \"rasheed\", \"tremayne\", \"tyrone\", \"aisha\", \n \"ebony\", \"keisha\", \"kenya\", \"latonya\", \"lakisha\", \n \"latoya\", \"tamika\", \"tanisha\"]\nattribute_words[\"6_a\"] = [ \"joy\", \"love\", \"peace\", \"wonderful\", \"pleasure\", \"friend\", \"laughter\", \"happy\"]\nattribute_words[\"6_b\"] = [\"agony\", \"terrible\", \"horrible\", \"nasty\", \"evil\", \"war\", \"awful\",\"failure\"]\nweats_name.append(\"African - 1\")\n\n# 7 WEAT African American 2\ntarget_words[\"7_a\"] = [\"brad\", \"brendan\", \"geoffrey\", \"greg\", \"brett\", \"jay\",\n \"matthew\", \"neil\", \"todd\", \"allison\", \"anne\", \"carrie\",\n \"emily\", \"jill\", \"laurie\", \"kristen\", \"meredith\", \"sarah\"]\n\ntarget_words[\"7_b\"] = [\"darnell\", \"hakim\", \"jermaine\", \"kareem\", \"jamal\",\n \"leroy\", \"rasheed\", \"tremayne\", \"tyrone\", \"aisha\", \n \"ebony\", \"keisha\", \"kenya\", \"latonya\", \"lakisha\", \n \"latoya\", \"tamika\", \"tanisha\"]\nattribute_words[\"7_a\"] = [\"caress\", \"freedom\", \"health\", \"love\", \"peace\",\n \"cheer\", \"friend\", \"heaven\", \"loyal\", \"pleasure\", \n \"diamond\", \"gentle\", \"honest\", \"lucky\", \"rainbow\",\n \"diploma\", \"gift\", \"honor\", \"miracle\", \"sunrise\",\n \"family\", \"happy\",\"laughter\",\"paradise\", \"vacation\"] \n\nattribute_words[\"7_b\"] = [\"abuse\", \"crash\", \"filth\", \"murder\", \"sickness\",\n \"accident\", \"death\", \"grief\", \"poison\", \"stink\", \n \"assault\", \"disaster\", \"hatred\",\"pollute\", \"tragedy\", \n \"bomb\", \"divorce\", \"jail\", \"poverty\", \"ugly\", \"cancer\",\n \"evil\", \"kill\", \"rotten\",\"vomit\"]\nweats_name.append(\"African - 2\")\n\n\n\n\n\n\ndef statistic_test(X,Y,A,B,M):\n result = 0.0\n sum_X = 0.0\n sum_Y = 0.0\n\n for word_X in X:\n sum_X += sub_statistic_test(word_X, A,B,M)\n for word_Y in Y:\n sum_Y += sub_statistic_test(word_Y, A,B,M)\n\n return (sum_X - sum_Y)\n\ndef sub_statistic_test(w,A,B,M):\n result = 0.0\n sum_cos_A = 0.0\n sum_cos_B = 0.0\n\n for word_A in A:\n sum_cos_A += numpy.dot(M[w],M[word_A])/(numpy.linalg.norm(M[w])*numpy.linalg.norm(M[word_A]))\n for word_B in B:\n sum_cos_B += numpy.dot(M[w],M[word_B])/(numpy.linalg.norm(M[w])*numpy.linalg.norm(M[word_B]))\n\n return (sum_cos_A/len(A) - sum_cos_B/len(B))\n\ndef effect_size(x_words,y_words,a_attributes,b_attributes,M):\n # Effect size\n test_x = 0.0\n test_y = 0.0\n samples = []\n\n for word_x in target_words[x_words]:\n test_x += sub_statistic_test(word_x,attribute_words[a_attributes],attribute_words[b_attributes],M)\n samples.append(sub_statistic_test(word_x,attribute_words[a_attributes],attribute_words[b_attributes],M))\n\n for word_y in target_words[y_words]:\n test_y += sub_statistic_test(word_y,attribute_words[a_attributes],attribute_words[b_attributes],M)\n samples.append(sub_statistic_test(word_y,attribute_words[a_attributes],attribute_words[b_attributes],M))\n\n mean_x = test_x/len(target_words[x_words])\n mean_y = test_y/len(target_words[y_words])\n\n std_dev = numpy.std(samples)\n effect_size = (mean_x - mean_y)/std_dev\n return effect_size\n\n\n# P-Value\ndef p_value(X,Y,A,B,model):\n null_hipotese_evidance = 0.0\n number_permitations = 0.0\n\n # Finds the biggest possible set of the same size for the two classes\n X_size = len(target_words[X])\n Y_size = len(target_words[Y])\n size = max(X_size, Y_size)\n union = set(target_words[X] + target_words[Y])\n random_test_statistic_values = []\n test_statistic_value = statistic_test(target_words[X],target_words[Y],attribute_words[A],attribute_words[B],model)\n\n if (Y_size + X_size) < 14:\n # there will be less than 5000 combinations\n permutations = itertools.combinations(union,size)\n\n for i,permutation in enumerate(permutations):\n x_i = permutation\n y_i = union - set(permutation)\n test_value = statistic_test(x_i,y_i,attribute_words[A],attribute_words[B],model)\n\n random_test_statistic_values.append(test_value)\n if( test_value > test_statistic_value):\n null_hipotese_evidance += 1\n number_permitations += 1\n\n #print(\"null hipotese_evidance: \" + str(null_hipotese_evidance))\n #print(\"num_permutations: \" + str(number_permitations))\n #print(\"P-Value():\")\n #print(null_hipotese_evidance/number_permitations)\n p_value_result = null_hipotese_evidance/number_permitations\n #print(\"enviando \" + str(p_value_result))\n return(p_value_result)\n\n else:\n # There will be more than 5000, thus we should randomize\n print(\"Generating 5k random\")\n classes = target_words[X] + target_words[Y]\n\n for i in range(5000):\n random.shuffle(classes)\n x_i = classes[:size]\n y_i = classes[size+1:]\n test_value = statistic_test(x_i,y_i,attribute_words[A],attribute_words[B],model)\n # save the valus to be used for each channel\n random_test_statistic_values.append(test_value)\n if( test_value > test_statistic_value):\n null_hipotese_evidance += 1\n number_permitations += 1\n #if number_permitations % 100 == 0:\n # print(number_permitations)\n\n #print(\"null hipotese_evidance: \" + str(null_hipotese_evidance))\n #print(\"num_permutations: \" + str(number_permitations))\n #print(\"P-Value(english):\")\n #print(null_hipotese_evidance/number_permitations)\n p_value_result = null_hipotese_evidance/number_permitations\n return(p_value_result)\n\n\n\ndef main():\n\n # Which models to load\n political_biases_model = [\"left\", \"leftcenter\", \"center\", \"right-center\", \"right\"]\n model_types = [ \"captions\", \"comments\"]\n\n \n # list of WEATs to execute\n weats = [1,2,3]\n \n with open(\"../data/weat/weat_results.csv\", \"w\") as csvfile:\n writer = csv.writer(csvfile, delimiter=',')\n writer.writerow([\"channel\",\"WEAT\",\"political_bias\", \"source\", \"effect_size\", \"p_value\"])\n \n #for political_bias in political_biases_model:\n # for model_type in model_types: \n\n # for file in os.listdir(\"../models/biases/\" + model_type + \"/\" + political_bias):\n # if file.endswith(\".model\"):\n # print(\"Loading \" + political_bias + \" word2vec \" + model_type + \" model \" + \"(\" + file + \")\") \n # model = gensim.models.Word2Vec.load(\"../models/biases/\" + model_type + \"/\" + political_bias+ \"/\" + file)\n # #model = gensim.models.Word2Vec.load(\"../models/wiki-word2vec/wiki-en.word2vec.model\")\n # print(\"Executing WEATs on current model\" )\n # for weat_number in weats:\n # X = str(weat_number) + \"_a\"\n # Y = str(weat_number) + \"_b\"\n # A = str(weat_number) + \"_a\"\n # B = str(weat_number) + \"_b\"\n # ## Effect size of the base model\n # effect_size_result = effect_size(X,Y,A,B,model)\n # print(\"Effect-Size(\"+str(weat_number)+ \"):\" + str(effect_size_result))\n # p_value_result = p_value(X,Y,A,B,model)\n # print(\"P-value(\"+str(weat_number)+ \"):\" + str(p_value_result))\n # writer.writerow([file[:-6],weats_name[weat_number -1],political_bias , model_type, effect_size_result, p_value_result])\n\n # Add the baseline weat results the wikipedia model\n print(\"Loading the wiki base model\")\n model = gensim.models.Word2Vec.load(\"../models/wiki-word2vec/wiki-en.word2vec.model\")\n print(\"Executing WEATs on current model\" )\n for weat_number in weats:\n X = str(weat_number) + \"_a\"\n Y = str(weat_number) + \"_b\"\n A = str(weat_number) + \"_a\"\n B = str(weat_number) + \"_b\"\n ## Effect size of the base model\n effect_size_result = effect_size(X,Y,A,B,model)\n print(\"Effect-Size(\"+str(weat_number)+ \"):\" + str(effect_size_result))\n p_value_result = p_value(X,Y,A,B,model)\n print(\"P-value(\"+str(weat_number)+ \"):\" + str(p_value_result))\n writer.writerow([\"wikipedia\",weats_name[weat_number -1], \"wiki\", \"wiki\", effect_size_result, p_value_result])\n\n \n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.dot", "numpy.std", "numpy.linalg.norm" ] ]
[ { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
imisi-akande/disaster-response-pipeline
[ "d691e643c57e45b226ca3cb2c0b4a708c7edfe8b" ]
[ "app/run.py" ]
[ "import json\nimport plotly\nimport pandas as pd\nimport nltk\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.tokenize import word_tokenize, sent_tokenize\nfrom nltk import pos_tag, word_tokenize\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.tokenize import word_tokenize\n\nfrom flask import Flask\nfrom flask import render_template, request, jsonify\nfrom plotly.graph_objs import Bar\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\nimport joblib\nfrom sqlalchemy import create_engine\n\n\napp = Flask(__name__)\n\nclass StartingVerbExtractor(BaseEstimator, TransformerMixin):\n \n def starting_verb(self, text):\n sentence_list = nltk.sent_tokenize(text)\n for sentence in sentence_list:\n pos_tags = nltk.pos_tag(tokenize(sentence))\n first_word, first_tag = pos_tags[0]\n if first_tag in ['VB', 'VBP'] or first_word == 'RT':\n return True\n return False\n\n def fit(self, X, y=None):\n return self\n\n def transform(self, X):\n X_tagged = pd.Series(X).apply(self.starting_verb)\n return pd.DataFrame(X_tagged)\n\n\ndef tokenize(text):\n tokens = word_tokenize(text)\n lemmatizer = WordNetLemmatizer()\n\n clean_tokens = []\n for tok in tokens:\n clean_tok = lemmatizer.lemmatize(tok).lower().strip()\n clean_tokens.append(clean_tok)\n\n return clean_tokens\n\n# load data\nengine = create_engine('sqlite:///../data/disaster_response.db')\ndf = pd.read_sql_table('disaster_response_table', engine)\n\n# load model\nmodel = joblib.load(\"../models/classifier.pkl\")\n\n\n# index webpage displays cool visuals and receives user input text for model\[email protected]('/')\[email protected]('/index')\ndef index():\n # extract data needed for visuals\n # TODO: Below is an example - modify to extract data for your own visuals\n genre_counts = df.groupby('genre').count()['message']\n genre_percent = round(100*genre_counts/genre_counts.sum(), 2)\n genre_names = list(genre_counts.index)\n\n category_names = df.iloc[:,4:].columns\n category_boolean = (df.iloc[:,4:] != 0).sum().values\n\n # create visuals\n # TODO: Below is an example - modify to create your own visuals\n graphs = [\n # GRAPH 1 - genre graph\n {\n \"data\": [\n {\n \"type\": \"pie\",\n \"uid\": \"f4de1f\",\n \"hole\": 0.4,\n \"name\": \"Genre\",\n \"pull\": 0,\n \"domain\": {\n \"x\": genre_percent,\n \"y\": genre_names\n },\n \"marker\": {\n \"colors\": [\n \"#7fc97f\",\n \"#bc5090\",\n \"#ffa600\"\n ]\n },\n \"textinfo\": \"label+value\",\n \"hoverinfo\": \"all\",\n \"labels\": genre_names,\n \"values\": genre_counts\n }\n ],\n \"layout\": {\n \"title\": \"Count and Percentage of Messages by Genre\"\n }\n },\n # GRAPH 2 - category graph\n {\n 'data': [\n Bar(\n x=category_names,\n y=category_boolean\n )\n ],\n\n 'layout': {\n 'title': 'Distribution of Message Categories',\n 'yaxis': {\n 'title': \"Count\"\n },\n 'xaxis': {\n 'title': \"Category\",\n 'tickangle': 35\n }\n }\n }\n ]\n\n # encode plotly graphs in JSON\n ids = [\"graph-{}\".format(i) for i, _ in enumerate(graphs)]\n graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)\n\n # render web page with plotly graphs\n return render_template('master.html', ids=ids, graphJSON=graphJSON)\n\n# web page that handles user query and displays model results\[email protected]('/go')\ndef go():\n # save user input in query\n query = request.args.get('query', '')\n\n # use model to predict classification for query\n classification_labels = model.predict([query])[0]\n classification_results = dict(zip(df.columns[4:], classification_labels))\n\n # This will render the go.html Please see that file. \n return render_template(\n 'go.html',\n query=query,\n classification_result=classification_results\n )\n\n\ndef main():\n app.run(host='0.0.0.0', port=5000, debug=True)\n\n\nif __name__ == '__main__':\n main()" ]
[ [ "pandas.read_sql_table", "pandas.Series", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
ess-dmsc/JustBinIt
[ "dc8242ed44f03e92f60618c96596025ec8cbc40e" ]
[ "tests/test_histogram2d.py" ]
[ "import numpy as np\nimport pytest\n\nfrom just_bin_it.histograms.histogram2d import Histogram2d\n\nIRRELEVANT_TOPIC = \"some-topic\"\n\n\nclass TestHistogram2dFunctionality:\n @pytest.fixture(autouse=True)\n def prepare(self):\n self.pulse_time = 1234\n self.num_bins = (5, 10)\n self.tof_range = (0, 10)\n self.det_range = (0, 5)\n self.data = np.array([x for x in range(self.num_bins[0])])\n self.hist = Histogram2d(\"topic\", self.num_bins, self.tof_range, self.det_range)\n\n def test_if_single_value_for_num_bins_then_value_used_for_both_x_and_y(self):\n num_bins = 5\n hist = Histogram2d(\"topic\", num_bins, self.tof_range, self.det_range)\n assert len(hist.x_edges) == num_bins + 1\n assert len(hist.y_edges) == num_bins + 1\n assert hist.shape == (num_bins, num_bins)\n\n def test_on_construction_histogram_is_uninitialised(self):\n assert self.hist.x_edges is not None\n assert self.hist.y_edges is not None\n assert self.hist.shape == self.num_bins\n assert len(self.hist.x_edges) == self.num_bins[0] + 1\n assert len(self.hist.y_edges) == self.num_bins[1] + 1\n assert self.hist.x_edges[0] == self.data[0]\n assert self.hist.x_edges[-1] == 10\n assert self.hist.y_edges[0] == self.data[0]\n assert self.hist.y_edges[-1] == 5\n assert self.hist.data.sum() == 0\n\n def test_adding_data_to_initialised_histogram_new_data_is_added(self):\n self.hist.add_data(self.pulse_time, self.data, self.data)\n first_sum = self.hist.data.sum()\n\n # Add the data again\n self.hist.add_data(self.pulse_time, self.data, self.data)\n\n # Sum should be double\n assert self.hist.data.sum() == first_sum * 2\n\n def test_adding_data_outside_initial_bins_is_ignored(self):\n self.hist.add_data(self.pulse_time, self.data, self.data)\n first_sum = self.hist.data.sum()\n x_edges = self.hist.x_edges[:]\n y_edges = self.hist.y_edges[:]\n\n # Add data that is outside the edges\n new_data = np.array([x + self.num_bins[0] + 1 for x in range(self.num_bins[0])])\n self.hist.add_data(self.pulse_time, new_data, new_data)\n\n # Sum should not change\n assert self.hist.data.sum() == first_sum\n # Edges should not change\n assert np.array_equal(self.hist.x_edges, x_edges)\n assert np.array_equal(self.hist.y_edges, y_edges)\n\n def test_if_no_id_supplied_then_defaults_to_empty_string(self):\n assert self.hist.identifier == \"\"\n\n def test_id_supplied_then_is_set(self):\n example_id = \"abcdef\"\n hist = Histogram2d(\n \"topic1\",\n self.num_bins,\n self.tof_range,\n self.det_range,\n identifier=example_id,\n )\n assert hist.identifier == example_id\n\n def test_only_data_with_correct_source_is_added(self):\n hist = Histogram2d(\n \"topic\", self.num_bins, self.tof_range, self.det_range, source=\"source1\"\n )\n\n hist.add_data(self.pulse_time, self.data, self.data, source=\"source1\")\n hist.add_data(self.pulse_time, self.data, self.data, source=\"source1\")\n hist.add_data(self.pulse_time, self.data, self.data, source=\"OTHER\")\n\n assert hist.data.sum() == 10\n\n def test_clearing_histogram_data_clears_histogram(self):\n self.hist.add_data(self.pulse_time, self.data, self.data)\n\n self.hist.clear_data()\n\n assert self.hist.data.sum() == 0\n\n def test_after_clearing_histogram_can_add_data(self):\n self.hist.add_data(self.pulse_time, self.data, self.data)\n self.hist.clear_data()\n\n self.hist.add_data(self.pulse_time, self.data, self.data)\n\n assert self.hist.shape == self.num_bins\n assert self.hist.data.sum() == 5\n\n def test_adding_empty_data_does_nothing(self):\n self.hist.add_data(self.pulse_time, [], [])\n\n assert self.hist.data.sum() == 0\n\n def test_histogram_keeps_track_of_last_pulse_time_processed(self):\n self.hist.add_data(1234, self.data, self.data)\n self.hist.add_data(1235, self.data, self.data)\n self.hist.add_data(1236, self.data, self.data)\n\n assert self.hist.last_pulse_time == 1236\n" ]
[ [ "numpy.array_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
MGH-LMIC/CXR-autolabeling
[ "74eac30bb6eaa6c1d5a8b343743024ef6bd9db7d" ]
[ "autolabeling.py" ]
[ "import re\nimport pickle\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as mpl_color_map\n\nfrom tqdm import tqdm\nfrom pathlib import Path\nfrom prettytable import PrettyTable\nfrom scipy.ndimage import gaussian_filter\nfrom sklearn.metrics import roc_curve, precision_recall_curve\n\nimport torch\nimport torchnet as tnt\nimport torch.nn.functional as F\n\nfrom utils import logger\nfrom environment import TestEnvironment, initialize, print_label_name\nfrom gradcam import GradCam, save_class_activation_images\nfrom data import CxrDataset, EXT_DATA_BASE\nfrom atlasmethod import EX_AI\n\nimport time\n\nATLAS_GEN = False\natlas_name = 'cardiomegaly'\n# 'cardiomegaly', 'atelectasis', 'pulmonary_edema', 'pneumonia', 'pleural_effusion'\n\nclass Tester:\n def __init__(self, env, pt_runtime=\"test\", fn_net=None, fl_gradcam=False, cls_gradcam=None, id_prob=None, fl_ensemble=False, fl_exai=False, f_name='sim', f_csv=None):\n self.env = env\n self.pt_runtime = pt_runtime\n self.fl_prob = False if id_prob == None else True\n self.id_prob = id_prob\n self.f_name = f_name\n self.fl_ensemble = fl_ensemble\n # for multiple class and binary label tasks\n self.pf_metric = {\n 'loss': [],\n 'accuracy': [],\n 'sensitivity': [],\n 'specificity': [],\n 'auc_score': [],\n 'ap_score': [],\n 'mse_score': []\n }\n self.fn_net = fn_net\n self.fl_gradcam = fl_gradcam\n self.cls_gradcam = cls_gradcam\n self.th_gradcam = 0.5\n self.fl_gradcam_save = True\n\n #explainable methods\n self.fl_exai = fl_exai\n if self.fl_exai:\n self.fl_gradcam = True\n self.cls_gradcam = [\n 'Hilar/mediastinum>Cardiomegaly>.',\n 'Lung density>Increased lung density>Atelectasis',\n 'Lung density>Increased lung density>Pulmonary edema',\n 'Lung density>Increased lung density>pneumonia',\n 'Pleura>Pleural effusion>.'\n ]\n self.th_gradcam = 0.5\n self.ex_method = EX_AI(env, pt_runtime=pt_runtime, thr=0.5, f_name=f_name, ext_data_csv=f_csv)\n\n def load(self):\n pt_file = self.pt_runtime.joinpath(f'train.pkl')\n with open(pt_file, 'rb') as f:\n self.pf_metric = pickle.load(f)\n\n def test_evaluation(self, epoch=1, fl_save=False):\n if self.fn_net == None:\n pt_model = self.pt_runtime.joinpath(f'model_epoch_{epoch:04d}.pth.tar')\n else:\n pt_model = self.pt_runtime.joinpath(str(self.fn_net))\n\n self.env.load_model(pt_model)\n\n try:\n self.load()\n except:\n logger.debug('there is no pkl to load.')\n\n _, _, _ = self.test(epoch, self.env.test_loader, fl_save=fl_save)\n\n if False:\n self.algorithm_attribution(self.env.gradcam_loader)\n\n if self.fl_gradcam:\n _, _, _ = self.gradcam_data(self.env.gradcam_loader)\n\n\n def test_ensemble_evaluation(self, epoch=1, fl_save=False, n_ens=1):\n\n predict = []\n target = []\n\n if self.fl_gradcam:\n cams = np.ones((len(self.env.gradcam_loader), len(self.cls_gradcam), 16, 16))\n\n if ATLAS_GEN:\n gradcam_df = pd.DataFrame(columns=[f'{x:03d}' for x in range(256)])\n\n for k in range(n_ens):\n pt_model = self.pt_runtime.joinpath(str(self.fn_net)+f'_{k:02d}.pth.tar')\n self.env.load_model(pt_model)\n\n #logger.info(f'network to test: {self.env.model}')\n try:\n self.load()\n except:\n logger.debug('there is no pkl to load.')\n\n _, pred, tar = self.test(epoch, self.env.test_loader, fl_save=False)\n\n predict.append(pred)\n target.append(tar)\n\n # evaluate ensemble's performance\n prob_ens = self.ensemble_performance(predict, target, n_ens, fl_save=fl_save)\n\n if self.fl_exai:\n prob_in = pd.DataFrame(prob_ens.cpu().numpy()[:,1:])\n prob_in['PATH'] = self.env.test_loader.dataset.entries['PATH']\n self.ex_method.input_preparation(prob_in)\n\n if self.fl_gradcam:\n cams = np.ones((len(self.env.gradcam_loader), len(self.cls_gradcam), 16, 16))\n for k in range(n_ens):\n pt_model = self.pt_runtime.joinpath(str(self.fn_net)+f'_{k:02d}.pth.tar')\n self.env.load_model(pt_model)\n\n start = time.time()\n _, _, cam = self.gradcam_data(self.env.gradcam_loader, prob_ens=prob_ens)\n #review_cam\n #cams *= cam\n cams += cam\n end = time.time()\n print(f'{k:02d} model gradcam time: {end-start} sec')\n\n _, _, cams = self.gradcam_data(self.env.gradcam_loader, ens_flg=True, cams_ens=cams, prob_ens=prob_ens)\n\n if self.fl_exai:\n start = time.time()\n self.ex_method.run(cams)\n end = time.time()\n print(f'self-annotation time: {end-start} sec')\n\n if ATLAS_GEN:\n for k in range(len(self.env.gradcam_loader)):\n gradcam_df.loc[k] = cams[k].flatten()\n print(f\"[{atlas_name}]Atlas generation: {k:5d}\")\n\n gradcam_df['PATH'] = self.env.gradcam_loader.dataset.entries['PATH']\n gradcam_df.to_csv(self.pt_runtime.joinpath(f'gradcam_atlas_{atlas_name}.csv'), index=False)\n\n\n def ensemble_performance(self, predict, target, n_ens, fl_save=False):\n\n pred_ens = torch.zeros(predict[0].shape).to(self.env.device)\n #pred_ens = np.zeros(predict[0].shape)\n for i in range(n_ens):\n pred_ens += torch.from_numpy(predict[i]).to(self.env.device)\n\n pred_ens /= n_ens\n targ_ens = torch.from_numpy(target[0]).to(self.env.device)\n\n aucs, aps = self.AUC_AP_metric(pred_ens, targ_ens)\n correct, total = self.ACC_metric(pred_ens, targ_ens)\n self.Per_print(correct=correct, total=total, aucs=aucs, aps=aps)\n\n if fl_save:\n test_set = self.env.test_loader.dataset\n labels = self.env.labels\n self.roc_evaluation(test_set, pred_ens, targ_ens, labels)\n\n return pred_ens\n\n\n def AUC_AP_metric(self, output, target):\n out_dim = output.shape[1]\n aucs = [tnt.meter.AUCMeter() for i in range(out_dim)]\n aps = [tnt.meter.APMeter() for i in range(out_dim)]\n\n for i in range(out_dim):\n mask_out, mask_tar = self.mask_pred(output[:, i], target[:, i])\n try:\n aucs[i].add(mask_out, mask_tar)\n aps[i].add(mask_out, mask_tar)\n except:\n continue\n\n return aucs, aps\n\n def MSE__metric(self, output, target):\n out_dim = 1\n mses = [tnt.meter.MSEMeter() for i in range(out_dim)]\n\n mses[0].add(output[:, -1], target[:, -1])\n\n return mses\n\n def ACC_metric(self, output, target):\n mask_out, mask_tar = self.mask_pred(output, target)\n\n ones = torch.ones(mask_out.shape).int().to(self.env.device)\n zeros = torch.zeros(mask_out.shape).int().to(self.env.device)\n\n pred = torch.where(mask_out > 0.5, ones, zeros)\n correct = pred.eq(mask_tar.int()).sum().item()\n total = len(mask_tar)\n\n return correct, total\n\n\n def Per_print(self, correct=None, total=None, aucs=None, aps=None, mses=None):\n labels = self.env.labels\n\n out_dim = len(aucs)\n\n percent = 100. * correct / total\n\n logger.info(f\"accuracy {correct}/{total} \"\n f\"({percent:.2f}%)\")\n\n p = PrettyTable()\n p.field_names = [\"findings\", \"auroc score\", \"ap score\"]\n auc_cnt = out_dim\n for i in range(out_dim):\n try:\n #p.add_row([labels[i], f\"{aucs[i].value()[0]:.4f}\", f\"{aps[i].value()[0]:.4f}\"])\n p.add_row([f'E-{labels[i]}', f\"{aucs[i].value()[0]:.4f}\", f\"{aps[i].value()[0]:.4f}\"])\n except:\n p.add_row([labels[i], \"-\", \"-\"])\n\n try:\n list_aucs=[]\n for k in aucs:\n if type(k.value()) == tuple:\n if np.isnan(k.value()[0]) == False:\n list_aucs.append(k.value()[0])\n\n list_aps=[]\n for k in aps:\n if type(k.value()) == torch.Tensor:\n if np.isnan(k.value()[0]) == False:\n list_aps.append(k.value()[0])\n\n ave_auc = np.mean(list_aucs)\n ave_ap = np.mean(list_aps)\n tbl_str = p.get_string(title=f\"Ensemble-performance (avg auc {ave_auc:.4f}, mean ap {ave_ap:.4f})\")\n logger.info(f\"\\n{tbl_str}\")\n except:\n print(\"We cannot calcuate average acu scores\")\n ave_auc = 0\n ave_ap = 0\n\n\n def test(self, epoch, test_loader, fl_save=False):\n test_set = test_loader.dataset\n out_dim = self.env.out_dim\n labels = self.env.labels\n\n aucs = [tnt.meter.AUCMeter() for i in range(out_dim)]\n aps = [tnt.meter.APMeter() for i in range(out_dim)]\n\n CxrDataset.eval()\n self.env.model.eval()\n\n with torch.no_grad():\n correct = 0\n total = 0\n\n predict_seq = torch.FloatTensor().to(self.env.device)\n target_seq = torch.FloatTensor().to(self.env.device)\n\n tqdm_desc = f'testing '\n t = tqdm(enumerate(test_loader), total=len(test_loader), desc=tqdm_desc,\n dynamic_ncols=True)\n\n for bt_idx, tp_data in t:\n output, target = self.test_batch(tp_data)\n\n # Network outputs\n predict_seq = torch.cat((predict_seq, F.sigmoid(output)), dim=0)\n target_seq = torch.cat((target_seq, target), dim=0)\n\n for i in range(out_dim):\n mask_out, mask_tar = self.mask_pred(output[:, i], target[:, i])\n try:\n aucs[i].add(mask_out, mask_tar)\n aps[i].add(mask_out, mask_tar)\n except:\n continue\n\n mask_out, mask_tar = self.mask_pred(output, target)\n\n ones = torch.ones(mask_out.shape).int().to(self.env.device)\n zeros = torch.zeros(mask_out.shape).int().to(self.env.device)\n\n pred = torch.where(mask_out > 0., ones, zeros)\n correct += pred.eq(mask_tar.int()).sum().item()\n total += len(mask_tar)\n #pred = torch.where(output > 0., ones, zeros)\n #correct += pred.eq(target.int()).sum().item()\n\n #total = len(test_loader.sampler) * out_dim\n percent = 100. * correct / total\n\n logger.info(f\"val epoch {epoch:03d}: \"\n f\"accuracy {correct}/{total} \"\n f\"({percent:.2f}%)\")\n\n p = PrettyTable()\n p.field_names = [\"findings\", \"auroc score\", \"ap score\"]\n auc_cnt = out_dim\n for i in range(out_dim):\n try:\n p.add_row([labels[i], f\"{aucs[i].value()[0]:.4f}\", f\"{aps[i].value()[0]:.4f}\"])\n except:\n p.add_row([labels[i], \"-\", \"-\"])\n\n if fl_save:\n self.roc_evaluation(test_set, predict_seq, target_seq, labels)\n\n if self.fl_prob:\n self.df_prob = pd.DataFrame()\n self.df_prob['PATH_CHECK'] = test_set.entries['PATH']\n self.df_prob['PROB'] = predict_seq.cpu().numpy()[:, self.id_prob]\n\n try:\n list_aucs=[]\n for k in aucs:\n if type(k.value()) == tuple:\n if np.isnan(k.value()[0]) == False:\n list_aucs.append(k.value()[0])\n\n list_aps=[]\n for k in aps:\n if type(k.value()) == torch.Tensor:\n if np.isnan(k.value()[0]) == False:\n list_aps.append(k.value()[0])\n \n ave_auc = np.mean(list_aucs)\n ave_ap = np.mean(list_aps)\n\n tbl_str = p.get_string(title=f\"performance (avg auc {ave_auc:.4f}, mean ap {ave_ap:.4f})\")\n logger.info(f\"\\n{tbl_str}\")\n except:\n print(\"We cannot calcuate average auc scores\")\n ave_auc = 0\n ave_ap = 0\n\n self.pf_metric[f'accuracy'].append((epoch, correct / total))\n self.pf_metric[f'auc_score'].append((epoch, ave_auc))\n self.pf_metric[f'ap_score'].append((epoch, ave_ap))\n\n return ave_auc, predict_seq.cpu().numpy(), target_seq.cpu().numpy()\n\n def mask_pred(self, output, target):\n mask_one = torch.ones(output.shape, dtype=torch.uint8, device=self.env.device)\n mask_zero = torch.zeros(output.shape, dtype=torch.uint8, device=self.env.device)\n\n #mask = torch.where(target == -1, mask_zero, mask_one)\n mask = torch.where(target == -1, mask_zero, mask_one).bool()\n mask_output = output.masked_select(mask.to(self.env.device))\n mask_target = target.masked_select(mask.to(self.env.device))\n\n return mask_output, mask_target\n\n def test_batch(self, tp_data, fl_input=False):\n # to support different types of models.\n if self.env.type == 0:\n data = tp_data[0]\n target = tp_data[1]\n info = tp_data[2]\n data, target, info = data.to(self.env.device), target.to(self.env.device), info.to(self.env.device)\n #data, target = data.to(self.env.device), target.to(self.env.device)\n #network output\n output = self.env.model(data)\n elif self.env.type == 1:\n data1 = tp_data[0]\n data2 = tp_data[1]\n target = tp_data[2]\n data1, data2, target = data1.to(self.env.device), data2.to(self.env.device), target.to(self.env.device)\n #network output\n output = self.env.model(data1, data2)\n elif self.env.type == 3:\n data = tp_data[0]\n target = tp_data[1]\n info = tp_data[2]\n data, target, info = data.to(self.env.device), target.to(self.env.device), info.to(self.env.device)\n #network output\n output = self.env.model(data, info)\n\n if fl_input == False:\n return output, target\n else:\n return data, info, output\n\n\n def gradcam_data(self, test_loader, hmp_dims=(512,512), ens_flg=False, cams_ens=None, prob_ens=None):\n # threshold to draw a heatmap\n out_dim = self.env.out_dim\n\n CxrDataset.eval()\n self.env.model.eval()\n #with torch.no_grad():\n gradcam_res_list = []\n gradcam_path_list = []\n\n cams = np.zeros((len(test_loader), len(self.cls_gradcam), 16, 16))\n\n grad_cam = GradCam(self.env.model, self.env.type)\n for batch_idx, (data, target, info) in enumerate(test_loader):\n #data, target = data.to(self.env.device), target.to(self.env.device)\n data, target, info = data.to(self.env.device), target.to(self.env.device), info.to(self.env.device)\n # Grad CAM\n #grad_cam = GradCam(self.env.model, self.env.type)\n if self.cls_gradcam == None:\n gradcam_res, gradcam_path = self.gradcam_save_maxcls(grad_cam, data, test_loader, batch_idx, hmp_dims, info)\n else:\n if self.fl_ensemble:\n cam = self.gradcam_save_argcls_ens(grad_cam, data, test_loader, batch_idx, hmp_dims, info, ens_flg=ens_flg, cams_ens=cams_ens, prob_ens=prob_ens)\n else:\n gradcam_res, gradcam_path = self.gradcam_save_argcls(grad_cam, data, test_loader, batch_idx, hmp_dims, info)\n\n try:\n if self.fl_ensemble:\n cams[batch_idx, :, :, :] = cam\n else:\n gradcam_res_list.append(gradcam_res.tolist())\n gradcam_path_list.append(gradcam_path)\n\n except AttributeError as e:\n print(\"No GradCam result?\")\n\n if False:\n self.gradcam_thumbnail()\n\n\n return gradcam_res_list, gradcam_path_list, cams\n\n def gradcam_save_maxcls(self, grad_cam, data, test_loader, batch_idx, hmp_dims, info):\n if self.env.type == 3:\n cam, prob, tcls = grad_cam.generate_cam(data, info)\n else:\n cam, prob, tcls = grad_cam.generate_cam(data)\n\n noPlotflg = np.array([-1])\n # when we draw gradcam, we have to batch size as 1.\n file_name = test_loader.dataset.entries['PATH'][batch_idx]\n path_name = file_name.split(\".\")[0]\n\n if prob >= self.th_gradcam:\n target_class = self.env.labels[tcls]\n label_list = re.split(' \\- |\\/| ', target_class)\n label_name = \"_\".join(label_list)\n path_name = \"_\".join([path_name, label_name])\n\n cam_rs = save_class_activation_images(data, cam, self.pt_runtime.joinpath(f\"gradcam_image\"), path_name, hmp_dims)\n return cam_rs, path_name\n else:\n cam_rs = save_class_activation_images(data, noPlotflg, self.pt_runtime.joinpath(\"gradcam_image\"), path_name, hmp_dims)\n return None, None\n\n def gradcam_save_argcls(self, grad_cam, data, test_loader, batch_idx, hmp_dims, info):\n\n if self.cls_gradcam[0] == 'all':\n self.cls_gradcam = self.env.labels\n\n for i, nm_tcls in enumerate(self.cls_gradcam):\n ## need to implement to find index among self.env.labels from string of target class\n ## code start here!!!!\n id_tcls = self.env.labels.index(nm_tcls)\n if self.env.type == 3:\n cam, prob, tcls = grad_cam.generate_cam(data, info, target_class=id_tcls)\n else:\n cam_w = self.env.model.module.main.classifier.weight[id_tcls].cpu().detach().numpy()\n cam, prob, tcls, _ = grad_cam.generate_cam(data, target_class=id_tcls, cam_w=cam_w)\n noPlotflg = np.array([-1])\n # when we draw gradcam, we have to batch size as 1.\n file_name = test_loader.dataset.entries['PATH'][batch_idx]\n path_name = file_name.split(\".\")[0]\n\n target_class = self.env.labels[tcls]\n label_list = re.split(' \\- |\\/| ', target_class)\n label_name = \"_\".join(label_list)\n label_name = label_name.strip('>.').split('>')[-1]\n #path_name = \"_\".join([f'{int(prob*1000):04d}', path_name, label_name])\n\n if prob >= self.th_gradcam:\n cam_rs = save_class_activation_images(data, cam, self.pt_runtime.joinpath(f\"gradcam_image_{label_name}\"), path_name, hmp_dims)\n\n cam_list=[]\n path_list=[]\n\n path_list.append(path_name)\n return cam_list, path_list\n\n def gradcam_save_argcls_ens(self, grad_cam, data, test_loader, batch_idx, hmp_dims, info, ens_flg=False, cams_ens=None, prob_ens=None):\n\n if self.cls_gradcam[0] == 'all':\n self.cls_gradcam = self.env.labels\n\n cams = np.zeros((len(self.cls_gradcam), 16, 16))\n for i, nm_tcls in enumerate(self.cls_gradcam):\n ## need to implement to find index among self.env.labels from string of target class\n ## code start here!!!!\n id_tcls = self.env.labels.index(nm_tcls)\n cam_w = self.env.model.module.main.classifier.weight[id_tcls].cpu().detach().numpy()\n if prob_ens[batch_idx, id_tcls].item() >= self.th_gradcam:\n if ens_flg == True:\n cam, prob, tcls, cam_low = grad_cam.generate_cam(data, target_class=id_tcls, cam_w=cam_w, ens_flg=True, ens_cam=cams_ens[batch_idx, i, :, :])\n cams[i, :, :] = cam_low\n\n noPlotflg = np.array([-1])\n # when we draw gradcam, we have to batch size as 1.\n file_name = test_loader.dataset.entries['PATH'][batch_idx]\n path_name = file_name.split(\".\")[0]\n\n label_name = print_label_name[tcls]\n\n if ATLAS_GEN:\n label_name = f\"ATLAS_{atlas_name}\"\n\n #if prob_ens[batch_idx, id_tcls].item() >= self.th_gradcam:\n if ATLAS_GEN:\n cam_rs = save_class_activation_images(data, cam, self.pt_runtime.joinpath(f\"{label_name}\"), path_name, hmp_dims)\n else:\n if '/' in path_name:\n self.pt_runtime.joinpath(f\"explain_sample/{self.f_name}/{label_name}/{path_name}\").parent.mkdir(parents=True, exist_ok=True)\n cam_rs = save_class_activation_images(data, cam, self.pt_runtime.joinpath(f\"explain_sample/{self.f_name}/{label_name}\"), path_name, hmp_dims)\n else:\n #review_cam\n cam, prob, tcls, cam_low = grad_cam.generate_cam(data, target_class=id_tcls, cam_w=cam_w, th_cam=0.5)\n cams[i, :, :] = cam_low\n\n return cams\n\n def roc_evaluation(self, test_set, predict_seq, target_seq, labels):\n out_dim = self.env.out_dim\n df_data = pd.DataFrame()\n df_data['PATH'] = test_set.entries['PATH']\n for i in range(out_dim):\n df_data[f'{labels[i]}'] = predict_seq.cpu().numpy()[:, i]\n df_data[f'{labels[i]}_GT'] = target_seq.cpu().numpy()[:, i]\n\n t = self.pt_runtime.joinpath('roc_result')\n Path.mkdir(t, parents=True, exist_ok=True)\n df_data.to_excel(t.joinpath('save_predicted_probabilities.xlsx'))\n\n roc_dim = out_dim \n for i in range(roc_dim):\n mask_out, mask_tar = self.mask_pred(predict_seq[:, i], target_seq[:, i])\n if mask_tar.cpu().numpy().size != 0 :\n fpr, tpr, thresholds = roc_curve(mask_tar.cpu().numpy(), mask_out.cpu().numpy())\n pre, rec, thresholds_pr = precision_recall_curve(mask_tar.cpu().numpy(), mask_out.cpu().numpy())\n #logger.debug(f\"{predict_seq.cpu().numpy()}\")\n df = pd.DataFrame()\n df[f'specificity'] = 1-fpr\n df[f'sensitivity'] = tpr\n df[f'thresholds'] = thresholds\n\n label_name = print_label_name[i]\n df.to_excel(t.joinpath(f'save_{i:03d}_{label_name}_sensitivity_specificity.xlsx'))\n del df\n\n if False:\n # ROC plot\n fig, (ax1, ax2) = plt.subplots(1,2)\n ax1.plot(fpr, tpr, color = 'darkorange', lw = 2, label = 'ROC curve')\n ax1.set_title(f'ROC curve for {labels[i]}')\n ax1.set(xlabel='False positive rate', ylabel='True positive rate')\n # PR plot\n ax2.plot(rec, pre, color = 'darkorange', lw = 2, label = 'Precision-Recall curve')\n ax2.set_title(f'Precision-Recall curve')\n ax2.set(xlabel='Recall', ylabel='Precision')\n plt.savefig(t.joinpath(f'{i:03d}_{label_name}_curve.png'))\n else:\n # ROC plot\n fig, ax1 = plt.subplots(1,1)\n ax1.plot(fpr, tpr, color = 'darkorange', lw = 2, label = f'{label_name}')\n ax1.set_title(f'ROC curve for {label_name}')\n ax1.set(xlabel='False positive rate', ylabel='True positive rate')\n plt.savefig(t.joinpath(f'{i:03d}_{label_name}_curve.png'))\n\n\n def save_prob(self, input_file, save_path):\n df = pd.read_csv(input_file)\n df.insert(6, 'prob', self.df_prob.PROB)\n df.insert(6, 'path_check', self.df_prob.PATH_CHECK)\n\n df.to_excel(save_path)\n\n\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser(description=\"Testng Our Explainable AI Model on CXR\")\n parser.add_argument('--cuda', default=None, type=str, help=\"use GPUs with its device ids, separated by commas\")\n\n args = parser.parse_args()\n args.in_dim = 1\n args.out_dim = 21\n args.labels = None\n args.paths = None\n args.runtime_dir = 'autolabeling'\n args.type = 0\n args.pretr_net = 'pa_feat_model'\n args.gradcam = False\n args.gradcam_cls = None\n args.fl_save = False\n args.id_prob = None\n args.test_csv = 'autolabeling_5_features_490_cases.csv'\n args.arch = None\n args.Nens = 6\n args.exai = True\n args.simname = 'Outputs'\n args.seed = -1\n\n runtime_path, device = initialize(args, fl_demo=True)\n fl_ensemble = False if args.Nens == 1 else True\n\n # start training\n env = TestEnvironment(device, mtype=args.type, in_dim=args.in_dim, out_dim=args.out_dim, name_labels=args.labels, name_paths=args.paths, testset_csv=args.test_csv, name_model=args.arch, r_seed=args.seed)\n t = Tester(env, pt_runtime=runtime_path, fn_net=args.pretr_net, fl_gradcam=args.gradcam, cls_gradcam=args.gradcam_cls, id_prob=args.id_prob, fl_ensemble=fl_ensemble, fl_exai=args.exai, f_name=args.simname, f_csv=args.test_csv)\n\n if(fl_ensemble):\n t.test_ensemble_evaluation(fl_save=args.fl_save, n_ens = args.Nens)\n else:\n t.test_evaluation(fl_save=args.fl_save)\n\n" ]
[ [ "pandas.read_csv", "torch.ones", "torch.zeros", "torch.cat", "torch.from_numpy", "pandas.DataFrame", "matplotlib.pyplot.subplots", "torch.nn.functional.sigmoid", "numpy.mean", "torch.no_grad", "torch.where", "torch.FloatTensor", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
aureocarneiro/sardana
[ "43644c9966d73c7a9023b53e97b530f3ea0dfb39", "43644c9966d73c7a9023b53e97b530f3ea0dfb39" ]
[ "src/sardana/macroserver/macros/scan.py", "src/sardana/macroserver/recorders/h5storage.py" ]
[ "##############################################################################\n##\n# This file is part of Sardana\n##\n# http://www.sardana-controls.org/\n##\n# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain\n##\n# Sardana is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n##\n# Sardana is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n##\n# You should have received a copy of the GNU Lesser General Public License\n# along with Sardana. If not, see <http://www.gnu.org/licenses/>.\n##\n##############################################################################\n\n\"\"\"\n Macro library containning scan macros for the macros server Tango device\n server as part of the Sardana project.\n\"\"\"\n\n__all__ = [\"a2scan\", \"a3scan\", \"a4scan\", \"amultiscan\", \"aNscan\", \"ascan\",\n \"d2scan\", \"d3scan\", \"d4scan\", \"dmultiscan\", \"dNscan\", \"dscan\",\n \"fscan\", \"mesh\", \"timescan\", \"rscan\", \"r2scan\", \"r3scan\",\n \"a2scanc\", \"a3scanc\", \"a4scanc\", \"ascanc\",\n \"d2scanc\", \"d3scanc\", \"d4scanc\", \"dscanc\",\n \"meshc\",\n \"a2scanct\", \"a3scanct\", \"a4scanct\", \"ascanct\", \"meshct\",\n \"scanhist\", \"getCallable\", \"UNCONSTRAINED\",\n \"scanstats\"]\n\n__docformat__ = 'restructuredtext'\n\nimport os\nimport copy\nimport datetime\n\nimport numpy\n\nfrom taurus.core.util import SafeEvaluator\n\nfrom sardana.macroserver.msexception import UnknownEnv\nfrom sardana.macroserver.macro import Hookable, Macro, Type, Table, List\nfrom sardana.macroserver.scan.gscan import SScan, CTScan, HScan, \\\n MoveableDesc, CSScan, TScan\nfrom sardana.util.motion import MotionPath\nfrom sardana.util.tree import BranchNode\n\nUNCONSTRAINED = \"unconstrained\"\n\nStepMode = 's'\n# TODO: change it to be more verbose e.g. ContinuousSwMode\nContinuousMode = 'c'\nContinuousHwTimeMode = 'ct'\nHybridMode = 'h'\n\n\ndef getCallable(repr):\n \"\"\"\n returns a function .\n Ideas: repr could be an URL for a file where the function is contained,\n or be evaluable code, or a pickled function object,...\n\n In any case, the return from it should be a callable of the form:\n f(x1,x2) where x1, x2 are points in the moveable space and the return value\n of f is True if the movement from x1 to x2 is allowed. False otherwise\n \"\"\"\n if repr == UNCONSTRAINED:\n return lambda x1, x2: True\n else:\n return lambda: None\n\n\n# TODO: remove starts\ndef _calculate_positions(moveable_node, start, end):\n '''Function to calculate starting and ending positions on the physical\n motors level.\n :param moveable_node: (BaseNode) node representing a moveable.\n Can be a BranchNode representing a PseudoMotor,\n or a LeafNode representing a PhysicalMotor).\n :param start: (float) starting position of the moveable\n :param end: (float) ending position of the moveable\n\n :return: (list<(float,float)>) a list of tuples comprising starting\n and ending positions. List order is important and preserved.'''\n start_positions = []\n end_positions = []\n if isinstance(moveable_node, BranchNode):\n pseudo_node = moveable_node\n moveable = pseudo_node.data\n moveable_nodes = moveable_node.children\n starts = moveable.calcPhysical(start)\n ends = moveable.calcPhysical(end)\n for moveable_node, start, end in zip(moveable_nodes, starts,\n ends):\n _start_positions, _end_positions = _calculate_positions(\n moveable_node,\n start, end)\n start_positions += _start_positions\n end_positions += _end_positions\n else:\n start_positions = [start]\n end_positions = [end]\n\n return start_positions, end_positions\n\n\nclass aNscan(Hookable):\n \"\"\"N-dimensional scan. This is **not** meant to be called by the user,\n but as a generic base to construct ascan, a2scan, a3scan,...\"\"\"\n\n hints = {'scan': 'aNscan', 'allowsHooks': ('pre-scan', 'pre-move',\n 'post-move', 'pre-acq',\n 'post-acq', 'post-step',\n 'post-scan')}\n # env = ('ActiveMntGrp',)\n\n def _prepare(self, motorlist, startlist, endlist, scan_length, integ_time,\n mode=StepMode, latency_time=0, **opts):\n\n self.motors = motorlist\n self.starts = numpy.array(startlist, dtype='d')\n self.finals = numpy.array(endlist, dtype='d')\n self.mode = mode\n self.integ_time = integ_time\n self.opts = opts\n if len(self.motors) == self.starts.size == self.finals.size:\n self.N = self.finals.size\n else:\n raise ValueError(\n 'Moveablelist, startlist and endlist must all be same length')\n\n moveables = []\n for m, start, final in zip(self.motors, self.starts, self.finals):\n moveables.append(MoveableDesc(moveable=m, min_value=min(\n start, final), max_value=max(start, final)))\n moveables[0].is_reference = True\n\n env = opts.get('env', {})\n constrains = [getCallable(cns) for cns in opts.get(\n 'constrains', [UNCONSTRAINED])]\n extrainfodesc = opts.get('extrainfodesc', [])\n\n # Hooks are not always set at this point. We will call getHooks\n # later on in the scan_loop\n # self.pre_scan_hooks = self.getHooks('pre-scan')\n # self.post_scan_hooks = self.getHooks('post-scan'\n\n if mode == StepMode:\n self.nr_interv = scan_length\n self.nb_points = self.nr_interv + 1\n self.interv_sizes = (self.finals - self.starts) / self.nr_interv\n self.name = opts.get('name', 'a%iscan' % self.N)\n self._gScan = SScan(self, self._stepGenerator,\n moveables, env, constrains, extrainfodesc)\n elif mode in [ContinuousMode, ContinuousHwTimeMode]:\n # TODO: probably not 100% correct,\n # the idea is to allow passing a list of waypoints\n if isinstance(endlist[0], list):\n self.waypoints = self.finals\n else:\n self.waypoints = [self.finals]\n self.nr_waypoints = len(self.waypoints)\n if mode == ContinuousMode:\n self.slow_down = scan_length\n # aNscans will only have two waypoints (the start and the final\n # positions)\n self.nr_waypoints = 2\n self.way_lengths = (\n self.finals - self.starts) / (self.nr_waypoints - 1)\n self.name = opts.get('name', 'a%iscanc' % self.N)\n self._gScan = CSScan(self, self._waypoint_generator,\n self._period_generator, moveables, env,\n constrains, extrainfodesc)\n elif mode == ContinuousHwTimeMode:\n self.nr_interv = scan_length\n self.nb_points = self.nr_interv + 1\n mg_name = self.getEnv('ActiveMntGrp')\n mg = self.getMeasurementGroup(mg_name)\n mg_latency_time = mg.getLatencyTime()\n if mg_latency_time > latency_time:\n self.info(\"Choosing measurement group latency time: %f\" %\n mg_latency_time)\n latency_time = mg_latency_time\n self.latency_time = latency_time\n self.name = opts.get('name', 'a%iscanct' % self.N)\n self._gScan = CTScan(self, self._waypoint_generator_hwtime,\n moveables,\n env,\n constrains,\n extrainfodesc)\n elif mode == HybridMode:\n self.nr_interv = scan_length\n self.nb_points = self.nr_interv + 1\n self.interv_sizes = (self.finals - self.starts) / self.nr_interv\n self.name = opts.get('name', 'a%iscanh' % self.N)\n self._gScan = HScan(self, self._stepGenerator,\n moveables, env, constrains, extrainfodesc)\n else:\n raise ValueError('invalid value for mode %s' % mode)\n # _data is the default member where the Macro class stores the data.\n # Assign the date produced by GScan (or its subclasses) to it so all\n # the Macro infrastructure related to the data works e.g. getter,\n # property, etc. Ideally this should be done by the data setter\n # but this is available in the Macro class and we inherit from it\n # latter. More details in sardana-org/sardana#683.\n self._data = self._gScan.data\n\n def _stepGenerator(self):\n step = {}\n step[\"integ_time\"] = self.integ_time\n step[\"pre-move-hooks\"] = self.getHooks('pre-move')\n step[\"post-move-hooks\"] = self.getHooks('post-move')\n step[\"pre-acq-hooks\"] = self.getHooks('pre-acq')\n step[\"post-acq-hooks\"] = self.getHooks('post-acq') + self.getHooks(\n '_NOHINTS_')\n step[\"post-step-hooks\"] = self.getHooks('post-step')\n\n step[\"check_func\"] = []\n for point_no in range(self.nb_points):\n step[\"positions\"] = self.starts + point_no * self.interv_sizes\n step[\"point_id\"] = point_no\n yield step\n\n def _waypoint_generator(self):\n step = {}\n step[\"pre-move-hooks\"] = self.getHooks('pre-move')\n step[\"post-move-hooks\"] = self.getHooks('post-move')\n step[\"check_func\"] = []\n step[\"slow_down\"] = self.slow_down\n for point_no in range(self.nr_waypoints):\n step[\"positions\"] = self.starts + point_no * self.way_lengths\n step[\"waypoint_id\"] = point_no\n yield step\n\n def _waypoint_generator_hwtime(self):\n\n # CScan in its constructor populates a list of data structures - trees.\n # Each tree represent one Moveables with its hierarchy of inferior\n # moveables.\n moveables_trees = self._gScan.get_moveables_trees()\n step = {}\n step[\"pre-move-hooks\"] = self.getHooks('pre-move')\n post_move_hooks = self.getHooks(\n 'post-move') + [self._fill_missing_records]\n step[\"post-move-hooks\"] = post_move_hooks\n step[\"pre-acq-hooks\"] = self.getHooks('pre-acq')\n step[\"post-acq-hooks\"] = self.getHooks('post-acq') + self.getHooks(\n '_NOHINTS_')\n step[\"check_func\"] = []\n step[\"active_time\"] = self.nb_points * (self.integ_time\n + self.latency_time)\n step[\"positions\"] = []\n step[\"start_positions\"] = []\n starts = self.starts\n for point_no, waypoint in enumerate(self.waypoints):\n for start, end, moveable_tree in zip(starts, waypoint,\n moveables_trees):\n moveable_root = moveable_tree.root()\n start_positions, end_positions = _calculate_positions(\n moveable_root, start, end)\n step[\"start_positions\"] += start_positions\n step[\"positions\"] += end_positions\n step[\"waypoint_id\"] = point_no\n starts = waypoint\n yield step\n\n def _period_generator(self):\n step = {}\n step[\"integ_time\"] = self.integ_time\n step[\"pre-acq-hooks\"] = self.getHooks('pre-acq')\n step[\"post-acq-hooks\"] = (self.getHooks('post-acq') +\n self.getHooks('_NOHINTS_'))\n step[\"post-step-hooks\"] = self.getHooks('post-step')\n step[\"check_func\"] = []\n step['extrainfo'] = {}\n point_no = 0\n while(True):\n point_no += 1\n step[\"point_id\"] = point_no\n yield step\n\n def run(self, *args):\n for step in self._gScan.step_scan():\n yield step\n\n def getTimeEstimation(self):\n gScan = self._gScan\n mode = self.mode\n it = gScan.generator()\n v_motors = gScan.get_virtual_motors()\n curr_pos = gScan.motion.readPosition()\n total_time = 0.0\n if mode == StepMode:\n # calculate motion time\n max_step0_time, max_step_time = 0.0, 0.0\n # first motion takes longer, all others should be \"equal\"\n step0 = next(it)\n for v_motor, start, stop, length in zip(v_motors, curr_pos,\n step0['positions'],\n self.interv_sizes):\n path0 = MotionPath(v_motor, start, stop)\n path = MotionPath(v_motor, 0, length)\n max_step0_time = max(max_step0_time, path0.duration)\n max_step_time = max(max_step_time, path.duration)\n motion_time = max_step0_time + self.nr_interv * max_step_time\n # calculate acquisition time\n acq_time = self.nb_points * self.integ_time\n total_time = motion_time + acq_time\n\n elif mode == ContinuousMode:\n total_time = gScan.waypoint_estimation()\n # TODO: add time estimation for ContinuousHwTimeMode\n return total_time\n\n def getIntervalEstimation(self):\n mode = self.mode\n if mode in [StepMode, ContinuousHwTimeMode, HybridMode]:\n return self.nr_interv\n elif mode == ContinuousMode:\n return self.nr_waypoints\n\n def _fill_missing_records(self):\n # fill record list with dummy records for the final padding\n nb_of_points = self.nb_points\n scan = self._gScan\n nb_of_records = len(scan.data.records)\n missing_records = nb_of_points - nb_of_records\n scan.data.initRecords(missing_records)\n\n def _get_nr_points(self):\n msg = (\"nr_points is deprecated since version 3.0.3. \"\n \"Use nb_points instead.\")\n self.warning(msg)\n return self.nb_points\n\n nr_points = property(_get_nr_points)\n\nclass dNscan(aNscan):\n \"\"\"\n same as aNscan but it interprets the positions as being relative to the\n current positions and upon completion, it returns the motors to their\n original positions\n \"\"\"\n\n hints = copy.deepcopy(aNscan.hints)\n hints['scan'] = 'dNscan'\n\n def _prepare(self, motorlist, startlist, endlist, scan_length,\n integ_time, mode=StepMode, **opts):\n self._motion = self.getMotion([m.getName() for m in motorlist])\n self.originalPositions = numpy.array(\n self._motion.readPosition(force=True))\n starts = numpy.array(startlist, dtype='d') + self.originalPositions\n finals = numpy.array(endlist, dtype='d') + self.originalPositions\n aNscan._prepare(self, motorlist, starts, finals,\n scan_length, integ_time, mode=mode, **opts)\n\n def do_restore(self):\n self.info(\"Returning to start positions...\")\n self._motion.move(self.originalPositions)\n\n\nclass ascan(aNscan, Macro):\n \"\"\"\n Do an absolute scan of the specified motor.\n ascan scans one motor, as specified by motor. The motor starts at the\n position given by start_pos and ends at the position given by final_pos.\n The step size is (start_pos-final_pos)/nr_interv. The number of data\n points collected will be nr_interv+1. Count time is given by time which\n if positive, specifies seconds and if negative, specifies monitor counts.\n \"\"\"\n\n param_def = [\n ['motor', Type.Moveable, None, 'Moveable to move'],\n ['start_pos', Type.Float, None, 'Scan start position'],\n ['final_pos', Type.Float, None, 'Scan final position'],\n ['nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time']\n ]\n\n def prepare(self, motor, start_pos, final_pos, nr_interv, integ_time,\n **opts):\n self._prepare([motor], [start_pos], [final_pos],\n nr_interv, integ_time, **opts)\n\n\nclass a2scan(aNscan, Macro):\n \"\"\"\n two-motor scan.\n a2scan scans two motors, as specified by motor1 and motor2.\n Each motor moves the same number of intervals with starting and ending\n positions given by start_pos1 and final_pos1, start_pos2 and final_pos2,\n respectively. The step size for each motor is:\n (start_pos-final_pos)/nr_interv\n The number of data points collected will be nr_interv+1.\n Count time is given by time which if positive, specifies seconds and\n if negative, specifies monitor counts.\n \"\"\"\n param_def = [\n ['motor1', Type.Moveable, None, 'Moveable 1 to move'],\n ['start_pos1', Type.Float, None, 'Scan start position 1'],\n ['final_pos1', Type.Float, None, 'Scan final position 1'],\n ['motor2', Type.Moveable, None, 'Moveable 2 to move'],\n ['start_pos2', Type.Float, None, 'Scan start position 2'],\n ['final_pos2', Type.Float, None, 'Scan final position 2'],\n ['nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time']\n ]\n\n def prepare(self, motor1, start_pos1, final_pos1, motor2, start_pos2,\n final_pos2, nr_interv, integ_time, **opts):\n self._prepare([motor1, motor2], [start_pos1, start_pos2], [\n final_pos1, final_pos2], nr_interv, integ_time, **opts)\n\n\nclass a3scan(aNscan, Macro):\n \"\"\"three-motor scan .\n a3scan scans three motors, as specified by motor1, motor2 and motor3.\n Each motor moves the same number of intervals with starting and ending\n positions given by start_pos1 and final_pos1, start_pos2 and final_pos2,\n start_pos3 and final_pos3, respectively.\n The step size for each motor is (start_pos-final_pos)/nr_interv.\n The number of data points collected will be nr_interv+1.\n Count time is given by time which if positive, specifies seconds and\n if negative, specifies monitor counts.\"\"\"\n param_def = [\n ['motor1', Type.Moveable, None, 'Moveable 1 to move'],\n ['start_pos1', Type.Float, None, 'Scan start position 1'],\n ['final_pos1', Type.Float, None, 'Scan final position 1'],\n ['motor2', Type.Moveable, None, 'Moveable 2 to move'],\n ['start_pos2', Type.Float, None, 'Scan start position 2'],\n ['final_pos2', Type.Float, None, 'Scan final position 2'],\n ['motor3', Type.Moveable, None, 'Moveable 3 to move'],\n ['start_pos3', Type.Float, None, 'Scan start position 3'],\n ['final_pos3', Type.Float, None, 'Scan final position 3'],\n ['nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time']\n ]\n\n def prepare(self, m1, s1, f1, m2, s2, f2, m3, s3, f3, nr_interv,\n integ_time, **opts):\n self._prepare([m1, m2, m3], [s1, s2, s3], [f1, f2, f3],\n nr_interv, integ_time, **opts)\n\n\nclass a4scan(aNscan, Macro):\n \"\"\"four-motor scan .\n a4scan scans four motors, as specified by motor1, motor2, motor3 and\n motor4.\n Each motor moves the same number of intervals with starting and ending\n positions given by start_posN and final_posN (for N=1,2,3,4).\n The step size for each motor is (start_pos-final_pos)/nr_interv.\n The number of data points collected will be nr_interv+1.\n Count time is given by time which if positive, specifies seconds and\n if negative, specifies monitor counts.\"\"\"\n param_def = [\n ['motor1', Type.Moveable, None, 'Moveable 1 to move'],\n ['start_pos1', Type.Float, None, 'Scan start position 1'],\n ['final_pos1', Type.Float, None, 'Scan final position 1'],\n ['motor2', Type.Moveable, None, 'Moveable 2 to move'],\n ['start_pos2', Type.Float, None, 'Scan start position 2'],\n ['final_pos2', Type.Float, None, 'Scan final position 2'],\n ['motor3', Type.Moveable, None, 'Moveable 3 to move'],\n ['start_pos3', Type.Float, None, 'Scan start position 3'],\n ['final_pos3', Type.Float, None, 'Scan final position 3'],\n ['motor4', Type.Moveable, None, 'Moveable 3 to move'],\n ['start_pos4', Type.Float, None, 'Scan start position 3'],\n ['final_pos4', Type.Float, None, 'Scan final position 3'],\n ['nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time']\n ]\n\n def prepare(self, m1, s1, f1, m2, s2, f2, m3, s3, f3, m4, s4, f4,\n nr_interv, integ_time, **opts):\n self._prepare([m1, m2, m3, m4], [s1, s2, s3, s4], [\n f1, f2, f3, f4], nr_interv, integ_time, **opts)\n\n\nclass amultiscan(aNscan, Macro):\n \"\"\"\n Multiple motor scan.\n amultiscan scans N motors, as specified by motor1, motor2,...,motorN.\n Each motor moves the same number of intervals with starting and ending\n positions given by start_posN and final_posN (for N=1,2,...).\n The step size for each motor is (start_pos-final_pos)/nr_interv.\n The number of data points collected will be nr_interv+1.\n Count time is given by time which if positive, specifies seconds and\n if negative, specifies monitor counts.\n \"\"\"\n\n param_def = [\n ['motor_start_end_list',\n [['motor', Type.Moveable, None, 'Moveable to move'],\n ['start', Type.Float, None, 'Starting position'],\n ['end', Type.Float, None, 'Final position']],\n None, 'List of motor, start and end positions'],\n ['nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time']\n ]\n\n def prepare(self, *args, **opts):\n motors = args[0:-2:3]\n starts = args[1:-2:3]\n ends = args[2:-2:3]\n nr_interv = args[-2]\n integ_time = args[-1]\n\n self._prepare(motors, starts, ends, nr_interv, integ_time, **opts)\n\n\nclass dmultiscan(dNscan, Macro):\n \"\"\"\n Multiple motor scan relative to the starting positions.\n dmultiscan scans N motors, as specified by motor1, motor2,...,motorN.\n Each motor moves the same number of intervals If each motor is at a\n position X before the scan begins, it will be scanned from X+start_posN\n to X+final_posN (where N is one of 1,2,...)\n The step size for each motor is (start_pos-final_pos)/nr_interv.\n The number of data points collected will be nr_interv+1.\n Count time is given by time which if positive, specifies seconds and\n if negative, specifies monitor counts.\n \"\"\"\n\n param_def = [\n ['motor_start_end_list',\n [['motor', Type.Moveable, None, 'Moveable to move'],\n ['start', Type.Float, None, 'Starting position'],\n ['end', Type.Float, None, 'Final position']],\n None, 'List of motor, start and end positions'],\n ['nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time']\n ]\n\n def prepare(self, *args, **opts):\n motors = args[0:-2:3]\n starts = args[1:-2:3]\n ends = args[2:-2:3]\n nr_interv = args[-2]\n integ_time = args[-1]\n\n self._prepare(motors, starts, ends, nr_interv, integ_time, **opts)\n\n\nclass dscan(dNscan, Macro):\n \"\"\"motor scan relative to the starting position.\n dscan scans one motor, as specified by motor. If motor motor is at a\n position X before the scan begins, it will be scanned from X+start_pos\n to X+final_pos. The step size is (start_pos-final_pos)/nr_interv.\n The number of data points collected will be nr_interv+1. Count time is\n given by time which if positive, specifies seconds and if negative,\n specifies monitor counts. \"\"\"\n\n param_def = [\n ['motor', Type.Moveable, None, 'Moveable to move'],\n ['start_pos', Type.Float, None, 'Scan start position'],\n ['final_pos', Type.Float, None, 'Scan final position'],\n ['nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time']\n ]\n\n def prepare(self, motor, start_pos, final_pos, nr_interv, integ_time,\n **opts):\n self._prepare([motor], [start_pos], [final_pos],\n nr_interv, integ_time, **opts)\n\n\nclass d2scan(dNscan, Macro):\n \"\"\"two-motor scan relative to the starting position.\n d2scan scans two motors, as specified by motor1 and motor2.\n Each motor moves the same number of intervals. If each motor is at a\n position X before the scan begins, it will be scanned from X+start_posN\n to X+final_posN (where N is one of 1,2).\n The step size for each motor is (start_pos-final_pos)/nr_interv.\n The number of data points collected will be nr_interv+1.\n Count time is given by time which if positive, specifies seconds and\n if negative, specifies monitor counts.\"\"\"\n param_def = [\n ['motor1', Type.Moveable, None, 'Moveable 1 to move'],\n ['start_pos1', Type.Float, None, 'Scan start position 1'],\n ['final_pos1', Type.Float, None, 'Scan final position 1'],\n ['motor2', Type.Moveable, None, 'Moveable 2 to move'],\n ['start_pos2', Type.Float, None, 'Scan start position 2'],\n ['final_pos2', Type.Float, None, 'Scan final position 2'],\n ['nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time']\n ]\n\n def prepare(self, motor1, start_pos1, final_pos1, motor2, start_pos2,\n final_pos2, nr_interv, integ_time, **opts):\n self._prepare([motor1, motor2], [start_pos1, start_pos2], [\n final_pos1, final_pos2], nr_interv, integ_time, **opts)\n\n\nclass d3scan(dNscan, Macro):\n \"\"\"three-motor scan .\n d3scan scans three motors, as specified by motor1, motor2 and motor3.\n Each motor moves the same number of intervals. If each motor is at a\n position X before the scan begins, it will be scanned from X+start_posN\n to X+final_posN (where N is one of 1,2,3)\n The step size for each motor is (start_pos-final_pos)/nr_interv.\n The number of data points collected will be nr_interv+1.\n Count time is given by time which if positive, specifies seconds and\n if negative, specifies monitor counts.\"\"\"\n\n param_def = [\n ['motor1', Type.Moveable, None, 'Moveable 1 to move'],\n ['start_pos1', Type.Float, None, 'Scan start position 1'],\n ['final_pos1', Type.Float, None, 'Scan final position 1'],\n ['motor2', Type.Moveable, None, 'Moveable 2 to move'],\n ['start_pos2', Type.Float, None, 'Scan start position 2'],\n ['final_pos2', Type.Float, None, 'Scan final position 2'],\n ['motor3', Type.Moveable, None, 'Moveable 3 to move'],\n ['start_pos3', Type.Float, None, 'Scan start position 3'],\n ['final_pos3', Type.Float, None, 'Scan final position 3'],\n ['nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time']\n ]\n\n def prepare(self, m1, s1, f1, m2, s2, f2, m3, s3, f3, nr_interv,\n integ_time, **opts):\n self._prepare([m1, m2, m3], [s1, s2, s3], [f1, f2, f3],\n nr_interv, integ_time, **opts)\n\n\nclass d4scan(dNscan, Macro):\n \"\"\"four-motor scan relative to the starting positions\n a4scan scans four motors, as specified by motor1, motor2, motor3 and\n motor4.\n Each motor moves the same number of intervals. If each motor is at a\n position X before the scan begins, it will be scanned from X+start_posN\n to X+final_posN (where N is one of 1,2,3,4).\n The step size for each motor is (start_pos-final_pos)/nr_interv.\n The number of data points collected will be nr_interv+1.\n Count time is given by time which if positive, specifies seconds and\n if negative, specifies monitor counts.\n Upon termination, the motors are returned to their starting positions.\n \"\"\"\n\n param_def = [\n ['motor1', Type.Moveable, None, 'Moveable 1 to move'],\n ['start_pos1', Type.Float, None, 'Scan start position 1'],\n ['final_pos1', Type.Float, None, 'Scan final position 1'],\n ['motor2', Type.Moveable, None, 'Moveable 2 to move'],\n ['start_pos2', Type.Float, None, 'Scan start position 2'],\n ['final_pos2', Type.Float, None, 'Scan final position 2'],\n ['motor3', Type.Moveable, None, 'Moveable 3 to move'],\n ['start_pos3', Type.Float, None, 'Scan start position 3'],\n ['final_pos3', Type.Float, None, 'Scan final position 3'],\n ['motor4', Type.Moveable, None, 'Moveable 3 to move'],\n ['start_pos4', Type.Float, None, 'Scan start position 3'],\n ['final_pos4', Type.Float, None, 'Scan final position 3'],\n ['nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time']\n ]\n\n def prepare(self, m1, s1, f1, m2, s2, f2, m3, s3, f3, m4, s4, f4,\n nr_interv, integ_time, **opts):\n self._prepare([m1, m2, m3, m4], [s1, s2, s3, s4], [\n f1, f2, f3, f4], nr_interv, integ_time, **opts)\n\n\nclass mesh(Macro, Hookable):\n \"\"\"2d grid scan.\n The mesh scan traces out a grid using motor1 and motor2.\n The first motor scans from m1_start_pos to m1_final_pos using the specified\n number of intervals. The second motor similarly scans from m2_start_pos\n to m2_final_pos. Each point is counted for for integ_time seconds\n (or monitor counts, if integ_time is negative).\n The scan of motor1 is done at each point scanned by motor2. That is, the\n first motor scan is nested within the second motor scan.\n \"\"\"\n\n hints = {'scan': 'mesh', 'allowsHooks': ('pre-scan', 'pre-move',\n 'post-move', 'pre-acq',\n 'post-acq', 'post-step',\n 'post-scan')}\n env = ('ActiveMntGrp',)\n\n param_def = [\n ['motor1', Type.Moveable, None, 'First motor to move'],\n ['m1_start_pos', Type.Float, None, 'Scan start position for first '\n 'motor'],\n ['m1_final_pos', Type.Float, None, 'Scan final position for first '\n 'motor'],\n ['m1_nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['motor2', Type.Moveable, None, 'Second motor to move'],\n ['m2_start_pos', Type.Float, None, 'Scan start position for second '\n 'motor'],\n ['m2_final_pos', Type.Float, None, 'Scan final position for second '\n 'motor'],\n ['m2_nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['bidirectional', Type.Boolean, False, 'Save time by scanning '\n 's-shaped']\n ]\n\n def prepare(self, m1, m1_start_pos, m1_final_pos, m1_nr_interv,\n m2, m2_start_pos, m2_final_pos, m2_nr_interv, integ_time,\n bidirectional, **opts):\n self.motors = [m1, m2]\n self.starts = numpy.array([m1_start_pos, m2_start_pos], dtype='d')\n self.finals = numpy.array([m1_final_pos, m2_final_pos], dtype='d')\n self.nr_intervs = numpy.array([m1_nr_interv, m2_nr_interv], dtype='i')\n self.nb_points = (m1_nr_interv + 1) * (m2_nr_interv + 1)\n self.integ_time = integ_time\n self.bidirectional_mode = bidirectional\n\n self.name = opts.get('name', 'mesh')\n\n generator = self._generator\n moveables = []\n for m, start, final in zip(self.motors, self.starts, self.finals):\n moveables.append(MoveableDesc(moveable=m,\n min_value=min(start, final),\n max_value=max(start, final)))\n moveables[0].is_reference = True\n env = opts.get('env', {})\n constrains = [getCallable(cns) for cns in opts.get(\n 'constrains', [UNCONSTRAINED])]\n\n # Hooks are not always set at this point. We will call getHooks\n # later on in the scan_loop\n # self.pre_scan_hooks = self.getHooks('pre-scan')\n # self.post_scan_hooks = self.getHooks('post-scan')\n\n self._gScan = SScan(self, generator, moveables, env, constrains)\n\n # _data is the default member where the Macro class stores the data.\n # Assign the date produced by GScan (or its subclasses) to it so all\n # the Macro infrastructure related to the data works e.g. getter,\n # property, etc.\n self.setData(self._gScan.data)\n\n def _generator(self):\n step = {}\n step[\"integ_time\"] = self.integ_time\n step[\"pre-move-hooks\"] = self.getHooks('pre-move')\n step[\"post-move-hooks\"] = self.getHooks('post-move')\n step[\"pre-acq-hooks\"] = self.getHooks('pre-acq')\n step[\"post-acq-hooks\"] = (self.getHooks('post-acq') +\n self.getHooks('_NOHINTS_'))\n step[\"post-step-hooks\"] = self.getHooks('post-step')\n step[\"check_func\"] = []\n m1start, m2start = self.starts\n m1end, m2end = self.finals\n points1, points2 = self.nr_intervs + 1\n point_no = 1\n m1_space = numpy.linspace(m1start, m1end, points1)\n m1_space_inv = numpy.linspace(m1end, m1start, points1)\n\n for i, m2pos in enumerate(numpy.linspace(m2start, m2end, points2)):\n space = m1_space\n if i % 2 != 0 and self.bidirectional_mode:\n space = m1_space_inv\n for m1pos in space:\n step[\"positions\"] = numpy.array([m1pos, m2pos])\n # TODO: maybe another ID would be better? (e.g. \"(A,B)\")\n step[\"point_id\"] = point_no\n point_no += 1\n yield step\n\n def run(self, *args):\n for step in self._gScan.step_scan():\n yield step\n\n\nclass dmesh(mesh):\n \"\"\"\n 2d relative grid scan.\n The relative mesh scan traces out a grid using motor1 and motor2.\n If first motor is at the position X before the scan begins, it will\n be scanned from X+m1_start_pos to X+m1_final_pos using the specified\n m1_nr_interv number of intervals. If the second motor is\n at the position Y before the scan begins, it will be scanned\n from Y+m2_start_pos to Y+m2_final_pos using the specified m2_nr_interv\n number of intervals.\n Each point is counted for the integ_time seconds (or monitor counts,\n if integ_time is negative).\n The scan of motor1 is done at each point scanned by motor2. That is, the\n first motor scan is nested within the second motor scan.\n Upon scan completion, it returns the motors to their original positions.\n \"\"\"\n\n hints = copy.deepcopy(mesh.hints)\n hints['scan'] = 'dmesh'\n\n env = copy.deepcopy(mesh.env)\n\n param_def = [\n ['motor1', Type.Moveable, None, 'First motor to move'],\n ['m1_start_pos', Type.Float, None, 'Scan start position for first '\n 'motor'],\n ['m1_final_pos', Type.Float, None, 'Scan final position for first '\n 'motor'],\n ['m1_nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['motor2', Type.Moveable, None, 'Second motor to move'],\n ['m2_start_pos', Type.Float, None, 'Scan start position for second '\n 'motor'],\n ['m2_final_pos', Type.Float, None, 'Scan final position for second '\n 'motor'],\n ['m2_nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['bidirectional', Type.Boolean, False, 'Save time by scanning '\n 's-shaped']\n ]\n\n def prepare(self, m1, m1_start_pos, m1_final_pos, m1_nr_interv,\n m2, m2_start_pos, m2_final_pos, m2_nr_interv, integ_time,\n bidirectional, **opts):\n self._motion = self.getMotion([m1, m2])\n self.originalPositions = numpy.array(\n self._motion.readPosition(force=True))\n start1 = self.originalPositions[0] + m1_start_pos\n start2 = self.originalPositions[1] + m2_start_pos\n final1 = self.originalPositions[0] + m1_final_pos\n final2 = self.originalPositions[1] + m2_final_pos\n mesh.prepare(self, m1, start1, final1, m1_nr_interv,\n m2, start2, final2, m2_nr_interv, integ_time,\n bidirectional, **opts)\n\n def do_restore(self):\n self.info(\"Returning to start positions...\")\n self._motion.move(self.originalPositions)\n\n\nclass fscan(Macro, Hookable):\n \"\"\"\n N-dimensional scan along user defined paths.\n The motion path for each motor is defined through the evaluation of a\n user-supplied function that is evaluated as a function of the independent\n variables.\n -independent variables are supplied through the indepvar string.\n The syntax for indepvar is \"x=expresion1,y=expresion2,...\"\n -If no indep vars need to be defined, write \"!\" or \"*\" or \"None\"\n -motion path for motor is generated by evaluating the corresponding\n function 'func'\n -Count time is given by integ_time. If integ_time is a scalar, then\n the same integ_time is used for all points. If it evaluates as an array\n (with same length as the paths), fscan will assign a different integration\n time to each acquisition point.\n -If integ_time is positive, it specifies seconds and if negative, specifies\n monitor counts.\n\n IMPORTANT Notes:\n -no spaces are allowed in the indepvar string.\n -all funcs must evaluate to the same number of points\n\n\n >>> fscan \"x=[1,3,5,7,9],y=arange(5)\" 0.1 motor1 x**2 motor2 sqrt(y*x+3)\n >>> fscan \"x=[1,3,5,7,9],y=arange(5)\" \"[0.1,0.2,0.3,0.4,0.5]\" motor1 x**2 \\\nmotor2 sqrt(y*x+3)\n \"\"\"\n\n # ['integ_time', Type.String, None, 'Integration time']\n hints = {'scan': 'fscan',\n 'allowsHooks': ('pre-scan', 'pre-move', 'post-move', 'pre-acq',\n 'post-acq', 'post-step', 'post-scan')}\n env = ('ActiveMntGrp',)\n\n param_def = [\n ['indepvars', Type.String, None, 'Independent Variables'],\n ['integ_time', Type.String, None, 'Integration time'],\n ['motor_funcs',\n [['motor', Type.Moveable, None, 'motor'],\n ['func', Type.String, None, 'curve defining path']],\n None, 'List of motor and path curves']\n ]\n\n def prepare(self, *args, **opts):\n if args[0].lower() in [\"!\", \"*\", \"none\", None]:\n indepvars = {}\n else:\n indepvars = SafeEvaluator({'dict': dict}).eval(\n 'dict(%s)' % args[0]) # create a dict containing the indepvars\n\n self.motors = [item[0] for item in args[2]]\n self.funcstrings = [item[1] for item in args[2]]\n\n globals_lst = [dict(list(zip(indepvars, values)))\n for values in zip(*list(indepvars.values()))]\n self.paths = [[SafeEvaluator(globals).eval(\n func) for globals in globals_lst] for func in self.funcstrings]\n\n self._integ_time = numpy.array(eval(args[1]), dtype='d')\n\n self.opts = opts\n if len(self.motors) == len(self.paths) > 0:\n self.N = len(self.motors)\n else:\n raise ValueError(\n 'Moveable and func lists must be non-empty and same length')\n npoints = len(self.paths[0])\n try:\n # if everything is OK, the following lines should return a 2D array\n # n which each motor path is a row.\n # Typical failure is due to shape mismatch due to inconsistent\n # input\n self.paths = numpy.array(self.paths, dtype='d')\n self.paths.reshape((self.N, npoints))\n except Exception: # shape mismatch?\n # try to give a meaningful description of the error\n for p, fs in zip(self.paths, self.funcstrings):\n if len(p) != npoints:\n raise ValueError('\"%s\" and \"%s\" yield different number '\n 'of points (%i vs %i)' %\n (self.funcstrings[0], fs, npoints,\n len(p)))\n raise # the problem wasn't a shape mismatch\n self._nb_points = npoints\n\n if self._integ_time.size == 1:\n self._integ_time = self._integ_time * \\\n numpy.ones(self._nb_points) # extend integ_time\n elif self._integ_time.size != self._nb_points:\n raise ValueError('time_integ must either be a scalar or '\n 'length=npoints (%i)' % self._nb_points)\n\n self.name = opts.get('name', 'fscan')\n\n generator = self._generator\n moveables = self.motors\n env = opts.get('env', {})\n constrains = [getCallable(cns) for cns in opts.get(\n 'constrains', [UNCONSTRAINED])]\n\n # Hooks are not always set at this point. We will call getHooks\n # later on in the scan_loop\n # self.pre_scan_hooks = self.getHooks('pre-scan')\n # self.post_scan_hooks = self.getHooks('post-scan'\n\n self._gScan = SScan(self, generator, moveables, env, constrains)\n\n # _data is the default member where the Macro class stores the data.\n # Assign the date produced by GScan (or its subclasses) to it so all\n # the Macro infrastructure related to the data works e.g. getter,\n # property, etc.\n self.setData(self._gScan.data)\n\n def _generator(self):\n step = {}\n step[\"pre-move-hooks\"] = self.getHooks('pre-move')\n step[\"post-move-hooks\"] = self.getHooks('post-move')\n step[\"pre-acq-hooks\"] = self.getHooks('pre-acq')\n step[\"post-acq-hooks\"] = (self.getHooks('post-acq') +\n self.getHooks('_NOHINTS_'))\n step[\"post-step-hooks\"] = self.getHooks('post-step')\n\n step[\"check_func\"] = []\n for i in range(self._nb_points):\n step[\"positions\"] = self.paths[:, i]\n step[\"integ_time\"] = self._integ_time[i]\n step[\"point_id\"] = i\n yield step\n\n def run(self, *args):\n for step in self._gScan.step_scan():\n yield step\n\n def _get_nr_points(self):\n msg = (\"nr_points is deprecated since version 3.0.3. \"\n \"Use nb_points instead.\")\n self.warning(msg)\n return self.nb_points\n\n nr_points = property(_get_nr_points)\n\n\n\nclass ascanh(aNscan, Macro):\n \"\"\"Do an absolute scan of the specified motor.\n ascan scans one motor, as specified by motor. The motor starts at the\n position given by start_pos and ends at the position given by final_pos.\n The step size is (start_pos-final_pos)/nr_interv. The number of data\n points collected will be nr_interv+1. Count time is given by time which\n if positive, specifies seconds and if negative, specifies monitor\n counts. \"\"\"\n\n param_def = [\n ['motor', Type.Moveable, None, 'Moveable to move'],\n ['start_pos', Type.Float, None, 'Scan start position'],\n ['final_pos', Type.Float, None, 'Scan final position'],\n ['nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time']\n ]\n\n def prepare(self, motor, start_pos, final_pos, nr_interv, integ_time,\n **opts):\n self._prepare([motor], [start_pos], [final_pos], nr_interv, integ_time,\n mode=HybridMode, **opts)\n\n\nclass rscan(Macro, Hookable):\n \"\"\"rscan.\n Do an absolute scan of the specified motor with different number of intervals for each region.\n It uses the gscan framework.\n \"\"\"\n\n hints = {'scan': 'rscan', 'allowsHooks': ('pre-scan', 'pre-move',\n 'post-move', 'pre-acq',\n 'post-acq', 'post-step',\n 'post-scan')}\n # env = ('ActiveMntGrp',)\n\n param_def = [\n ['motor', Type.Moveable, None, 'Motor to move'],\n ['start_pos', Type.Float, None, 'Start position'],\n ['regions',\n [['next_pos', Type.Float, None, 'next position'],\n ['region_nr_intervals', Type.Integer, None,\n 'Region number of intervals']],\n None, 'List of tuples: (next_pos, region_nr_intervals'],\n ['integ_time', Type.Float, None, 'Integration time']\n ]\n\n def prepare(self, motor, start_pos, regions, integ_time, **opts):\n self.name = 'rscan'\n self.integ_time = integ_time\n self.start_pos = start_pos\n self.regions = regions\n self.regions_count = len(self.regions) // 2\n\n generator = self._generator\n self.motors = [motor]\n env = opts.get('env', {})\n constrains = []\n self._gScan = SScan(self, generator, self.motors, env, constrains)\n self._data = self._gScan.data\n\n def _generator(self):\n step = {}\n step[\"integ_time\"] = self.integ_time\n step[\"pre-move-hooks\"] = self.getHooks('pre-move')\n step[\"post-move-hooks\"] = self.getHooks('post-move')\n step[\"pre-acq-hooks\"] = self.getHooks('pre-acq')\n step[\"post-acq-hooks\"] = self.getHooks('post-acq') + self.getHooks(\n '_NOHINTS_')\n step[\"post-step-hooks\"] = self.getHooks('post-step')\n\n point_id = 0\n region_start = self.start_pos\n for r in range(len(self.regions)):\n region_stop, region_nr_intervals = self.regions[\n r][0], self.regions[r][1]\n positions = numpy.linspace(\n region_start, region_stop, region_nr_intervals + 1)\n if point_id != 0:\n # positions must be calculated from the start to the end of the region\n # but after the first region, the 'start' point must not be\n # repeated\n positions = positions[1:]\n for p in positions:\n step['positions'] = [p]\n step['point_id'] = point_id\n point_id += 1\n yield step\n region_start = region_stop\n\n def run(self, *args):\n for step in self._gScan.step_scan():\n yield step\n\n\nclass r2scan(Macro, Hookable):\n \"\"\"r2scan.\n Do an absolute scan of the specified motors with different number of intervals for each region.\n It uses the gscan framework. All the motors will be drived to the same position in each step\n \"\"\"\n\n hints = {'scan': 'r2scan', 'allowsHooks': ('pre-scan', 'pre-move',\n 'post-move', 'pre-acq',\n 'post-acq', 'post-step',\n 'post-scan')}\n # env = ('ActiveMntGrp',)\n\n param_def = [\n ['motor1', Type.Moveable, None, 'Motor to move'],\n ['motor2', Type.Moveable, None, 'Motor to move'],\n ['start_pos', Type.Float, None, 'Start position'],\n ['regions',\n [['next_pos', Type.Float, None, 'next position'],\n ['region_nr_intervals', Type.Integer, None,\n 'Region number of intervals']],\n None, 'List of tuples: (next_pos, region_nr_intervals'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ]\n\n def prepare(self, motor1, motor2, start_pos, regions, integ_time, **opts):\n self.name = 'r2scan'\n self.integ_time = integ_time\n self.start_pos = start_pos\n self.regions = regions\n self.regions_count = len(self.regions) // 2\n\n generator = self._generator\n self.motors = [motor1, motor2]\n env = opts.get('env', {})\n constrains = []\n self._gScan = SScan(self, generator, self.motors, env, constrains)\n self._data = self._gScan.data\n\n def _generator(self):\n step = {}\n step[\"integ_time\"] = self.integ_time\n step[\"pre-move-hooks\"] = self.getHooks('pre-move')\n step[\"post-move-hooks\"] = self.getHooks('post-move')\n step[\"pre-acq-hooks\"] = self.getHooks('pre-acq')\n step[\"post-acq-hooks\"] = self.getHooks('post-acq') + self.getHooks(\n '_NOHINTS_')\n step[\"post-step-hooks\"] = self.getHooks('post-step')\n\n point_id = 0\n region_start = self.start_pos\n for r in range(len(self.regions)):\n region_stop, region_nr_intervals = self.regions[\n r][0], self.regions[r][1]\n positions = numpy.linspace(\n region_start, region_stop, region_nr_intervals + 1)\n if point_id != 0:\n # positions must be calculated from the start to the end of the region\n # but after the first region, the 'start' point must not be\n # repeated\n positions = positions[1:]\n for p in positions:\n step['positions'] = [p, p]\n step['point_id'] = point_id\n point_id += 1\n yield step\n region_start = region_stop\n\n def run(self, *args):\n for step in self._gScan.step_scan():\n yield step\n\n\nclass r3scan(Macro, Hookable):\n \"\"\"r3scan.\n Do an absolute scan of the specified motors with different number of\n intervals for each region. It uses the gscan framework.\n All the motors will be drived to the same position in each step\n\n \"\"\"\n\n hints = {'scan': 'r3scan', 'allowsHooks': ('pre-scan', 'pre-move',\n 'post-move', 'pre-acq',\n 'post-acq', 'post-step',\n 'post-scan')}\n # env = ('ActiveMntGrp',)\n\n param_def = [\n ['motor1', Type.Moveable, None, 'Motor to move'],\n ['motor2', Type.Moveable, None, 'Motor to move'],\n ['motor3', Type.Moveable, None, 'Motor to move'],\n ['start_pos', Type.Float, None, 'Start position'],\n ['regions',\n [['next_pos', Type.Float, None, 'next position'],\n ['region_nr_intervals', Type.Integer, None,\n 'Region number of intervals']],\n None, 'List of tuples: (next_pos, region_nr_intervals'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ]\n\n def prepare(self, motor1, motor2, motor3, start_pos, regions, integ_time, **opts):\n self.name = 'r3scan'\n self.integ_time = integ_time\n self.start_pos = start_pos\n self.regions = regions\n self.regions_count = len(self.regions) // 2\n\n generator = self._generator\n self.motors = [motor1, motor2, motor3]\n env = opts.get('env', {})\n constrains = []\n self._gScan = SScan(self, generator, self.motors, env, constrains)\n self._data = self._gScan.data\n\n def _generator(self):\n step = {}\n step[\"integ_time\"] = self.integ_time\n step[\"pre-move-hooks\"] = self.getHooks('pre-move')\n step[\"post-move-hooks\"] = self.getHooks('post-move')\n step[\"pre-acq-hooks\"] = self.getHooks('pre-acq')\n step[\"post-acq-hooks\"] = self.getHooks('post-acq') + self.getHooks(\n '_NOHINTS_')\n step[\"post-step-hooks\"] = self.getHooks('post-step')\n\n point_id = 0\n region_start = self.start_pos\n for r in range(len(self.regions)):\n region_stop, region_nr_intervals = self.regions[\n r][0], self.regions[r][1]\n positions = numpy.linspace(\n region_start, region_stop, region_nr_intervals + 1)\n if point_id != 0:\n # positions must be calculated from the start to the end of the region\n # but after the first region, the 'start' point must not be\n # repeated\n positions = positions[1:]\n for p in positions:\n step['positions'] = [p, p, p]\n step['point_id'] = point_id\n point_id += 1\n yield step\n region_start = region_stop\n\n def run(self, *args):\n for step in self._gScan.step_scan():\n yield step\n\n\nclass scanhist(Macro):\n \"\"\"Shows scan history information. Give optional parameter scan number to\n display details about a specific scan\"\"\"\n\n param_def = [\n ['scan number', Type.Integer, -1,\n 'scan number. [default=-1 meaning show all scans]'],\n ]\n\n def run(self, scan_number):\n try:\n hist = self.getEnv(\"ScanHistory\")\n except UnknownEnv:\n print(\"No scan recorded in history\")\n return\n if scan_number < 0:\n self.show_all(hist)\n else:\n self.show_one(hist, scan_number)\n\n def show_one(self, hist, scan_number):\n item = None\n for h in hist:\n if h['serialno'] == scan_number:\n item = h\n break\n if item is None:\n self.warning(\"Could not find scan number %s\", scan_number)\n return\n\n serialno, title = h['serialno'], h['title']\n start = datetime.datetime.fromtimestamp(h['startts'])\n end = datetime.datetime.fromtimestamp(h['endts'])\n total_time = end - start\n start, end, total_time = start.ctime(), end.ctime(), str(total_time)\n scan_dir, scan_file = h['ScanDir'], h['ScanFile']\n deadtime = '%.1f%%' % h['deadtime']\n\n user = h['user']\n store = \"Not stored!\"\n if scan_dir is not None and scan_file is not None:\n if isinstance(scan_file, str):\n store = os.path.join(scan_dir, scan_file)\n else:\n store = scan_dir + os.path.sep + str(scan_file)\n\n channels = \", \".join(h['channels'])\n cols = [\"#\", \"Title\", \"Start time\", \"End time\", \"Took\", \"Dead time\",\n \"User\", \"Stored\", \"Channels\"]\n data = [serialno, title, start, end, total_time, deadtime, user, store,\n channels]\n\n table = Table([data], row_head_str=cols, row_head_fmt='%*s',\n elem_fmt=['%-*s'],\n col_sep=' : ')\n for line in table.genOutput():\n self.output(line)\n\n def show_all(self, hist):\n\n cols = \"#\", \"Title\", \"Start time\", \"End time\", \"Stored\"\n width = -1, -1, -1, -1, -1\n out = List(cols, max_col_width=width)\n today = datetime.datetime.today().date()\n for h in hist:\n start = datetime.datetime.fromtimestamp(h['startts'])\n if start.date() == today:\n start = start.time().strftime(\"%H:%M:%S\")\n else:\n start = start.strftime(\"%Y-%m-%d %H:%M:%S\")\n end = datetime.datetime.fromtimestamp(h['endts'])\n if end.date() == today:\n end = end.time().strftime(\"%H:%M:%S\")\n else:\n end = end.strftime(\"%Y-%m-%d %H:%M:%S\")\n scan_file = h['ScanFile']\n store = \"Not stored!\"\n if scan_file is not None:\n store = \", \".join(scan_file)\n row = h['serialno'], h['title'], start, end, store\n out.appendRow(row)\n for line in out.genOutput():\n self.output(line)\n\n\nclass ascanc(aNscan, Macro):\n \"\"\"Do an absolute continuous scan of the specified motor.\n ascanc scans one motor, as specified by motor.\"\"\"\n\n param_def = [\n ['motor', Type.Moveable, None, 'Moveable to move'],\n ['start_pos', Type.Float, None, 'Scan start position'],\n ['final_pos', Type.Float, None, 'Scan final position'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['slow_down', Type.Float, 1, 'global scan slow down factor (0, 1]'],\n ]\n\n def prepare(self, motor, start_pos, final_pos, integ_time, slow_down,\n **opts):\n self._prepare([motor], [start_pos], [final_pos], slow_down,\n integ_time, mode=ContinuousMode, **opts)\n\n\nclass a2scanc(aNscan, Macro):\n \"\"\"two-motor continuous scan\"\"\"\n param_def = [\n ['motor1', Type.Moveable, None, 'Moveable 1 to move'],\n ['start_pos1', Type.Float, None, 'Scan start position 1'],\n ['final_pos1', Type.Float, None, 'Scan final position 1'],\n ['motor2', Type.Moveable, None, 'Moveable 2 to move'],\n ['start_pos2', Type.Float, None, 'Scan start position 2'],\n ['final_pos2', Type.Float, None, 'Scan final position 2'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['slow_down', Type.Float, 1, 'global scan slow down factor (0, 1]'],\n ]\n\n def prepare(self, motor1, start_pos1, final_pos1, motor2, start_pos2,\n final_pos2, integ_time, slow_down, **opts):\n self._prepare([motor1, motor2], [start_pos1, start_pos2],\n [final_pos1, final_pos2], slow_down, integ_time,\n mode=ContinuousMode, **opts)\n\n\nclass a3scanc(aNscan, Macro):\n \"\"\"three-motor continuous scan\"\"\"\n param_def = [\n ['motor1', Type.Moveable, None, 'Moveable 1 to move'],\n ['start_pos1', Type.Float, None, 'Scan start position 1'],\n ['final_pos1', Type.Float, None, 'Scan final position 1'],\n ['motor2', Type.Moveable, None, 'Moveable 2 to move'],\n ['start_pos2', Type.Float, None, 'Scan start position 2'],\n ['final_pos2', Type.Float, None, 'Scan final position 2'],\n ['motor3', Type.Moveable, None, 'Moveable 3 to move'],\n ['start_pos3', Type.Float, None, 'Scan start position 3'],\n ['final_pos3', Type.Float, None, 'Scan final position 3'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['slow_down', Type.Float, 1, 'global scan slow down factor (0, 1]'],\n ]\n\n def prepare(self, m1, s1, f1, m2, s2, f2, m3, s3, f3, integ_time,\n slow_down, **opts):\n self._prepare([m1, m2, m3], [s1, s2, s3], [f1, f2, f3], slow_down,\n integ_time, mode=ContinuousMode, **opts)\n\n\nclass a4scanc(aNscan, Macro):\n \"\"\"four-motor continuous scan\"\"\"\n param_def = [\n ['motor1', Type.Moveable, None, 'Moveable 1 to move'],\n ['start_pos1', Type.Float, None, 'Scan start position 1'],\n ['final_pos1', Type.Float, None, 'Scan final position 1'],\n ['motor2', Type.Moveable, None, 'Moveable 2 to move'],\n ['start_pos2', Type.Float, None, 'Scan start position 2'],\n ['final_pos2', Type.Float, None, 'Scan final position 2'],\n ['motor3', Type.Moveable, None, 'Moveable 3 to move'],\n ['start_pos3', Type.Float, None, 'Scan start position 3'],\n ['final_pos3', Type.Float, None, 'Scan final position 3'],\n ['motor4', Type.Moveable, None, 'Moveable 3 to move'],\n ['start_pos4', Type.Float, None, 'Scan start position 3'],\n ['final_pos4', Type.Float, None, 'Scan final position 3'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['slow_down', Type.Float, 1, 'global scan slow down factor (0, 1]'],\n ]\n\n def prepare(self, m1, s1, f1, m2, s2, f2, m3, s3, f3, m4, s4, f4,\n integ_time, slow_down, **opts):\n self._prepare([m1, m2, m3, m4], [s1, s2, s3, s4], [f1, f2, f3, f4],\n slow_down, integ_time, mode=ContinuousMode, **opts)\n\n\nclass dNscanc(dNscan):\n\n def do_restore(self):\n # set velocities to maximum and then move to initial positions\n for moveable in self.motors:\n self._gScan.set_max_top_velocity(moveable)\n dNscan.do_restore(self)\n\n\nclass dscanc(dNscanc, Macro):\n \"\"\"continuous motor scan relative to the starting position.\"\"\"\n\n param_def = [\n ['motor', Type.Moveable, None, 'Moveable to move'],\n ['start_pos', Type.Float, None, 'Scan start position'],\n ['final_pos', Type.Float, None, 'Scan final position'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['slow_down', Type.Float, 1, 'global scan slow down factor (0, 1]'],\n ]\n\n def prepare(self, motor, start_pos, final_pos, integ_time, slow_down,\n **opts):\n self._prepare([motor], [start_pos], [final_pos], slow_down, integ_time,\n mode=ContinuousMode, **opts)\n\n\nclass d2scanc(dNscanc, Macro):\n \"\"\"continuous two-motor scan relative to the starting positions\"\"\"\n\n param_def = [\n ['motor1', Type.Moveable, None, 'Moveable 1 to move'],\n ['start_pos1', Type.Float, None, 'Scan start position 1'],\n ['final_pos1', Type.Float, None, 'Scan final position 1'],\n ['motor2', Type.Moveable, None, 'Moveable 2 to move'],\n ['start_pos2', Type.Float, None, 'Scan start position 2'],\n ['final_pos2', Type.Float, None, 'Scan final position 2'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['slow_down', Type.Float, 1, 'global scan slow down factor (0, 1]'],\n ]\n\n def prepare(self, motor1, start_pos1, final_pos1, motor2, start_pos2,\n final_pos2, integ_time, slow_down, **opts):\n self._prepare([motor1, motor2], [start_pos1, start_pos2],\n [final_pos1, final_pos2], slow_down, integ_time,\n mode=ContinuousMode, **opts)\n\n\nclass d3scanc(dNscanc, Macro):\n \"\"\"continuous three-motor scan\"\"\"\n param_def = [\n ['motor1', Type.Moveable, None, 'Moveable 1 to move'],\n ['start_pos1', Type.Float, None, 'Scan start position 1'],\n ['final_pos1', Type.Float, None, 'Scan final position 1'],\n ['motor2', Type.Moveable, None, 'Moveable 2 to move'],\n ['start_pos2', Type.Float, None, 'Scan start position 2'],\n ['final_pos2', Type.Float, None, 'Scan final position 2'],\n ['motor3', Type.Moveable, None, 'Moveable 3 to move'],\n ['start_pos3', Type.Float, None, 'Scan start position 3'],\n ['final_pos3', Type.Float, None, 'Scan final position 3'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['slow_down', Type.Float, 1, 'global scan slow down factor (0, 1]'],\n ]\n\n def prepare(self, m1, s1, f1, m2, s2, f2, m3, s3, f3, integ_time,\n slow_down, **opts):\n self._prepare([m1, m2, m3], [s1, s2, s3], [f1, f2, f3], slow_down,\n integ_time, mode=ContinuousMode, **opts)\n\n\nclass d4scanc(dNscanc, Macro):\n \"\"\"continuous four-motor scan relative to the starting positions\"\"\"\n param_def = [\n ['motor1', Type.Moveable, None, 'Moveable 1 to move'],\n ['start_pos1', Type.Float, None, 'Scan start position 1'],\n ['final_pos1', Type.Float, None, 'Scan final position 1'],\n ['motor2', Type.Moveable, None, 'Moveable 2 to move'],\n ['start_pos2', Type.Float, None, 'Scan start position 2'],\n ['final_pos2', Type.Float, None, 'Scan final position 2'],\n ['motor3', Type.Moveable, None, 'Moveable 3 to move'],\n ['start_pos3', Type.Float, None, 'Scan start position 3'],\n ['final_pos3', Type.Float, None, 'Scan final position 3'],\n ['motor4', Type.Moveable, None, 'Moveable 3 to move'],\n ['start_pos4', Type.Float, None, 'Scan start position 3'],\n ['final_pos4', Type.Float, None, 'Scan final position 3'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['slow_down', Type.Float, 1, 'global scan slow down factor (0, 1]'],\n ]\n\n def prepare(self, m1, s1, f1, m2, s2, f2, m3, s3, f3, m4, s4, f4,\n integ_time, slow_down, **opts):\n self._prepare([m1, m2, m3, m4], [s1, s2, s3, s4], [f1, f2, f3, f4],\n slow_down, integ_time, mode=ContinuousMode, **opts)\n\n\nclass meshc(Macro, Hookable):\n \"\"\"2d grid scan. scans continuous\"\"\"\n\n hints = {'scan': 'mesh', 'allowsHooks': ('pre-scan', 'pre-move',\n 'post-move', 'pre-acq',\n 'post-acq', 'post-step',\n 'post-scan')}\n env = ('ActiveMntGrp',)\n\n param_def = [\n ['motor1', Type.Moveable, None, 'First motor to move'],\n ['m1_start_pos', Type.Float, None, 'Scan start position for first '\n 'motor'],\n ['m1_final_pos', Type.Float, None, 'Scan final position for first '\n 'motor'],\n ['slow_down', Type.Float, None, 'global scan slow down factor (0, 1]'],\n ['motor2', Type.Moveable, None, 'Second motor to move'],\n ['m2_start_pos', Type.Float, None, 'Scan start position for second '\n 'motor'],\n ['m2_final_pos', Type.Float, None, 'Scan final position for second '\n 'motor'],\n ['m2_nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['bidirectional', Type.Boolean, False, 'Save time by scanning '\n 's-shaped']\n ]\n\n def prepare(self, m1, m1_start_pos, m1_final_pos, slow_down,\n m2, m2_start_pos, m2_final_pos, m2_nr_interv, integ_time,\n bidirectional, **opts):\n self.motors = [m1, m2]\n self.slow_down = slow_down\n self.starts = numpy.array([m1_start_pos, m2_start_pos], dtype='d')\n self.finals = numpy.array([m1_final_pos, m2_final_pos], dtype='d')\n self.m2_nr_interv = m2_nr_interv\n self.integ_time = integ_time\n self.bidirectional_mode = bidirectional\n self.nr_waypoints = m2_nr_interv + 1\n\n self.name = opts.get('name', 'meshc')\n\n moveables = []\n for m, start, final in zip(self.motors, self.starts, self.finals):\n moveables.append(MoveableDesc(moveable=m, min_value=min(\n start, final), max_value=max(start, final)))\n moveables[0].is_reference = True\n\n env = opts.get('env', {})\n constrains = [getCallable(cns) for cns in opts.get(\n 'constrains', [UNCONSTRAINED])]\n extrainfodesc = opts.get('extrainfodesc', [])\n\n # Hooks are not always set at this point. We will call getHooks\n # later on in the scan_loop\n # self.pre_scan_hooks = self.getHooks('pre-scan')\n # self.post_scan_hooks = self.getHooks('post-scan'\n\n self._gScan = CSScan(self, self._waypoint_generator,\n self._period_generator, moveables, env,\n constrains, extrainfodesc)\n self._gScan.frozen_motors = [m2]\n\n # _data is the default member where the Macro class stores the data.\n # Assign the date produced by GScan (or its subclasses) to it so all\n # the Macro infrastructure related to the data works e.g. getter,\n # property, etc.\n self.setData(self._gScan.data)\n\n def _waypoint_generator(self):\n step = {}\n step[\"pre-move-hooks\"] = self.getHooks('pre-move')\n step[\"post-move-hooks\"] = self.getHooks('post-move')\n step[\"check_func\"] = []\n step[\"slow_down\"] = self.slow_down\n points2 = self.m2_nr_interv + 1\n m1start, m2start = self.starts\n m1end, m2end = self.finals\n point_no = 1\n for i, m2pos in enumerate(numpy.linspace(m2start, m2end, points2)):\n start, end = m1start, m1end\n if i % 2 != 0 and self.bidirectional_mode:\n start, end = m1end, m1start\n step[\"start_positions\"] = numpy.array([start, m2pos])\n step[\"positions\"] = numpy.array([end, m2pos])\n step[\"point_id\"] = point_no\n point_no += 1\n yield step\n\n def _period_generator(self):\n step = {}\n step[\"integ_time\"] = self.integ_time\n step[\"pre-acq-hooks\"] = self.getHooks('pre-acq')\n step[\"post-acq-hooks\"] = (self.getHooks('post-acq') +\n self.getHooks('_NOHINTS_'))\n step[\"post-step-hooks\"] = self.getHooks('post-step')\n step[\"check_func\"] = []\n step['extrainfo'] = {}\n point_no = 0\n while(True):\n point_no += 1\n step[\"point_id\"] = point_no\n yield step\n\n def run(self, *args):\n for step in self._gScan.step_scan():\n yield step\n\n def getTimeEstimation(self):\n return self._gScan.waypoint_estimation()\n\n def getIntervalEstimation(self):\n return self.nr_waypoints\n\n\nclass dmeshc(meshc):\n \"\"\"2d relative continuous grid scan.\n The relative mesh scan traces out a grid using motor1 and motor2.\n If first motor is at the position X before the scan begins, it will\n be continuously scanned from X+m1_start_pos to X+m1_final_pos.\n If the second motor is at the position Y before the scan begins,\n it will be discrete scanned from Y+m2_start_pos to Y+m2_final_pos\n using the specified m2_nr_interv number of intervals.\n The scan considers the accel. and decel. times of the motor1, so the\n counts (for the integ_time seconds or monitor counts,\n if integ_time is negative) are executed while motor1 is moving\n with the constant velocity.\n Upon scan completion, it returns the motors to their original positions.\n \"\"\"\n\n hints = copy.deepcopy(meshc.hints)\n hints['scan'] = 'dmeshc'\n\n env = copy.deepcopy(meshc.env)\n\n param_def = [\n ['motor1', Type.Moveable, None, 'First motor to move'],\n ['m1_start_pos', Type.Float, None, 'Scan start position for first '\n 'motor'],\n ['m1_final_pos', Type.Float, None, 'Scan final position for first '\n 'motor'],\n ['slow_down', Type.Float, None, 'global scan slow down factor (0, 1]'],\n ['motor2', Type.Moveable, None, 'Second motor to move'],\n ['m2_start_pos', Type.Float, None, 'Scan start position for second '\n 'motor'],\n ['m2_final_pos', Type.Float, None, 'Scan final position for second '\n 'motor'],\n ['m2_nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['bidirectional', Type.Boolean, False, 'Save time by scanning '\n 's-shaped']\n ]\n\n def prepare(self, m1, m1_start_pos, m1_final_pos, slow_down,\n m2, m2_start_pos, m2_final_pos, m2_nr_interv, integ_time,\n bidirectional, **opts):\n self._motion = self.getMotion([m1, m2])\n self.originalPositions = numpy.array(\n self._motion.readPosition(force=True))\n start1 = self.originalPositions[0] + m1_start_pos\n start2 = self.originalPositions[1] + m2_start_pos\n final1 = self.originalPositions[0] + m1_final_pos\n final2 = self.originalPositions[1] + m2_final_pos\n meshc.prepare(self, m1, start1, final1, slow_down,\n m2, start2, final2, m2_nr_interv, integ_time,\n bidirectional, **opts)\n\n def do_restore(self):\n self.info(\"Returning to start positions...\")\n self._motion.move(self.originalPositions)\n\n\nclass aNscanct(aNscan):\n \"\"\"N-dimensional continuous scan. This is **not** meant to be called by\n the user, but as a generic base to construct ascanct, a2scanct, a3scanct,\n ...\"\"\"\n\n hints = {\"scan\": \"aNscanct\",\n \"allowsHooks\": (\"pre-scan\", \"pre-configuration\",\n \"post-configuration\", \"pre-move\",\n \"post-move\", \"pre-acq\", \"pre-start\",\n \"post-acq\", \"pre-cleanup\", \"post-cleanup\",\n \"post-scan\")}\n\n\nclass ascanct(aNscanct, Macro):\n \"\"\"Do an absolute continuous scan of the specified motor.\n ascanct scans one motor, as specified by motor. The motor starts before the\n position given by start_pos in order to reach the constant velocity at the\n start_pos and finishes at the position after the final_pos in order to\n maintain the constant velocity until the final_pos.\"\"\"\n\n param_def = [['motor', Type.Moveable, None, 'Moveable name'],\n ['start_pos', Type.Float, None, 'Scan start position'],\n ['final_pos', Type.Float, None, 'Scan final position'],\n ['nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['latency_time', Type.Float, 0, 'Latency time']]\n\n def prepare(self, motor, start_pos, final_pos, nr_interv,\n integ_time, latency_time, **opts):\n self._prepare([motor], [start_pos], [final_pos], nr_interv,\n integ_time, mode=ContinuousHwTimeMode,\n latency_time=latency_time, **opts)\n\n\nclass a2scanct(aNscanct, Macro):\n \"\"\"Two-motor continuous scan.\n a2scanct scans two motors, as specified by motor1 and motor2. Each motor\n starts before the position given by its start_pos in order to reach the\n constant velocity at its start_pos and finishes at the position after\n its final_pos in order to maintain the constant velocity until its\n final_pos.\"\"\"\n\n param_def = [\n ['motor1', Type.Moveable, None, 'Moveable 1 to move'],\n ['start_pos1', Type.Float, None, 'Scan start position 1'],\n ['final_pos1', Type.Float, None, 'Scan final position 1'],\n ['motor2', Type.Moveable, None, 'Moveable 2 to move'],\n ['start_pos2', Type.Float, None, 'Scan start position 2'],\n ['final_pos2', Type.Float, None, 'Scan final position 2'],\n ['nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['latency_time', Type.Float, 0, 'Latency time']]\n\n def prepare(self, m1, s1, f1, m2, s2, f2, nr_interv,\n integ_time, latency_time, **opts):\n self._prepare([m1, m2], [s1, s2], [f1, f2], nr_interv,\n integ_time, mode=ContinuousHwTimeMode,\n latency_time=latency_time, **opts)\n\n\nclass a3scanct(aNscanct, Macro):\n \"\"\"Three-motor continuous scan.\n a2scanct scans three motors, as specified by motor1, motor2 and motor3.\n Each motor starts before the position given by its start_pos in order to\n reach the constant velocity at its start_pos and finishes at the position\n after its final_pos in order to maintain the constant velocity until its\n final_pos.\"\"\"\n\n param_def = [\n ['motor1', Type.Moveable, None, 'Moveable 1 to move'],\n ['start_pos1', Type.Float, None, 'Scan start position 1'],\n ['final_pos1', Type.Float, None, 'Scan final position 1'],\n ['motor2', Type.Moveable, None, 'Moveable 2 to move'],\n ['start_pos2', Type.Float, None, 'Scan start position 2'],\n ['final_pos2', Type.Float, None, 'Scan final position 2'],\n ['motor3', Type.Moveable, None, 'Moveable 3 to move'],\n ['start_pos3', Type.Float, None, 'Scan start position 3'],\n ['final_pos3', Type.Float, None, 'Scan final position 3'],\n ['nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['latency_time', Type.Float, 0, 'Latency time']]\n\n def prepare(self, m1, s1, f1, m2, s2, f2, m3, s3, f3, nr_interv,\n integ_time, latency_time, **opts):\n self._prepare([m1, m2, m3], [s1, s2, s3], [f1, f2, f3], nr_interv,\n integ_time, mode=ContinuousHwTimeMode,\n latency_time=latency_time, **opts)\n\n\nclass a4scanct(aNscan, Macro):\n \"\"\"Four-motor continuous scan.\n a2scanct scans four motors, as specified by motor1, motor2, motor3 and\n motor4. Each motor starts before the position given by its start_pos in\n order to reach the constant velocity at its start_pos and finishes at the\n position after its final_pos in order to maintain the constant velocity\n until its final_pos.\"\"\"\n\n param_def = [\n ['motor1', Type.Moveable, None, 'Moveable 1 to move'],\n ['start_pos1', Type.Float, None, 'Scan start position 1'],\n ['final_pos1', Type.Float, None, 'Scan final position 1'],\n ['motor2', Type.Moveable, None, 'Moveable 2 to move'],\n ['start_pos2', Type.Float, None, 'Scan start position 2'],\n ['final_pos2', Type.Float, None, 'Scan final position 2'],\n ['motor3', Type.Moveable, None, 'Moveable 3 to move'],\n ['start_pos3', Type.Float, None, 'Scan start position 3'],\n ['final_pos3', Type.Float, None, 'Scan final position 3'],\n ['motor4', Type.Moveable, None, 'Moveable 4 to move'],\n ['start_pos4', Type.Float, None, 'Scan start position 4'],\n ['final_pos4', Type.Float, None, 'Scan final position 4'],\n ['nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['latency_time', Type.Float, 0, 'Latency time']]\n\n def prepare(self, m1, s1, f1, m2, s2, f2, m3, s3, f3, m4, s4, f4,\n nr_interv, integ_time, latency_time, **opts):\n self._prepare([m1, m2, m3, m4], [s1, s2, s3, s4], [f1, f2, f3, f4],\n nr_interv, integ_time, mode=ContinuousHwTimeMode,\n latency_time=latency_time, **opts)\n\n\nclass dNscanct(dNscan):\n \"\"\"N-dimensional continuous scan. This is **not** meant to be called by\n the user, but as a generic base to construct ascanct, a2scanct, a3scanct,\n ...\"\"\"\n\n hints = {\"scan\": \"dNscanct\",\n \"allowsHooks\": (\"pre-scan\", \"pre-configuration\",\n \"post-configuration\", \"pre-move\",\n \"post-move\", \"pre-acq\", \"pre-start\",\n \"post-acq\", \"pre-cleanup\", \"post-cleanup\",\n \"post-scan\")}\n\n\nclass dscanct(dNscanct, Macro):\n \"\"\"Do an a relative continuous motor scan,\n dscanct scans a motor, as specified by motor1.\n The Motor starts before the position given by its start_pos in order to\n reach the constant velocity at its start_pos and finishes at the position\n after its final_pos in order to maintain the constant velocity until its\n final_pos.\"\"\"\n\n param_def = [['motor', Type.Moveable, None, 'Moveable name'],\n ['start_pos', Type.Float, None, 'Scan start position'],\n ['final_pos', Type.Float, None, 'Scan final position'],\n ['nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['latency_time', Type.Float, 0, 'Latency time']]\n\n def prepare(self, motor, start_pos, final_pos, nr_interv,\n integ_time, latency_time, **opts):\n self._prepare([motor], [start_pos], [final_pos], nr_interv,\n integ_time, mode=ContinuousHwTimeMode,\n latency_time=latency_time, **opts)\n\n\nclass d2scanct(dNscanct, Macro):\n \"\"\"continuous two-motor scan relative to the starting positions,\n d2scanct scans three motors, as specified by motor1 and motor2.\n Each motor starts before the position given by its start_pos in order to\n reach the constant velocity at its start_pos and finishes at the position\n after its final_pos in order to maintain the constant velocity until its\n final_pos.\n \"\"\"\n param_def = [\n ['motor1', Type.Moveable, None, 'Moveable 1 to move'],\n ['start_pos1', Type.Float, None, 'Scan start position 1'],\n ['final_pos1', Type.Float, None, 'Scan final position 1'],\n ['motor2', Type.Moveable, None, 'Moveable 2 to move'],\n ['start_pos2', Type.Float, None, 'Scan start position 2'],\n ['final_pos2', Type.Float, None, 'Scan final position 2'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['slow_down', Type.Float, 1, 'global scan slow down factor (0, 1]'],\n ]\n\n def prepare(self, m1, s1, f1, m2, s2, f2, integ_time, slow_down, **opts):\n self._prepare([m1, m2], [s1, s2], [f1, f2], slow_down, integ_time,\n mode=ContinuousHwTimeMode, **opts)\n\n\nclass d3scanct(dNscanct, Macro):\n \"\"\"continuous three-motor scan relative to the starting positions,\n d3scanct scans three motors, as specified by motor1, motor2 and motor3.\n Each motor starts before the position given by its start_pos in order to\n reach the constant velocity at its start_pos and finishes at the position\n after its final_pos in order to maintain the constant velocity until its\n final_pos.\n \"\"\"\n param_def = [\n ['motor1', Type.Moveable, None, 'Moveable 1 to move'],\n ['start_pos1', Type.Float, None, 'Scan start position 1'],\n ['final_pos1', Type.Float, None, 'Scan final position 1'],\n ['motor2', Type.Moveable, None, 'Moveable 2 to move'],\n ['start_pos2', Type.Float, None, 'Scan start position 2'],\n ['final_pos2', Type.Float, None, 'Scan final position 2'],\n ['motor3', Type.Moveable, None, 'Moveable 3 to move'],\n ['start_pos3', Type.Float, None, 'Scan start position 3'],\n ['final_pos3', Type.Float, None, 'Scan final position 3'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['slow_down', Type.Float, 1, 'global scan slow down factor (0, 1]'],\n ]\n\n def prepare(self, m1, s1, f1, m2, s2, f2, m3, s3, f3, integ_time,\n slow_down, **opts):\n self._prepare([m1, m2, m3], [s1, s2, s3], [f1, f2, f3], slow_down,\n integ_time, mode=ContinuousHwTimeMode, **opts)\n\n\nclass d4scanct(dNscanct, Macro):\n \"\"\"continuous four-motor scan relative to the starting positions,\n d4scanct scans three motors, as specified by motor1, motor2, motor3 and\n motor4.\n Each motor starts before the position given by its start_pos in order to\n reach the constant velocity at its start_pos and finishes at the position\n after its final_pos in order to maintain the constant velocity until its\n final_pos.\"\"\"\n param_def = [\n ['motor1', Type.Moveable, None, 'Moveable 1 to move'],\n ['start_pos1', Type.Float, None, 'Scan start position 1'],\n ['final_pos1', Type.Float, None, 'Scan final position 1'],\n ['motor2', Type.Moveable, None, 'Moveable 2 to move'],\n ['start_pos2', Type.Float, None, 'Scan start position 2'],\n ['final_pos2', Type.Float, None, 'Scan final position 2'],\n ['motor3', Type.Moveable, None, 'Moveable 3 to move'],\n ['start_pos3', Type.Float, None, 'Scan start position 3'],\n ['final_pos3', Type.Float, None, 'Scan final position 3'],\n ['motor4', Type.Moveable, None, 'Moveable 3 to move'],\n ['start_pos4', Type.Float, None, 'Scan start position 3'],\n ['final_pos4', Type.Float, None, 'Scan final position 3'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['slow_down', Type.Float, 1, 'global scan slow down factor (0, 1]'],\n ]\n\n def prepare(self, m1, s1, f1, m2, s2, f2, m3, s3, f3, m4, s4, f4,\n integ_time, slow_down, **opts):\n self._prepare([m1, m2, m3, m4], [s1, s2, s3, s4], [f1, f2, f3, f4],\n slow_down, integ_time, mode=ContinuousHwTimeMode, **opts)\n\n\nclass meshct(Macro, Hookable):\n \"\"\"2d grid scan .\n The mesh scan traces out a grid using motor1 and motor2.\n The first motor scans in contiuous mode from m1_start_pos to m1_final_pos\n using the specified number of intervals. The second motor similarly\n scans from m2_start_pos to m2_final_pos but it does not move during the\n continuous scan. Each point is counted for integ_time seconds\n (or monitor counts, if integ_time is negative).\n The scan of motor1 is done at each point scanned by motor2. That is, the\n first motor scan is nested within the second motor scan.\n \"\"\"\n\n hints = {\"scan\": \"meshct\",\n \"allowsHooks\": (\"pre-scan\", \"pre-configuration\",\n \"post-configuration\", \"pre-move\",\n \"post-move\", \"pre-acq\", \"pre-start\",\n \"post-acq\", \"pre-cleanup\", \"post-cleanup\",\n \"post-scan\")}\n env = ('ActiveMntGrp',)\n\n param_def = [\n ['motor1', Type.Moveable, None, 'First motor to move'],\n ['m1_start_pos', Type.Float, None, 'Scan start position for first '\n 'motor'],\n ['m1_final_pos', Type.Float, None, 'Scan final position for first '\n 'motor'],\n ['m1_nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['motor2', Type.Moveable, None, 'Second motor to move'],\n ['m2_start_pos', Type.Float, None, 'Scan start position for second '\n 'motor'],\n ['m2_final_pos', Type.Float, None, 'Scan final position for second '\n 'motor'],\n ['m2_nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['bidirectional', Type.Boolean, False, 'Save time by scanning '\n 's-shaped'],\n ['latency_time', Type.Float, 0, 'Latency time']\n ]\n\n def prepare(self, m1, m1_start_pos, m1_final_pos, m1_nr_interv,\n m2, m2_start_pos, m2_final_pos, m2_nr_interv, integ_time,\n bidirectional, latency_time, **opts):\n\n self.motors = [m1, m2]\n self.starts = numpy.array([m1_start_pos, m2_start_pos], dtype='d')\n self.finals = numpy.array([m1_final_pos, m2_final_pos], dtype='d')\n self.nr_intervs = numpy.array([m1_nr_interv, m2_nr_interv], dtype='i')\n\n # Number of intervals of the first motor which is doing the\n # continuous scan.\n self.nr_interv = m1_nr_interv\n self.nb_points = self.nr_interv + 1\n self.integ_time = integ_time\n self.bidirectional_mode = bidirectional\n\n # Prepare the waypoints\n m1start, m2start = self.starts\n m1end, m2end = self.finals\n points1, points2 = self.nr_intervs + 1\n\n m2_space = numpy.linspace(m2start, m2end, points2)\n self.waypoints = []\n self.starts_points = []\n for i, m2pos in enumerate(m2_space):\n self.starts_points.append(numpy.array([m1start, m2pos], dtype='d'))\n self.waypoints.append(numpy.array([m1end, m2pos], dtype='d'))\n if self.bidirectional_mode:\n m1start, m1end = m1end, m1start\n\n self.name = opts.get('name', 'meshct')\n\n moveables = []\n for m, start, final in zip(self.motors, self.starts, self.finals):\n moveables.append(MoveableDesc(moveable=m, min_value=min(\n start, final), max_value=max(start, final)))\n moveables[0].is_reference = True\n\n env = opts.get('env', {})\n mg_name = self.getEnv('ActiveMntGrp')\n mg = self.getMeasurementGroup(mg_name)\n mg_latency_time = mg.getLatencyTime()\n if mg_latency_time > latency_time:\n self.info(\"Choosing measurement group latency time: %f\" %\n mg_latency_time)\n latency_time = mg_latency_time\n\n self.latency_time = latency_time\n\n constrains = [getCallable(cns) for cns in opts.get('constrains',\n [UNCONSTRAINED])]\n\n extrainfodesc = opts.get('extrainfodesc', [])\n\n # Hooks are not always set at this point. We will call getHooks\n # later on in the scan_loop\n # self.pre_scan_hooks = self.getHooks('pre-scan')\n # self.post_scan_hooks = self.getHooks('post-scan')\n\n self._gScan = CTScan(self, self._generator, moveables, env, constrains,\n extrainfodesc)\n # _data is the default member where the Macro class stores the data.\n # Assign the date produced by GScan (or its subclasses) to it so all\n # the Macro infrastructure related to the data works e.g. getter,\n # property, etc.\n self.setData(self._gScan.data)\n\n def _generator(self):\n moveables_trees = self._gScan.get_moveables_trees()\n step = {}\n step[\"pre-move-hooks\"] = self.getHooks('pre-move')\n post_move_hooks = self.getHooks(\n 'post-move') + [self._fill_missing_records]\n step[\"post-move-hooks\"] = post_move_hooks\n step[\"check_func\"] = []\n step[\"active_time\"] = self.nb_points * (self.integ_time\n + self.latency_time)\n\n points1, _ = self.nr_intervs + 1\n for i, waypoint in enumerate(self.waypoints):\n self.point_id = points1 * i\n step[\"waypoint_id\"] = i\n self.starts = self.starts_points[i]\n self.finals = waypoint\n step[\"positions\"] = []\n step[\"start_positions\"] = []\n\n for start, end, moveable_tree in zip(self.starts, self.finals,\n moveables_trees):\n moveable_root = moveable_tree.root()\n start_positions, end_positions = _calculate_positions(\n moveable_root, start, end)\n step[\"start_positions\"] += start_positions\n step[\"positions\"] += end_positions\n\n yield step\n\n def run(self, *args):\n for step in self._gScan.step_scan():\n yield step\n\n def getTimeEstimation(self):\n return 0.0\n\n def getIntervalEstimation(self):\n return len(self.waypoints)\n\n def _fill_missing_records(self):\n # fill record list with dummy records for the final padding\n nb_of_points = self.nb_points\n scan = self._gScan\n nb_of_total_records = len(scan.data.records)\n nb_of_records = nb_of_total_records - self.point_id\n missing_records = nb_of_points - nb_of_records\n scan.data.initRecords(missing_records)\n\n def _get_nr_points(self):\n msg = (\"nr_points is deprecated since version 3.0.3. \"\n \"Use nb_points instead.\")\n self.warning(msg)\n return self.nb_points\n\n nr_points = property(_get_nr_points)\n\n\nclass timescan(Macro, Hookable):\n \"\"\"Do a time scan over the specified time intervals. The scan starts\n immediately. The number of data points collected will be nr_interv + 1.\n Count time is given by integ_time. Latency time will be the longer one\n of latency_time and measurement group latency time.\n \"\"\"\n\n hints = {'scan': 'timescan', 'allowsHooks': ('pre-scan', 'pre-acq',\n 'post-acq', 'post-scan')}\n\n param_def = [\n ['nr_interv', Type.Integer, None, 'Number of scan intervals'],\n ['integ_time', Type.Float, None, 'Integration time'],\n ['latency_time', Type.Float, 0, 'Latency time']]\n\n def prepare(self, nr_interv, integ_time, latency_time):\n self.nr_interv = nr_interv\n self.nb_points = nr_interv + 1\n self.integ_time = integ_time\n self.latency_time = latency_time\n self._gScan = TScan(self)\n\n # _data is the default member where the Macro class stores the data.\n # Assign the date produced by GScan (or its subclasses) to it so all\n # the Macro infrastructure related to the data works e.g. getter,\n # property, etc.\n self.setData(self._gScan.data)\n\n def run(self, *args):\n for step in self._gScan.step_scan():\n yield step\n\n def getTimeEstimation(self):\n mg_latency_time = self._gScan.measurement_group.getLatencyTime()\n latency_time = max(self.latency_time, mg_latency_time)\n return self.nb_points * (self.integ_time + latency_time)\n\n def getIntervalEstimation(self):\n return self.nr_interv\n\n def _get_nr_points(self):\n msg = (\"nr_points is deprecated since version 3.0.3. \"\n \"Use nb_points instead.\")\n self.warning(msg)\n return self.nb_points\n\n nr_points = property(_get_nr_points)\n\n\nclass scanstats(Macro):\n \"\"\"Calculate basic statistics of the enabled and plotted channels in\n the active measurement group for the last scan. If no channel is selected\n for plotting it fallbacks to the first enabled channel. Print stats and\n publish them in the env.\n The macro must be hooked in the post-scan hook place.\n \"\"\"\n\n env = (\"ActiveMntGrp\", )\n\n param_def = [\n [\"channel\",\n [[\"channel\", Type.ExpChannel, None, \"\"], {\"min\": 0}],\n None,\n \"List of channels for statistics calculations\"\n ]\n ]\n\n def run(self, channel):\n parent = self.getParentMacro()\n if not parent:\n self.warning(\"for now the scanstats macro can only be executed as\"\n \" a post-scan hook\")\n return\n if not hasattr(parent, \"motors\"):\n self.warning(\"scan must involve at least one moveable \"\n \"to calculate statistics\")\n return\n\n active_meas_grp = self.getEnv(\"ActiveMntGrp\")\n meas_grp = self.getMeasurementGroup(active_meas_grp)\n calc_channels = []\n enabled_channels = meas_grp.getEnabled()\n if channel:\n stat_channels = [chan.name for chan in channel]\n else:\n stat_channels = [key for key in enabled_channels.keys()]\n\n for chan in stat_channels:\n enabled = enabled_channels.get(chan)\n if enabled is None:\n self.warning(\"{} not in {}\".format(chan, meas_grp.name))\n else:\n if not enabled and channel:\n self.warning(\"{} not enabled\".format(chan))\n elif enabled and channel:\n # channel was given as parameters\n calc_channels.append(chan)\n elif enabled and meas_grp.getPlotType(chan)[chan] == 1:\n calc_channels.append(chan)\n\n if len(calc_channels) == 0:\n # fallback is first enabled channel in meas_grp\n calc_channels.append(next(iter(enabled_channels)))\n\n scalar_channels = []\n for _, chan in self.getExpChannels().items():\n if chan.type in (\"OneDExpChannel\", \"TwoDExpChannel\"):\n continue\n scalar_channels.append(chan.name)\n calc_channels = [ch for ch in calc_channels if ch in scalar_channels]\n\n if len(calc_channels) == 0:\n self.warning(\"measurement group must contain at least one \"\n \"enabled scalar channel to calculate statistics\")\n return\n\n selected_motor = str(parent.motors[0])\n stats = {}\n col_header = []\n cols = []\n\n motor_data = []\n channels_data = {}\n for channel_name in calc_channels:\n channels_data[channel_name] = []\n\n for idx, rc in parent.data.items():\n motor_data.append(rc[selected_motor])\n for channel_name in calc_channels:\n channels_data[channel_name].append(rc[channel_name])\n\n motor_data = numpy.array(motor_data)\n for channel_name, data in channels_data.items():\n channel_data = numpy.array(data)\n\n (_min, _max, min_at, max_at, half_max, com, mean, _int,\n fwhm, cen) = self._calcStats(motor_data, channel_data)\n stats[channel_name] = {\n \"min\": _min,\n \"max\": _max,\n \"minpos\": min_at,\n \"maxpos\": max_at,\n \"mean\": mean,\n \"int\": _int,\n \"com\": com,\n \"fwhm\": fwhm,\n \"cen\": cen}\n\n col_header.append([channel_name])\n cols.append([\n stats[channel_name][\"min\"],\n stats[channel_name][\"max\"],\n stats[channel_name][\"minpos\"],\n stats[channel_name][\"maxpos\"],\n stats[channel_name][\"mean\"],\n stats[channel_name][\"int\"],\n stats[channel_name][\"com\"],\n stats[channel_name][\"fwhm\"],\n stats[channel_name][\"cen\"],\n ])\n self.info(\"Statistics for movable: {:s}\".format(selected_motor))\n\n table = Table(elem_list=cols, elem_fmt=[\"%*g\"],\n row_head_str=[\"MIN\", \"MAX\", \"MIN@\", \"MAX@\",\n \"MEAN\", \"INT\", \"COM\", \"FWHM\", \"CEN\"],\n col_head_str=col_header, col_head_sep=\"-\")\n out = table.genOutput()\n\n for line in out:\n self.info(line)\n self.setEnv(\"{:s}.ScanStats\".format(self.getDoorName()),\n {\"Stats\": stats,\n \"Motor\": selected_motor,\n \"ScanID\": self.getEnv(\"ScanID\")})\n\n @staticmethod\n def _calcStats(x, y):\n # max and min\n _min = numpy.min(y)\n _max = numpy.max(y)\n\n min_idx = numpy.argmin(y)\n min_at = x[min_idx]\n max_idx = numpy.argmax(y)\n max_at = x[max_idx]\n\n # center of mass (com)\n try:\n com = numpy.sum(y*x)/numpy.sum(y)\n except ZeroDivisionError:\n com = 0\n\n mean = numpy.mean(y)\n _int = numpy.sum(y)\n\n # determine if it is a peak- or erf-like function\n half_max = (_max-_min)/2+_min\n\n lower_left = False\n lower_right = False\n\n if numpy.any(y[0:max_idx] < half_max):\n lower_left = True\n if numpy.any(y[max_idx:] < half_max):\n lower_right = True\n\n if lower_left and lower_right:\n # it is a peak-like function\n y_data = y\n elif lower_left:\n # it is an erf-like function\n # use the gradient for further calculation\n y_data = numpy.gradient(y)\n # use also the half maximum of the gradient\n half_max = (numpy.max(y_data)-numpy.min(y_data)) \\\n / 2+numpy.min(y_data)\n else:\n # it is an erf-like function\n # use the gradient for further calculation\n y_data = -1*numpy.gradient(y)\n # use also the half maximum of the gradient\n half_max = (numpy.max(y_data)-numpy.min(y_data)) \\\n / 2+numpy.min(y_data)\n\n # cen and fwhm\n # this part is adapted from:\n #\n # The PyMca X-Ray Fluorescence Toolkit\n #\n # Copyright (c) 2004-2014 European Synchrotron Radiation Facility\n #\n # This file is part of the PyMca X-ray Fluorescence Toolkit developed\n # at the ESRF by the Software group.\n\n max_idx_data = numpy.argmax(y_data)\n idx = max_idx_data\n try:\n while y_data[idx] >= half_max:\n idx = idx-1\n\n x0 = x[idx]\n x1 = x[idx+1]\n y0 = y_data[idx]\n y1 = y_data[idx+1]\n\n lhmx = (half_max*(x1-x0) - (y0*x1)+(y1*x0)) / (y1-y0)\n except ZeroDivisionError:\n lhmx = 0\n except IndexError:\n lhmx = x[0]\n\n idx = max_idx_data\n try:\n while y_data[idx] >= half_max:\n idx = idx+1\n\n x0 = x[idx-1]\n x1 = x[idx]\n y0 = y_data[idx-1]\n y1 = y_data[idx]\n\n uhmx = (half_max*(x1-x0) - (y0*x1)+(y1*x0)) / (y1-y0)\n except ZeroDivisionError:\n uhmx = 0\n except IndexError:\n uhmx = x[-1]\n\n fwhm = uhmx - lhmx\n cen = (uhmx + lhmx)/2\n\n return (_min, _max, min_at, max_at, half_max, com, mean, _int,\n fwhm, cen)\n", "#!/usr/bin/env python\n\n#\n#\n# This file is part of Sardana\n#\n# http://www.sardana-controls.org/\n#\n# Copyright 2017 CELLS / ALBA Synchrotron, Bellaterra, Spain\n#\n# Sardana is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Sardana is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with Sardana. If not, see <http://www.gnu.org/licenses/>.\n#\n#\n\n\n\"\"\"\nThis module provides a recorder for NXscans implemented with h5py (no nxs)\n\"\"\"\n\n__all__ = [\"NXscanH5_FileRecorder\"]\n\n__docformat__ = 'restructuredtext'\n\nimport os\nimport re\nimport posixpath\nfrom datetime import datetime\nimport numpy\nimport h5py\n\nfrom sardana.sardanautils import is_pure_str\nfrom sardana.taurus.core.tango.sardana import PlotType\nfrom sardana.macroserver.scan.recorder import BaseFileRecorder, SaveModes\nfrom sardana.macroserver.recorders.h5util import _h5_file_handler, \\\n _open_h5_file\n\n\nVDS_available = True\ntry:\n h5py.VirtualSource\nexcept AttributeError:\n VDS_available = False\n\n\ndef timedelta_total_seconds(timedelta):\n \"\"\"Equivalent to timedelta.total_seconds introduced with python 2.7.\"\"\"\n return (\n timedelta.microseconds + 0.0\n + (timedelta.seconds + timedelta.days * 24 * 3600)\n * 10 ** 6) / 10 ** 6\n\n\nclass NXscanH5_FileRecorder(BaseFileRecorder):\n\n \"\"\"\n Saves data to a nexus file that follows the NXscan application definition\n (This is a pure h5py implementation that does not depend on the nxs module)\n \"\"\"\n formats = {'h5': '.h5'}\n # from http://docs.h5py.org/en/latest/strings.html\n try:\n str_dt = h5py.string_dtype()\n except AttributeError:\n # h5py < 3\n str_dt = h5py.special_dtype(vlen=str) # Variable-length UTF-8\n byte_dt = h5py.special_dtype(vlen=bytes) # Variable-length UTF-8\n supported_dtypes = ('float32', 'float64', 'int8',\n 'int16', 'int32', 'int64', 'uint8',\n 'uint16', 'uint32',\n 'uint64', str_dt, byte_dt)\n _dataCompressionRank = -1\n\n def __init__(self, filename=None, macro=None, overwrite=False, **pars):\n BaseFileRecorder.__init__(self, **pars)\n\n self.macro = macro\n self.overwrite = overwrite\n if filename:\n self.setFileName(filename)\n\n self.currentlist = None\n self._nxclass_map = {}\n self.entryname = 'entry'\n\n scheme = r'([A-Za-z][A-Za-z0-9\\.\\+\\-]*)'\n authority = (r'//(?P<host>([\\w\\-_]+\\.)*[\\w\\-_]+)'\n + r'(:(?P<port>\\d{1,5}))?')\n path = (r'((?P<filepath>(/(//+)?([A-Za-z]:/)?([\\w.\\-_]+/)*'\n + r'[\\w.\\-_]+.(h5|hdf5|\\w+))))'\n + r'(::(?P<dataset>(([\\w.\\-_]+/)*[\\w.\\-_]+)))?')\n pattern = ('^(?P<scheme>%(scheme)s):'\n + '((?P<authority>%(authority)s)'\n + '($|(?=[/#?])))?(?P<path>%(path)s)$')\n self.pattern = pattern % dict(scheme=scheme, authority=authority,\n path=path)\n self._close = False\n\n def getFormat(self):\n return 'HDF5::NXscan'\n\n def setFileName(self, filename):\n if self.fd is not None:\n self.fd.close()\n self.filename = filename\n self.currentlist = None\n\n def sanitizeName(self, name):\n \"\"\"It returns a version of the given name that can be used as a python\n variable (and conforms to NeXus best-practices for dataset names)\n \"\"\"\n # make sure the name does not start with a digit\n if name[0].isdigit():\n name = \"_%s\" % name\n # substitute whitespaces by underscores and remove other\n # non-alphanumeric characters\n return \"\".join(\n x for x in name.replace(' ', '_') if x.isalnum() or x == '_')\n\n def _openFile(self, fname):\n \"\"\"Open the file with given filename (create if it does not exist)\n Populate the root of the file with some metadata from the NXroot\n definition\"\"\"\n try:\n fd = _h5_file_handler[fname]\n except KeyError:\n fd = _open_h5_file(fname)\n self._close = True\n try:\n fd.attrs['NX_class']\n except KeyError:\n fd.attrs['NX_class'] = 'NXroot'\n fd.attrs['file_name'] = fname\n fd.attrs['file_time'] = datetime.now().isoformat()\n fd.attrs['creator'] = self.__class__.__name__\n fd.attrs['HDF5_Version'] = h5py.version.hdf5_version\n fd.attrs['h5py_version'] = h5py.version.version\n return fd\n\n def _startRecordList(self, recordlist):\n\n if self.filename is None:\n return\n\n self.currentlist = recordlist\n env = self.currentlist.getEnviron()\n serialno = env['serialno']\n self._dataCompressionRank = env.get('DataCompressionRank',\n self._dataCompressionRank)\n\n # open/create the file and store its descriptor\n self.fd = self._openFile(self.filename)\n\n # create an entry for this scan using the scan serial number\n self.entryname = 'entry%d' % serialno\n try:\n nxentry = self.fd.create_group(self.entryname)\n except ValueError:\n # Warn and abort\n if self.entryname in list(self.fd.keys()):\n msg = ('{ename:s} already exists in {fname:s}. '\n 'Aborting macro to prevent data corruption.\\n'\n 'This is likely caused by a wrong ScanID\\n'\n 'Possible workarounds:\\n'\n ' * first, try re-running this macro (the ScanID '\n 'may be automatically corrected)\\n'\n ' * if not, try changing ScanID with senv, or...\\n'\n ' * change the file name ({ename:s} will be in both '\n 'files containing different data)\\n'\n '\\nPlease report this problem.'\n ).format(ename=self.entryname, fname=self.filename)\n raise RuntimeError(msg)\n else:\n raise\n nxentry.attrs['NX_class'] = 'NXentry'\n\n # adapt the datadesc to the NeXus requirements\n self.datadesc = []\n for dd in env['datadesc']:\n dd = dd.clone()\n dd.label = self.sanitizeName(dd.label)\n if not hasattr(dd, \"value_ref_enabled\"):\n dd.value_ref_enabled = False\n if dd.dtype == 'bool':\n dd.dtype = 'int8'\n self.debug('%r will be stored with type=%r', dd.name, dd.dtype)\n elif dd.dtype == 'str':\n dd.dtype = NXscanH5_FileRecorder.str_dt\n if dd.value_ref_enabled:\n # substitute original data (image or spectrum) type and shape\n # since we will receive references instead\n dd.dtype = NXscanH5_FileRecorder.str_dt\n dd.shape = tuple()\n self.debug('%r will be stored with type=%r', dd.name, dd.dtype)\n if dd.dtype in self.supported_dtypes:\n self.datadesc.append(dd)\n else:\n msg = '%r will not be stored. Reason: %r not supported'\n self.warning(msg, dd.name, dd.dtype)\n\n # make a dictionary out of env['instrumentlist']\n # (use fullnames -paths- as keys)\n self._nxclass_map = {}\n for inst in env.get('instrumentlist', []):\n self._nxclass_map[nxentry.name + inst.getFullName()] = inst.klass\n if self._nxclass_map is {}:\n self.warning('Missing information on NEXUS structure. '\n + 'Nexus Tree will not be created')\n\n self.debug('Starting new recording %d on file %s', serialno,\n self.filename)\n\n # populate the entry with some data\n nxentry.create_dataset('definition', data='NXscan')\n import sardana.release\n program_name = '%s (%s)' % (sardana.release.name,\n self.__class__.__name__)\n _pname = nxentry.create_dataset('program_name', data=program_name)\n _pname.attrs['version'] = sardana.release.version\n nxentry.create_dataset('start_time', data=env['starttime'].isoformat())\n timedelta = (env['starttime'] - datetime(1970, 1, 1))\n try:\n _epoch = timedelta.total_seconds()\n except AttributeError:\n # for python 2.6 compatibility\n _epoch = timedelta_total_seconds(timedelta)\n nxentry.attrs['epoch'] = _epoch\n nxentry.create_dataset('title', data=env['title'])\n nxentry.create_dataset('entry_identifier', data=str(env['serialno']))\n\n _usergrp = nxentry.create_group('user')\n _usergrp.attrs['NX_class'] = 'NXuser'\n _usergrp.create_dataset('name', data=env['user'])\n\n # prepare the 'measurement' group\n _meas = nxentry.create_group('measurement')\n _meas.attrs['NX_class'] = 'NXcollection'\n if self.savemode == SaveModes.Record:\n # create extensible datasets\n for dd in self.datadesc:\n shape = ([0] + list(dd.shape))\n _ds = _meas.create_dataset(\n dd.label,\n dtype=dd.dtype,\n shape=shape,\n maxshape=([None] + list(dd.shape)),\n chunks=(1,) + tuple(dd.shape),\n compression=self._compression(shape)\n )\n if hasattr(dd, 'data_units'):\n _ds.attrs['units'] = dd.data_units\n\n else:\n # leave the creation of the datasets to _writeRecordList\n # (when we actually know the length of the data to write)\n pass\n\n self._createPreScanSnapshot(env)\n self._populateInstrumentInfo()\n self._createNXData()\n self.fd.flush()\n\n def _compression(self, shape, compfilter='gzip'):\n \"\"\"\n Returns `compfilter` (the name of the compression filter) to use\n (or None if no compression is recommended), based on the given shape\n and the self._dataCompressionRank thresshold.\n By default, `compfilter` is set to `'gzip'`\n \"\"\"\n min_rank = self._dataCompressionRank\n if shape is None or min_rank < 0 or len(shape) < min_rank:\n compfilter = None\n elif len(shape) == 0:\n msg = \"%s compression is not supported for scalar datasets\"\\\n \" - these datasets will not be compressed\" % compfilter\n self.warning(msg)\n compfilter = None\n return compfilter\n\n def _createPreScanSnapshot(self, env):\n \"\"\"\n Write the pre-scan snapshot in \"<entry>/measurement/pre_scan_snapshot\".\n Also link to the snapshot datasets from the <entry>/measurement group\n \"\"\"\n _meas = self.fd[posixpath.join(self.entryname, 'measurement')]\n self.preScanSnapShot = env.get('preScanSnapShot', [])\n _snap = _meas.create_group('pre_scan_snapshot')\n _snap.attrs['NX_class'] = 'NXcollection'\n\n meas_keys = list(_meas.keys())\n\n for dd in self.preScanSnapShot:\n label = self.sanitizeName(dd.label)\n dtype = dd.dtype\n pre_scan_value = dd.pre_scan_value\n if dd.dtype == 'bool':\n dtype = 'int8'\n pre_scan_value = numpy.int8(dd.pre_scan_value)\n self.debug('Pre-scan snapshot of %s will be stored as type %s',\n dd.name, dtype)\n elif dd.dtype == 'str':\n dtype = NXscanH5_FileRecorder.str_dt\n dd.dtype = NXscanH5_FileRecorder.str_dt\n\n if dtype in self.supported_dtypes:\n _ds = _snap.create_dataset(\n label,\n data=pre_scan_value,\n compression=self._compression(dd.shape)\n )\n # link to this dataset also from the measurement group\n if label not in meas_keys:\n _meas[label] = _ds\n else:\n self.warning(('Pre-scan snapshot of %s will not be stored. '\n + 'Reason: type %s not supported'),\n dd.name, dtype)\n\n def _writeRecord(self, record):\n if self.filename is None:\n return\n _meas = self.fd[posixpath.join(self.entryname, 'measurement')]\n\n for dd in self.datadesc:\n if dd.name in record.data:\n data = record.data[dd.name]\n _ds = _meas[dd.label]\n if data is None:\n data = numpy.zeros(dd.shape, dtype=dd.dtype)\n # skip NaN if value reference is enabled\n if dd.value_ref_enabled and not is_pure_str(data):\n continue\n elif not hasattr(data, 'shape'):\n data = numpy.array([data], dtype=dd.dtype)\n elif dd.dtype != data.dtype.name:\n self.debug('%s casted to %s (was %s)',\n dd.label, dd.dtype, data.dtype.name)\n data = data.astype(dd.dtype)\n\n # resize the dataset and add the latest chunk\n if _ds.shape[0] <= record.recordno:\n _ds.resize(record.recordno + 1, axis=0)\n\n # write the slab of data\n _ds[record.recordno, ...] = data\n\n else:\n self.debug('missing data for label %r', dd.label)\n self.fd.flush()\n\n def _endRecordList(self, recordlist):\n\n if self.filename is None:\n return\n\n env = self.currentlist.getEnviron()\n nxentry = self.fd[self.entryname]\n\n for dd, dd_env in zip(self.datadesc, env[\"datadesc\"]):\n label = dd.label\n\n # If h5file scheme is used: Creation of a Virtual Dataset\n if dd.value_ref_enabled:\n measurement = nxentry['measurement']\n try:\n dataset = measurement[label].asstr()\n except AttributeError:\n # h5py < 3\n dataset = measurement[label]\n first_reference = dataset[0]\n group = re.match(self.pattern, first_reference)\n if group is None:\n msg = 'Unsupported reference %s' % first_reference\n self.warning(msg)\n continue\n\n uri_groups = group.groupdict()\n if uri_groups['scheme'] != \"h5file\":\n continue\n if not VDS_available:\n msg = (\"VDS not available in this version of h5py, \"\n \"{0} will be stored as string reference\")\n msg.format(label)\n self.warning(msg)\n continue\n\n bk_label = \"_\" + label\n measurement[bk_label] = measurement[label]\n nb_points = measurement[label].size\n\n (dim_1, dim_2) = dd_env.shape\n layout = h5py.VirtualLayout(shape=(nb_points, dim_1, dim_2),\n dtype=dd_env.dtype)\n\n for i in range(nb_points):\n reference = dataset[i]\n group = re.match(self.pattern, reference)\n if group is None:\n msg = 'Unsupported reference %s' % first_reference\n self.warning(msg)\n continue\n uri_groups = group.groupdict()\n filename = uri_groups[\"filepath\"]\n remote_dataset_name = uri_groups[\"dataset\"]\n if remote_dataset_name is None:\n remote_dataset_name = \"dataset\"\n vsource = h5py.VirtualSource(filename, remote_dataset_name,\n shape=(dim_1, dim_2))\n layout[i] = vsource\n\n # Substitute dataset by Virtual Dataset in output file\n try:\n del measurement[label]\n measurement.create_virtual_dataset(\n label, layout, fillvalue=-numpy.inf)\n except Exception as e:\n msg = 'Could not create a Virtual Dataset. Reason: %r'\n self.warning(msg, e)\n else:\n del measurement[bk_label]\n\n nxentry.create_dataset('end_time', data=env['endtime'].isoformat())\n self.fd.flush()\n self.debug('Finishing recording %d on file %s:',\n env['serialno'], self.filename)\n if self._close:\n self.fd.close()\n self.currentlist = None\n\n def writeRecordList(self, recordlist):\n \"\"\"Called when in BLOCK writing mode\"\"\"\n self._startRecordList(recordlist)\n _meas = self.fd[posixpath.join(self.entryname, 'measurement')]\n for dd in self.datadesc:\n shape = ([len(recordlist.records)] + list(dd.shape))\n _ds = _meas.create_dataset(\n dd.label,\n dtype=dd.dtype,\n shape=shape,\n chunks=(1,) + tuple(dd.shape),\n compression=self._compression(shape)\n )\n if hasattr(dd, 'data_units'):\n _ds.attrs['units'] = dd.data_units\n\n for record in recordlist.records:\n if dd.label in record.data:\n _ds[record.recordno, ...] = record.data[dd.label]\n else:\n self.debug('missing data for label %r in record %i',\n dd.label, record.recordno)\n self._endRecordList(recordlist)\n\n def _populateInstrumentInfo(self):\n nxentry = self.fd[self.entryname]\n _meas = nxentry['measurement']\n _snap = _meas['pre_scan_snapshot']\n # create a link for each\n for dd in self.datadesc:\n # we only link if the instrument info is available\n if getattr(dd, 'instrument', None):\n try:\n _ds = _meas[dd.label]\n _instr = self._createNXpath(dd.instrument,\n prefix=nxentry.name)\n _instr[os.path.basename(_ds.name)] = _ds\n except Exception as e:\n msg = 'Could not create link to %r in %r. Reason: %r'\n self.warning(msg, dd.label, dd.instrument, e)\n\n for dd in self.preScanSnapShot:\n if getattr(dd, 'instrument', None):\n label = self.sanitizeName(dd.label)\n try:\n _ds = _snap[label]\n _instr = self._createNXpath(dd.instrument,\n prefix=nxentry.name)\n _instr[os.path.basename(_ds.name)] = _ds\n except Exception as e:\n msg = 'Could not create link to %r in %r. Reason: %r'\n self.warning(msg, label, dd.instrument, e)\n\n def _createNXData(self):\n \"\"\"\n Creates groups of type NXdata by making links to the corresponding\n datasets\n \"\"\"\n # classify by type of plot:\n plots1d = {}\n plots1d_names = {}\n i = 1\n for dd in self.datadesc:\n ptype = getattr(dd, 'plot_type', PlotType.No)\n if ptype == PlotType.No:\n continue\n elif ptype == PlotType.Spectrum:\n # converting the list into a colon-separated string\n axes = ':'.join(dd.plot_axes)\n if axes in plots1d:\n plots1d[axes].append(dd)\n else:\n plots1d[axes] = [dd]\n # Note that datatesc ordering determines group name\n # indexing\n plots1d_names[axes] = 'plot_%i' % i\n i += 1\n else:\n continue # TODO: implement support for images and other\n\n nxentry = self.fd[self.entryname]\n _meas = nxentry['measurement']\n\n # write the 1D NXdata group\n for axes, v in list(plots1d.items()):\n _nxdata = nxentry.create_group(plots1d_names[axes])\n _nxdata.attrs['NX_class'] = 'NXdata'\n\n # write the signals\n for i, dd in enumerate(v):\n # link the datasets\n _ds = _nxdata[dd.label] = _meas[dd.label]\n # add attrs\n _ds.attrs['signal'] = min(i + 1, 2)\n _ds.attrs['axes'] = axes\n _ds.attrs['interpretation'] = 'spectrum'\n # write the axes\n for axis in axes.split(':'):\n try:\n _nxdata[axis] = _meas[axis]\n except Exception:\n self.warning('cannot create link for \"%s\". Skipping', axis)\n\n def _createNXpath(self, path, prefix=None):\n \"\"\"\n Creates a path in the nexus file composed by nested data_groups\n with their corresponding NXclass attributes.\n\n This method creates the groups if they do not exist. If the\n path is given using `name:nxclass` notation, the given nxclass is\n used.\n Otherwise, the class name is obtained from self._nxclass_map values\n (and if not found, it defaults to NXcollection).\n\n It returns the tip of the branch (the last group created)\n \"\"\"\n\n if prefix is None:\n # if prefix is None, use current entry if path is relative\n path = posixpath.join(\"/%s:NXentry\" % self.entryname, path)\n else:\n # if prefix is given explicitly, assume that path is relative to it\n # even if path is absolute\n path = posixpath.join(prefix, path.lstrip('/'))\n\n grp = self.fd['/']\n for name in path[1:].split('/'):\n if ':' in name:\n name, nxclass = name.split(':')\n else:\n nxclass = None\n # open group (create if it does not exist)\n grp = grp.require_group(name)\n if 'NX_class' not in grp.attrs:\n if nxclass is None:\n nxclass = self._nxclass_map.get(grp.name, 'NXcollection')\n grp.attrs['NX_class'] = nxclass\n return grp\n\n def _addCustomData(self, value, name, nxpath=None, dtype=None, **kwargs):\n \"\"\"\n Apart from value and name, this recorder can use the following optional\n parameters:\n\n :param nxpath: (str) a nexus path (optionally using name:nxclass\n notation for the group names). See the rules for\n automatic nxclass resolution used by\n :meth:`._createNXpath`. If None given, it defaults to\n nxpath='custom_data:NXcollection'\n\n :param dtype: name of data type (it is inferred from value if not\n given)\n \"\"\"\n if nxpath is None:\n nxpath = 'custom_data:NXcollection'\n if dtype is None:\n if numpy.isscalar(value):\n dtype = numpy.dtype(type(value)).name\n if numpy.issubdtype(dtype, str):\n dtype = NXscanH5_FileRecorder.str_dt\n if dtype == 'bool':\n value, dtype = int(value), 'int8'\n else:\n value = numpy.array(value)\n dtype = value.dtype.name\n\n if dtype not in self.supported_dtypes and dtype != 'char':\n self.warning(\n 'cannot write %r. Reason: unsupported data type', name)\n return\n\n # open the file if necessary\n fileClosed = self.fd is None or not hasattr(self.fd, 'mode')\n if fileClosed:\n self.fd = self._openFile(self.filename)\n\n # create the custom data group if it does not exist\n grp = self._createNXpath(nxpath)\n try:\n grp.create_dataset(name, data=value)\n except ValueError as e:\n msg = 'Error writing %s. Reason: %s' % (name, e)\n self.warning(msg)\n self.macro.warning(msg)\n\n # flush\n self.fd.flush()\n\n # leave the file as it was\n if fileClosed:\n self.fd.close()\n" ]
[ [ "numpy.linspace", "numpy.min", "numpy.gradient", "numpy.ones", "numpy.max", "numpy.argmax", "numpy.argmin", "numpy.mean", "numpy.any", "numpy.array", "numpy.sum" ], [ "numpy.issubdtype", "numpy.int8", "numpy.isscalar", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
rdarie/kCSD-python
[ "4dd0015e9c5598e7eceeeb25668e696e495b2026" ]
[ "figures/kCSD_properties/targeted_basis.py" ]
[ "\"\"\"\n@author: mkowalska\n\"\"\"\nimport os\nfrom os.path import expanduser\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime\nimport time\n\nfrom kcsd import ValidateKCSD, ValidateKCSD1D, SpectralStructure, KCSD1D\n\n__abs_file__ = os.path.abspath(__file__)\nhome = expanduser('~')\nDAY = datetime.datetime.now()\nDAY = DAY.strftime('%Y%m%d')\nTIMESTR = time.strftime(\"%H%M%S\")\nSAVE_PATH = home + \"/kCSD_results/\" + DAY + '/' + TIMESTR\n\n\ndef makemydir(directory):\n \"\"\"\n Creates a new folder if it doesn't exist\n\n Parameters\n ----------\n directory: string\n directory\n\n Returns\n -------\n None\n \"\"\"\n try:\n os.makedirs(directory)\n except OSError:\n pass\n os.chdir(directory)\n\n\ndef save_source_code(save_path, timestr):\n \"\"\"\n Saves the source code.\n\n Parameters\n ----------\n save_path: string\n directory\n timestr: float\n\n Returns\n -------\n None\n \"\"\"\n with open(save_path + '/source_code_' + str(timestr), 'w') as sf:\n sf.write(open(__file__).read())\n\n\ndef csd_profile(x, seed):\n '''Function used for adding multiple 1D gaussians.\n\n Parameters\n ----------\n x: numpy array\n x coordinates of true source profile.\n seed: list [r, mu]\n\n Returns\n -------\n gauss: numpy array\n Gaussian profile for given R and M.\n '''\n r = seed[0]\n mu = seed[1]\n STDDEV = r/3.0\n gauss = (np.exp(-((x - mu)**2)/(2 * STDDEV**2)) /\n (np.sqrt(2 * np.pi) * STDDEV)**1)\n gauss /= np.max(gauss)\n return gauss\n\n\ndef targeted_basis(val, csd_at, true_csd, ele_pos, pots, n_src, R, MU,\n true_csd_xlims, ele_lims, title, h=0.25, sigma=0.3,\n csd_res=100, method='cross-validation', Rs=None,\n lambdas=None):\n '''\n Function investigating kCSD analysis for targeted bases.\n\n Parameters\n ----------\n val: object of the class ValidateKCSD.\n csd_at: numpy array\n Coordinates of ground truth data.\n true_csd: numpy array\n Values of ground truth data (true_csd).\n ele_pos: numpy array\n Locations of electrodes.\n pots: numpy array\n Potentials measured (calculated) on electrodes.\n n_src: int\n Number of basis sources.\n R: float\n Thickness of the groundtruth source.\n MU: float\n x coordinate of maximum ampliude of groundtruth source.\n true_csd_xlims: list\n Boundaries for ground truth space.\n ele_lims: list\n Boundaries for electrodes placement.\n title: string\n Name of the figure that is to be saved\n h: float\n Thickness of analyzed cylindrical slice.\n Default: 0.25.\n sigma: float\n Space conductance of the medium.\n Default: 0.3.\n csd_res: int\n Resolution of ground truth.\n Default: 100.\n method: string\n Determines the method of regularization.\n Default: cross-validation.\n Rs: numpy 1D array\n Basis source parameter for crossvalidation.\n Default: None.\n lambdas: numpy 1D array\n Regularization parameter for crossvalidation.\n Default: None.\n\n Returns\n -------\n obj: object of the class KCSD1D\n k: object of the class ValidateKCSD1D\n '''\n k = ValidateKCSD1D(1, n_src_init=n_src, R_init=0.23,\n ele_lims=ele_lims, est_xres=0.01,\n true_csd_xlims=true_csd_xlims, sigma=sigma, h=h,\n src_type='gauss')\n obj, est_csd = k.do_kcsd(pots, ele_pos, method=method, Rs=Rs,\n lambdas=lambdas)\n test_csd = csd_profile(obj.estm_x, [R, MU])\n rms = val.calculate_rms(test_csd, est_csd)\n titl = \"Lambda: %0.2E; R: %0.2f; RMS_Error: %0.2E;\" % (obj.lambd, obj.R,\n rms)\n fig = k.make_plot(csd_at, true_csd, obj, est_csd, ele_pos, pots, titl)\n save_as = (SAVE_PATH)\n fig.savefig(os.path.join(SAVE_PATH, save_as + '/' + title + '.png'))\n plt.close()\n return obj, k\n\n\ndef simulate_data(csd_profile, true_csd_xlims, R, MU, total_ele, ele_lims,\n h=0.25, sigma=0.3, csd_res=100, noise=0):\n '''\n Generates groundtruth profiles and interpolates potentials.\n\n Parameters\n ----------\n csd_profile: function\n Function to produce csd profile.\n true_csd_xlims: list\n Boundaries for ground truth space.\n R: float\n Thickness of the groundtruth source.\n MU: float\n x coordinate of maximum ampliude of groundtruth source.\n total_ele: int\n Number of electrodes.\n ele_lims: list\n Boundaries for electrodes placement.\n h: float\n Thickness of analyzed cylindrical slice.\n Default: 0.25.\n sigma: float\n Space conductance of the medium.\n Default: 0.3.\n csd_res: int\n Resolution of ground truth.\n Default: 100.\n noise: float\n Determines the level of noise in the data.\n Default: 0.\n\n Returns\n -------\n csd_at: numpy array\n Coordinates of ground truth data.\n true_csd: numpy array\n Values of ground truth data (true_csd).\n ele_pos: numpy array\n Locations of electrodes.\n pots: numpy array\n Potentials measured (calculated) on electrodes.\n val: object of the class ValidateKCSD\n '''\n val = ValidateKCSD(1)\n csd_at = np.linspace(true_csd_xlims[0], true_csd_xlims[1], csd_res)\n true_csd = csd_profile(csd_at, [R, MU])\n ele_pos = val.generate_electrodes(total_ele=total_ele, ele_lims=ele_lims)\n pots = val.calculate_potential(true_csd, csd_at, ele_pos, h, sigma)\n if noise is not None:\n pots = val.add_noise(pots, 10, level=noise)\n return csd_at, true_csd, ele_pos, pots, val\n\n\ndef structure_investigation(csd_profile, true_csd_xlims, n_src, R, MU,\n total_ele, ele_lims, title, h=0.25, sigma=0.3,\n csd_res=100, method='cross-validation', Rs=None,\n lambdas=None, noise=0):\n '''\n .\n\n Parameters\n ----------\n csd_profile: function\n Function to produce csd profile.\n true_csd_xlims: list\n Boundaries for ground truth space.\n n_src: int\n Number of basis sources.\n R: float\n Thickness of the groundtruth source.\n MU: float\n x coordinate of maximum ampliude of groundtruth source.\n total_ele: int\n Number of electrodes.\n ele_lims: list\n Boundaries for electrodes placement.\n title: string\n Name of the figure that is to be saved\n h: float\n Thickness of analyzed cylindrical slice.\n Default: 0.25.\n sigma: float\n Space conductance of the medium.\n Default: 0.3.\n csd_res: int\n Resolution of ground truth.\n Default: 100.\n method: string\n Determines the method of regularization.\n Default: cross-validation.\n Rs: numpy 1D array\n Basis source parameter for crossvalidation.\n Default: None.\n lambdas: numpy 1D array\n Regularization parameter for crossvalidation.\n Default: None.\n noise: float\n Determines the level of noise in the data.\n Default: 0.\n\n Returns\n -------\n obj: object of the class KCSD1D\n '''\n val = ValidateKCSD(1)\n csd_at, true_csd, ele_pos, pots, val = simulate_data(csd_profile,\n true_csd_xlims, R, MU,\n total_ele, ele_lims,\n h=h, sigma=sigma,\n noise=noise)\n obj, k = targeted_basis(val, csd_at, true_csd, ele_pos, pots, n_src, R, MU,\n true_csd_xlims, ele_lims, title, h=0.25,\n sigma=0.3, csd_res=100, method=method, Rs=Rs,\n lambdas=lambdas)\n return obj\n\n\ndef plot_eigenvalues(eigenvalues, save_path, title):\n '''\n Creates plot of eigenvalues of kernel matrix (k_pot).\n\n Parameters\n ----------\n eigenvalues: numpy array\n Eigenvalues of k_pot matrix.\n save_path: string\n Directory.\n title: string\n Title of the plot.\n\n Returns\n -------\n None\n '''\n fig = plt.figure()\n plt.plot(eigenvalues, '--', marker='.')\n plt.title('Eigenvalue decomposition of kernel matrix. ele_lims=basis_lims')\n plt.xlabel('Number of components')\n plt.ylabel('Eigenvalues')\n plt.show()\n save_as = (save_path + '/eigenvalues_for_' + title)\n fig.savefig(os.path.join(save_path, save_as+'.png'))\n plt.close()\n\n\ndef plot_eigenvectors(eigenvectors, save_path, title):\n \"\"\"\n Creates plot of eigenvectors of kernel matrix (k_pot).\n\n Parameters\n ----------\n eigenvectors: numpy array\n Eigenvectors of k_pot matrix.\n save_path: string\n Directory.\n title: string\n Title of the plot.\n\n Returns\n -------\n None\n \"\"\"\n fig = plt.figure(figsize=(15, 15))\n plt.suptitle('Eigenvalue decomposition of kernel matrix for different '\n 'number of basis sources')\n for i in range(eigenvectors.shape[1]):\n plt.subplot(int(eigenvectors.shape[1]/2) + 1, 2, i + 1)\n plt.plot(eigenvectors[:, i].T, '--', marker='.')\n plt.ylabel('Eigenvectors')\n plt.title(r'$v_' + str(i + 1) + '$')\n plt.xlabel('Number of components')\n plt.tight_layout()\n plt.show()\n save_as = (save_path + '/eigenvectors_for_' + title)\n fig.savefig(os.path.join(save_path, save_as+'.png'))\n plt.close()\n\n\ndef modified_bases(val, pots, ele_pos, n_src, title=None, h=0.25, sigma=0.3,\n gdx=0.01, ext_x=0, xmin=0, xmax=1, R=0.2, MU=0.25,\n method='cross-validation', Rs=None, lambdas=None):\n '''\n Parameters\n ----------\n val: object of the class ValidateKCSD1D\n pots: numpy array\n Potentials measured (calculated) on electrodes.\n ele_pos: numpy array\n Locations of electrodes.\n n_src: int\n Number of basis sources.\n title: string\n Title of the plot.\n h: float\n Thickness of analyzed cylindrical slice.\n Default: 0.25.\n sigma: float\n Space conductance of the medium.\n Default: 0.3.\n gdx: float\n Space increments in the estimation space.\n Default: 0.035.\n ext_x: float\n Length of space extension: xmin-ext_x ... xmax+ext_x.\n Default: 0.\n xmin: float\n Boundaries for CSD estimation space.\n xmax: float\n boundaries for CSD estimation space.\n R: float\n Thickness of the groundtruth source.\n Default: 0.2.\n MU: float\n Central position of Gaussian source\n Default: 0.25.\n method: string\n Determines the method of regularization.\n Default: cross-validation.\n Rs: numpy 1D array\n Basis source parameter for crossvalidation.\n Default: None.\n lambdas: numpy 1D array\n Regularization parameter for crossvalidation.\n Default: None.\n\n Returns\n -------\n obj_m: object of the class KCSD1D\n '''\n pots = pots.reshape((len(ele_pos), 1))\n obj_m = KCSD1D(ele_pos, pots, src_type='gauss', sigma=sigma, h=h, gdx=gdx,\n n_src_init=n_src, ext_x=ext_x, xmin=xmin, xmax=xmax)\n if method == 'cross-validation':\n obj_m.cross_validate(Rs=Rs, lambdas=lambdas)\n elif method == 'L-curve':\n obj_m.L_curve(Rs=Rs, lambdas=lambdas)\n est_csd = obj_m.values('CSD')\n test_csd = csd_profile(obj_m.estm_x, [R, MU])\n rms = val.calculate_rms(test_csd, est_csd)\n# titl = \"Lambda: %0.2E; R: %0.2f; RMS_Error: %0.2E;\" % (obj_m.lambd,\n# obj_m.R, rms)\n# fig = k.make_plot(csd_at, true_csd, obj_m, est_csd, ele_pos, pots, titl)\n# save_as = (SAVE_PATH)\n# fig.savefig(os.path.join(SAVE_PATH, save_as + '/' + title + '.png'))\n# plt.close()\n# ss = SpectralStructure(obj_m)\n# eigenvectors, eigenvalues = ss.evd()\n return obj_m\n\n\ndef plot_k_interp_cross_v(k_icross, eigenvectors, save_path, title):\n \"\"\"\n Creates plot of product of cross kernel vectors and eigenvectors for\n different number of basis sources\n\n Parameters\n ----------\n k_icross: numpy array\n List of cross kernel matrixes for different number of basis sources.\n eigenvectors: numpy array\n Eigenvectors of k_pot matrix.\n save_path: string\n Directory.\n title: string\n Name of the figure that is to be saved.\n\n Returns\n -------\n None\n \"\"\"\n fig = plt.figure(figsize=(15, 15))\n for i in range(eigenvectors.shape[0]):\n plt.subplot(int(k_icross.shape[1]/2) + 1, 2, i + 1)\n plt.plot(np.dot(k_icross, eigenvectors[:, i]), '--',\n marker='.')\n plt.title(r'$\\tilde{K}*v_' + str(i + 1) + '$')\n# plt.ylabel('Product K~V')\n plt.xlabel('Number of estimation points')\n fig.tight_layout()\n plt.show()\n save_path = save_path + '/cross_kernel'\n makemydir(save_path)\n save_as = (save_path + '/cross_kernel_eigenvector_product' + title)\n fig.savefig(os.path.join(save_path, save_as+'.png'))\n plt.close()\n\n\nif __name__ == '__main__':\n makemydir(SAVE_PATH)\n save_source_code(SAVE_PATH, time.strftime(\"%Y%m%d-%H%M%S\"))\n\n CSD_SEED = 15\n N_SRC = 64\n ELE_LIMS = [0, 1.] # range of electrodes space\n TRUE_CSD_XLIMS = [0., 1.]\n TOTAL_ELE = 12\n noise = 0\n method = 'cross-validation'\n Rs = None\n lambdas = None\n\n # A\n R = 0.2\n MU = 0.25\n csd_at, true_csd, ele_pos, pots, val = simulate_data(csd_profile,\n TRUE_CSD_XLIMS, R, MU,\n TOTAL_ELE, ELE_LIMS,\n noise=noise)\n title = 'A_basis_lims_0_1'\n obj, k = targeted_basis(val, csd_at, true_csd, ele_pos, pots, N_SRC, R, MU,\n TRUE_CSD_XLIMS, ELE_LIMS, title, method=method, Rs=Rs,\n lambdas=lambdas)\n ss = SpectralStructure(obj)\n eigenvectors, eigenvalues = ss.evd()\n plot_eigenvalues(eigenvalues, SAVE_PATH, title)\n plot_eigenvectors(eigenvectors, SAVE_PATH, title)\n plot_k_interp_cross_v(obj.k_interp_cross, eigenvectors, SAVE_PATH, title)\n\n # A.2\n title = 'A_basis_lims_0_0_5'\n modified_bases(val, pots, ele_pos, N_SRC, title, h=0.25, sigma=0.3,\n gdx=0.01, ext_x=0, xmin=0, xmax=0.5, method=method, Rs=Rs,\n lambdas=lambdas)\n\n # A.2.b\n title = 'A_basis_lims_0_0_5_less_sources'\n modified_bases(val, pots, ele_pos, N_SRC/2, title, h=0.25, sigma=0.3,\n gdx=0.01, ext_x=0, xmin=0, xmax=0.5, method=method, Rs=Rs,\n lambdas=lambdas)\n\n # B\n TRUE_CSD_XLIMS = [0., 1.5]\n R = 0.2\n MU = 1.25\n csd_at, true_csd, ele_pos, pots, val = simulate_data(csd_profile,\n TRUE_CSD_XLIMS, R, MU,\n TOTAL_ELE, ELE_LIMS,\n noise=noise)\n title = 'B_basis_lims_0_1'\n obj, k = targeted_basis(val, csd_at, true_csd, ele_pos, pots, N_SRC, R, MU,\n TRUE_CSD_XLIMS, ELE_LIMS, title, method=method, Rs=Rs,\n lambdas=lambdas)\n ss = SpectralStructure(obj)\n eigenvectors, eigenvalues = ss.evd()\n plot_eigenvalues(eigenvalues, SAVE_PATH, title)\n plot_eigenvectors(eigenvectors, SAVE_PATH, title)\n plot_k_interp_cross_v(obj.k_interp_cross, eigenvectors, SAVE_PATH, title)\n\n # B.2\n title = 'B_basis_lims_1_1_5'\n modified_bases(val, pots, ele_pos, N_SRC, title, h=0.25, sigma=0.3,\n gdx=0.01, ext_x=0, xmin=1, xmax=1.5, method=method, Rs=Rs,\n lambdas=lambdas)\n\n # B.2.b\n title = 'B_basis_lims_1_1_5_less_sources'\n modified_bases(val, pots, ele_pos, N_SRC/2, title, h=0.25, sigma=0.3,\n gdx=0.01, ext_x=0, xmin=1, xmax=1.5, method=method, Rs=Rs,\n lambdas=lambdas)\n\n # B.3\n title = 'B_basis_lims_0_1_5'\n modified_bases(val, pots, ele_pos, N_SRC, title, h=0.25, sigma=0.3,\n gdx=0.01, ext_x=0, xmin=0, xmax=1.5, method=method, Rs=Rs,\n lambdas=lambdas)\n" ]
[ [ "numpy.dot", "matplotlib.pyplot.tight_layout", "numpy.sqrt", "numpy.linspace", "matplotlib.pyplot.title", "matplotlib.pyplot.plot", "numpy.max", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.close", "numpy.exp", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.suptitle", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
chanyh0/PyTorch-StudioGAN
[ "5a912affc1ec975d97a33a12d1c96d05d4b883f0", "5a912affc1ec975d97a33a12d1c96d05d4b883f0", "5a912affc1ec975d97a33a12d1c96d05d4b883f0", "5a912affc1ec975d97a33a12d1c96d05d4b883f0" ]
[ "src/train_eval.py", "src/train_eval_impgd.py", "src/models/resnet.py", "src/metrics/Accuracy.py" ]
[ "# PyTorch StudioGAN: https://github.com/POSTECH-CVLab/PyTorch-StudioGAN\n# The MIT License (MIT)\n# See license file or visit https://github.com/POSTECH-CVLab/PyTorch-StudioGAN for details\n\n# train_eval.py\n\n\nimport numpy as np\nimport sys\nimport glob\nfrom scipy import ndimage\nfrom os.path import join\nfrom PIL import Image\nfrom tqdm import tqdm\nfrom datetime import datetime\n\nfrom metrics.IS import calculate_incep_score\nfrom metrics.FID import calculate_fid_score\nfrom metrics.F_beta import calculate_f_beta_score\nfrom metrics.Accuracy import calculate_accuracy\nfrom utils.ada import augment\nfrom utils.biggan_utils import interp\nfrom utils.sample import sample_latents, sample_1hot, make_mask, target_class_sampler\nfrom utils.misc import *\nfrom utils.losses import calc_derv4gp, calc_derv4dra, calc_derv, latent_optimise\nfrom utils.losses import Conditional_Contrastive_loss, Proxy_NCA_loss, NT_Xent_loss\nfrom utils.diff_aug import DiffAugment\nfrom utils.cr_diff_aug import CR_DiffAug\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import DataParallel\nimport torch.nn.functional as F\nimport torchvision\nfrom torchvision import transforms\n\n\nSAVE_FORMAT = 'step={step:0>3}-Inception_mean={Inception_mean:<.4}-Inception_std={Inception_std:<.4}-FID={FID:<.5}.pth'\n\nLOG_FORMAT = (\n \"Step: {step:>7} \"\n \"Progress: {progress:<.1%} \"\n \"Elapsed: {elapsed} \"\n \"temperature: {temperature:<.6} \"\n \"ada_p: {ada_p:<.6} \"\n \"Discriminator_loss: {dis_loss:<.6} \"\n \"Generator_loss: {gen_loss:<.6} \"\n)\n\n\ndef set_temperature(conditional_strategy, tempering_type, start_temperature, end_temperature, step_count, tempering_step, total_step):\n if conditional_strategy == 'ContraGAN':\n if tempering_type == 'continuous':\n t = start_temperature + step_count*(end_temperature - start_temperature)/total_step\n elif tempering_type == 'discrete':\n tempering_interval = total_step//(tempering_step + 1)\n t = start_temperature + \\\n (step_count//tempering_interval)*(end_temperature-start_temperature)/tempering_step\n else:\n t = start_temperature\n else:\n t = 'no'\n return t\n\n\nclass Train_Eval(object):\n def __init__(self, run_name, best_step, dataset_name, eval_type, logger, writer, n_gpus, gen_model, dis_model, inception_model,\n Gen_copy, Gen_ema, train_dataset, eval_dataset, train_dataloader, eval_dataloader, freeze_layers, conditional_strategy,\n pos_collected_numerator, z_dim, num_classes, hypersphere_dim, d_spectral_norm, g_spectral_norm, G_optimizer, D_optimizer,\n batch_size, g_steps_per_iter, d_steps_per_iter, accumulation_steps, total_step, G_loss, D_loss, contrastive_lambda, margin,\n tempering_type, tempering_step, start_temperature, end_temperature, weight_clipping_for_dis, weight_clipping_bound,\n gradient_penalty_for_dis, gradient_penalty_lambda, deep_regret_analysis_for_dis, regret_penalty_lambda, cr, cr_lambda, bcr,\n real_lambda, fake_lambda, zcr, gen_lambda, dis_lambda, sigma_noise, diff_aug, ada, prev_ada_p, ada_target, ada_length, prior,\n truncated_factor, ema, latent_op, latent_op_rate, latent_op_step, latent_op_step4eval, latent_op_alpha, latent_op_beta,\n latent_norm_reg_weight, default_device, print_every, save_every, checkpoint_dir, evaluate, mu, sigma, best_fid,\n best_fid_checkpoint_path, mixed_precision, train_config, model_config, gamma, steps):\n\n self.run_name = run_name\n self.best_step = best_step\n self.dataset_name = dataset_name\n self.eval_type = eval_type\n self.logger = logger\n self.writer = writer\n self.n_gpus = n_gpus\n\n self.gen_model = gen_model\n self.dis_model = dis_model\n self.inception_model = inception_model\n self.Gen_copy = Gen_copy\n self.Gen_ema = Gen_ema\n\n self.train_dataset = train_dataset\n self.eval_dataset = eval_dataset\n self.train_dataloader = train_dataloader\n self.eval_dataloader = eval_dataloader\n\n self.freeze_layers = freeze_layers\n\n self.conditional_strategy = conditional_strategy\n self.pos_collected_numerator = pos_collected_numerator\n self.z_dim = z_dim\n self.num_classes = num_classes\n self.hypersphere_dim = hypersphere_dim\n self.d_spectral_norm = d_spectral_norm\n self.g_spectral_norm = g_spectral_norm\n\n self.G_optimizer = G_optimizer\n self.D_optimizer = D_optimizer\n self.batch_size = batch_size\n self.g_steps_per_iter = g_steps_per_iter\n self.d_steps_per_iter = d_steps_per_iter\n self.accumulation_steps = accumulation_steps\n self.total_step = total_step\n\n self.G_loss = G_loss\n self.D_loss = D_loss\n self.contrastive_lambda = contrastive_lambda\n self.margin = margin\n self.tempering_type = tempering_type\n self.tempering_step = tempering_step\n self.start_temperature = start_temperature\n self.end_temperature = end_temperature\n self.weight_clipping_for_dis = weight_clipping_for_dis\n self.weight_clipping_bound = weight_clipping_bound\n self.gradient_penalty_for_dis = gradient_penalty_for_dis\n self.gradient_penalty_lambda = gradient_penalty_lambda\n self.deep_regret_analysis_for_dis = deep_regret_analysis_for_dis\n self.regret_penalty_lambda = regret_penalty_lambda\n self.cr = cr\n self.cr_lambda = cr_lambda\n self.bcr = bcr\n self.real_lambda = real_lambda\n self.fake_lambda = fake_lambda\n self.zcr = zcr\n self.gen_lambda = gen_lambda\n self.dis_lambda = dis_lambda\n self.sigma_noise = sigma_noise\n\n self.diff_aug = diff_aug\n self.ada = ada\n self.prev_ada_p = prev_ada_p\n self.ada_target = ada_target\n self.ada_length = ada_length\n self.prior = prior\n self.truncated_factor = truncated_factor\n self.ema = ema\n self.latent_op = latent_op\n self.latent_op_rate = latent_op_rate\n self.latent_op_step = latent_op_step\n self.latent_op_step4eval = latent_op_step4eval\n self.latent_op_alpha = latent_op_alpha\n self.latent_op_beta = latent_op_beta\n self.latent_norm_reg_weight = latent_norm_reg_weight\n\n self.default_device = default_device\n self.print_every = print_every\n self.save_every = save_every\n self.checkpoint_dir = checkpoint_dir\n self.evaluate = evaluate\n self.mu = mu\n self.sigma = sigma\n self.best_fid = best_fid\n self.best_fid_checkpoint_path = best_fid_checkpoint_path\n self.mixed_precision = mixed_precision\n self.train_config = train_config\n self.model_config = model_config\n\n self.start_time = datetime.now()\n self.l2_loss = torch.nn.MSELoss()\n self.ce_loss = torch.nn.CrossEntropyLoss()\n self.policy = \"color,translation,cutout\"\n\n self.steps = steps\n self.gamma = gamma\n\n sampler = define_sampler(self.dataset_name, self.conditional_strategy)\n\n check_flag_1(self.tempering_type, self.pos_collected_numerator, self.conditional_strategy, self.diff_aug, self.ada,\n self.mixed_precision, self.gradient_penalty_for_dis, self.deep_regret_analysis_for_dis, self.cr, self.bcr, self.zcr)\n\n if self.conditional_strategy == 'ContraGAN':\n self.contrastive_criterion = Conditional_Contrastive_loss(self.default_device, self.batch_size, self.pos_collected_numerator)\n\n elif self.conditional_strategy == 'Proxy_NCA_GAN':\n if isinstance(self.dis_model, DataParallel):\n self.embedding_layer = self.dis_model.module.embedding\n else:\n self.embedding_layer = self.dis_model.embedding\n self.NCA_criterion = Proxy_NCA_loss(self.default_device, self.embedding_layer, self.num_classes, self.batch_size)\n\n elif self.conditional_strategy == 'NT_Xent_GAN':\n self.NT_Xent_criterion = NT_Xent_loss(self.default_device, self.batch_size)\n else:\n pass\n\n if self.mixed_precision:\n self.scaler = torch.cuda.amp.GradScaler()\n\n if self.dataset_name in [\"imagenet\"]:\n self.num_eval = {'train':50000, 'valid':50000}\n elif self.dataset_name in [\"imagenet_less_0.25\"]:\n self.num_eval = {'train':50000, 'valid':50000}\n elif self.dataset_name in [\"imagenet_less\"]:\n self.num_eval = {'train':50000, 'valid':50000}\n elif self.dataset_name == \"tiny_imagenet\":\n self.num_eval = {'train':50000, 'valid':10000}\n elif self.dataset_name == \"cifar10\":\n self.num_eval = {'train':50000, 'test':10000}\n elif self.dataset_name == \"cifar10_less\":\n self.num_eval = {'train':len(self.train_dataset.data), 'valid':len(self.eval_dataset.data), 'test':len(self.eval_dataset.data)}\n elif self.dataset_name in [\"cifar100_less\"]:\n self.num_eval = {'train':len(self.train_dataset.data), 'valid':len(self.eval_dataset.data), 'test':len(self.eval_dataset.data)}\n elif self.dataset_name == \"custom\":\n num_train_images = len(self.train_dataset.data)\n num_eval_images = len(self.eval_dataset.data)\n self.num_eval = {'train':num_train_images, 'valid':num_eval_images}\n else:\n raise NotImplementedError\n\n\n ################################################################################################################################\n def train(self, current_step, total_step):\n self.dis_model.train()\n self.gen_model.train()\n if self.Gen_copy is not None:\n self.Gen_copy.train()\n\n self.logger.info('Start training....')\n step_count = current_step\n train_iter = iter(self.train_dataloader)\n\n if self.ada:\n self.ada_augment = torch.tensor([0.0, 0.0], device = self.default_device)\n if self.prev_ada_p is not None:\n self.ada_aug_p = self.prev_ada_p\n else:\n self.ada_aug_p = 0.0\n self.ada_aug_step = self.ada_target/self.ada_length\n else:\n self.ada_aug_p = 'No'\n\n while step_count <= total_step:\n # ================== TRAIN D ================== #\n toggle_grad(self.dis_model, True, freeze_layers=self.freeze_layers)\n toggle_grad(self.gen_model, False, freeze_layers=-1)\n t = set_temperature(self.conditional_strategy, self.tempering_type, self.start_temperature, self.end_temperature, step_count, self.tempering_step, total_step)\n for step_index in range(self.d_steps_per_iter):\n self.D_optimizer.zero_grad()\n for acml_index in range(self.accumulation_steps):\n try:\n real_images, real_labels = next(train_iter)\n except StopIteration:\n train_iter = iter(self.train_dataloader)\n real_images, real_labels = next(train_iter)\n\n real_images, real_labels = real_images.to(self.default_device), real_labels.to(self.default_device)\n with torch.cuda.amp.autocast() if self.mixed_precision else dummy_context_mgr() as mpc:\n if self.diff_aug:\n real_images = DiffAugment(real_images, policy=self.policy)\n if self.ada:\n real_images, _ = augment(real_images, self.ada_aug_p)\n\n if self.zcr:\n zs, fake_labels, zs_t = sample_latents(self.prior, self.batch_size, self.z_dim, 1, self.num_classes,\n self.sigma_noise, self.default_device)\n else:\n zs, fake_labels = sample_latents(self.prior, self.batch_size, self.z_dim, 1, self.num_classes,\n None, self.default_device)\n if self.latent_op:\n zs = latent_optimise(zs, fake_labels, self.gen_model, self.dis_model, self.conditional_strategy,\n self.latent_op_step, self.latent_op_rate, self.latent_op_alpha, self.latent_op_beta,\n False, self.default_device)\n \n fake_images = self.gen_model(zs, fake_labels)\n if self.diff_aug:\n fake_images = DiffAugment(fake_images, policy=self.policy)\n if self.ada:\n fake_images, _ = augment(fake_images, self.ada_aug_p)\n\n if self.conditional_strategy == \"ACGAN\":\n cls_out_real, dis_out_real = self.dis_model(real_images, real_labels)\n cls_out_fake, dis_out_fake = self.dis_model(fake_images, fake_labels)\n elif self.conditional_strategy == \"ProjGAN\" or self.conditional_strategy == \"no\":\n dis_out_real = self.dis_model(real_images, real_labels)\n dis_out_fake = self.dis_model(fake_images, fake_labels)\n elif self.conditional_strategy in [\"NT_Xent_GAN\", \"Proxy_NCA_GAN\", \"ContraGAN\"]:\n real_cls_mask = make_mask(real_labels, self.num_classes, self.default_device)\n cls_proxies_real, cls_embed_real, dis_out_real = self.dis_model(real_images, real_labels)\n cls_proxies_fake, cls_embed_fake, dis_out_fake = self.dis_model(fake_images, fake_labels)\n elif self.conditional_strategy == 'ProjGAN_adv':\n dis_out_real_prefc = self.dis_model(real_images, real_labels, fc=False)\n dis_out_fake_prefc = self.dis_model(fake_images, fake_labels, fc=False)\n \n loss_real = lambda x: torch.mean(F.relu(1. - x))\n loss_fake = lambda x: torch.mean(F.relu(1. + x))\n dis_out_real_prefc_adv = PGD(dis_out_real_prefc, real_labels, loss_real, self.dis_model, steps=self.steps, gamma=self.gamma)\n dis_out_fake_prefc_adv = PGD(dis_out_fake_prefc, fake_labels, loss_real, self.dis_model, steps=self.steps, gamma=self.gamma)\n\n fake_images = fake_images.detach()\n dis_out_real_prefc = self.dis_model(real_images, real_labels, fc=False, only_fc=False)\n dis_out_fake_prefc = self.dis_model(fake_images, fake_labels, fc=False, only_fc=False)\n\n dis_out_real = self.dis_model(dis_out_real_prefc, real_labels, only_fc=True, fc=True)\n dis_out_fake = self.dis_model(dis_out_fake_prefc, fake_labels, only_fc=True, fc=True)\n\n dis_out_real_adv = self.dis_model(dis_out_real_prefc_adv, real_labels, only_fc=True)\n dis_out_fake_adv = self.dis_model(dis_out_fake_prefc_adv, fake_labels, only_fc=True)\n\n\n else:\n raise NotImplementedError\n \n #if self.conditional_strategy != 'ProjGAN_adv':\n if self.conditional_strategy != 'ProjGAN_adv':\n dis_acml_loss = self.D_loss(dis_out_real, dis_out_fake)\n else:\n dis_acml_loss = (self.D_loss(dis_out_real, dis_out_fake) + self.D_loss(dis_out_real_adv, dis_out_fake_adv)) / 2\n\n if self.conditional_strategy == \"ACGAN\":\n dis_acml_loss += (self.ce_loss(cls_out_real, real_labels) + self.ce_loss(cls_out_fake, fake_labels))\n elif self.conditional_strategy == \"NT_Xent_GAN\":\n real_images_aug = CR_DiffAug(real_images)\n _, cls_embed_real_aug, dis_out_real_aug = self.dis_model(real_images_aug, real_labels)\n dis_acml_loss += self.contrastive_lambda*self.NT_Xent_criterion(cls_embed_real, cls_embed_real_aug, t)\n elif self.conditional_strategy == \"Proxy_NCA_GAN\":\n dis_acml_loss += self.contrastive_lambda*self.NCA_criterion(cls_embed_real, cls_proxies_real, real_labels)\n elif self.conditional_strategy == \"ContraGAN\":\n dis_acml_loss += self.contrastive_lambda*self.contrastive_criterion(cls_embed_real, cls_proxies_real,\n real_cls_mask, real_labels, t, self.margin)\n else:\n pass\n\n if self.cr:\n real_images_aug = CR_DiffAug(real_images)\n if self.conditional_strategy == \"ACGAN\":\n cls_out_real_aug, dis_out_real_aug = self.dis_model(real_images_aug, real_labels)\n cls_consistency_loss = self.l2_loss(cls_out_real, cls_out_real_aug)\n elif self.conditional_strategy == \"ProjGAN\" or self.conditional_strategy == \"no\":\n dis_out_real_aug = self.dis_model(real_images_aug, real_labels)\n elif self.conditional_strategy in [\"NT_Xent_GAN\", \"Proxy_NCA_GAN\", \"ContraGAN\"]:\n _, cls_embed_real_aug, dis_out_real_aug = self.dis_model(real_images_aug, real_labels)\n cls_consistency_loss = self.l2_loss(cls_embed_real, cls_embed_real_aug)\n elif self.conditional_strategy == \"ProjGAN_adv\":\n dis_out_real_aug = self.dis_model(real_images_aug, real_labels)\n else:\n raise NotImplementedError\n\n consistency_loss = self.l2_loss(dis_out_real, dis_out_real_aug)\n if self.conditional_strategy in [\"ACGAN\", \"NT_Xent_GAN\", \"Proxy_NCA_GAN\", \"ContraGAN\"]:\n consistency_loss += cls_consistency_loss\n dis_acml_loss += self.cr_lambda*consistency_loss\n\n if self.bcr:\n real_images_aug = CR_DiffAug(real_images)\n fake_images_aug = CR_DiffAug(fake_images)\n if self.conditional_strategy == \"ACGAN\":\n cls_out_real_aug, dis_out_real_aug = self.dis_model(real_images_aug, real_labels)\n cls_out_fake_aug, dis_out_fake_aug = self.dis_model(fake_images_aug, fake_labels)\n cls_bcr_real_loss = self.l2_loss(cls_out_real, cls_out_real_aug)\n cls_bcr_fake_loss = self.l2_loss(cls_out_fake, cls_out_fake_aug)\n elif self.conditional_strategy == \"ProjGAN\" or self.conditional_strategy == \"no\":\n dis_out_real_aug = self.dis_model(real_images_aug, real_labels)\n dis_out_fake_aug = self.dis_model(fake_images_aug, fake_labels)\n elif self.conditional_strategy in [\"ContraGAN\", \"Proxy_NCA_GAN\", \"NT_Xent_GAN\"]:\n cls_proxies_real_aug, cls_embed_real_aug, dis_out_real_aug = self.dis_model(real_images_aug, real_labels)\n cls_proxies_fake_aug, cls_embed_fake_aug, dis_out_fake_aug = self.dis_model(fake_images_aug, fake_labels)\n cls_bcr_real_loss = self.l2_loss(cls_embed_real, cls_embed_real_aug)\n cls_bcr_fake_loss = self.l2_loss(cls_embed_fake, cls_embed_fake_aug)\n elif self.conditional_strategy == \"ProjGAN_adv\":\n dis_out_real_aug = self.dis_model(real_images_aug, real_labels)\n dis_out_fake_aug = self.dis_model(fake_images_aug, fake_labels)\n else:\n raise NotImplementedError\n\n bcr_real_loss = self.l2_loss(dis_out_real, dis_out_real_aug)\n bcr_fake_loss = self.l2_loss(dis_out_fake, dis_out_fake_aug)\n if self.conditional_strategy in [\"ACGAN\", \"NT_Xent_GAN\", \"Proxy_NCA_GAN\", \"ContraGAN\"]:\n bcr_real_loss += cls_bcr_real_loss\n bcr_fake_loss += cls_bcr_fake_loss\n dis_acml_loss += self.real_lambda*bcr_real_loss + self.fake_lambda*bcr_fake_loss\n\n if self.zcr:\n fake_images_zaug = self.gen_model(zs_t, fake_labels)\n if self.conditional_strategy == \"ACGAN\":\n cls_out_fake_zaug, dis_out_fake_zaug = self.dis_model(fake_images_zaug, fake_labels)\n cls_zcr_dis_loss = self.l2_loss(cls_out_fake, cls_out_fake_zaug)\n elif self.conditional_strategy == \"ProjGAN\" or self.conditional_strategy == \"no\":\n dis_out_fake_zaug = self.dis_model(fake_images_zaug, fake_labels)\n elif self.conditional_strategy in [\"ContraGAN\", \"Proxy_NCA_GAN\", \"NT_Xent_GAN\"]:\n cls_proxies_fake_zaug, cls_embed_fake_zaug, dis_out_fake_zaug = self.dis_model(fake_images_zaug, fake_labels)\n cls_zcr_dis_loss = self.l2_loss(cls_embed_fake, cls_embed_fake_zaug)\n elif self.conditional_strategy == \"ProjGAN_adv\":\n dis_out_fake_zaug = self.dis_model(fake_images_zaug, fake_labels)\n else:\n raise NotImplementedError\n\n zcr_dis_loss = self.l2_loss(dis_out_fake, dis_out_fake_zaug)\n if self.conditional_strategy in [\"ACGAN\", \"NT_Xent_GAN\", \"Proxy_NCA_GAN\", \"ContraGAN\"]:\n zcr_dis_loss += cls_zcr_dis_loss\n dis_acml_loss += self.dis_lambda*zcr_dis_loss\n\n if self.gradient_penalty_for_dis:\n dis_acml_loss += self.gradient_penalty_lambda*calc_derv4gp(self.dis_model, self.conditional_strategy, real_images,\n fake_images, real_labels, self.default_device)\n if self.deep_regret_analysis_for_dis:\n dis_acml_loss += self.regret_penalty_lambda*calc_derv4dra(self.dis_model, self.conditional_strategy, real_images,\n real_labels, self.default_device)\n if self.ada:\n ada_aug_data = torch.tensor((torch.sign(dis_out_real).sum().item(), dis_out_real.shape[0]), device = self.default_device)\n self.ada_augment += ada_aug_data\n if self.ada_augment[1] > (self.batch_size*4 - 1):\n authen_out_signs, num_outputs = self.ada_augment.tolist()\n r_t_stat = authen_out_signs/num_outputs\n sign = 1 if r_t_stat > self.ada_target else -1\n self.ada_aug_p += sign*self.ada_aug_step*num_outputs\n self.ada_aug_p = min(1.0, max(0.0, self.ada_aug_p))\n self.ada_augment.mul_(0.0)\n\n dis_acml_loss = dis_acml_loss/self.accumulation_steps\n\n if self.mixed_precision:\n self.scaler.scale(dis_acml_loss).backward()\n else:\n dis_acml_loss.backward()\n\n if self.mixed_precision:\n self.scaler.step(self.D_optimizer)\n self.scaler.update()\n else:\n self.D_optimizer.step()\n\n if self.weight_clipping_for_dis:\n for p in self.dis_model.parameters():\n p.data.clamp_(-self.weight_clipping_bound, self.weight_clipping_bound)\n\n if step_count % self.print_every == 0 and step_count !=0 and self.logger:\n if self.d_spectral_norm:\n dis_sigmas = calculate_all_sn(self.dis_model)\n self.writer.add_scalars('SN_of_dis', dis_sigmas, step_count)\n\n # ================== TRAIN G ================== #\n toggle_grad(self.dis_model, False, freeze_layers=-1)\n toggle_grad(self.gen_model, True, freeze_layers=-1)\n for step_index in range(self.g_steps_per_iter):\n self.G_optimizer.zero_grad()\n for acml_step in range(self.accumulation_steps):\n with torch.cuda.amp.autocast() if self.mixed_precision else dummy_context_mgr() as mpc:\n if self.zcr:\n zs, fake_labels, zs_t = sample_latents(self.prior, self.batch_size, self.z_dim, 1, self.num_classes,\n self.sigma_noise, self.default_device)\n else:\n zs, fake_labels = sample_latents(self.prior, self.batch_size, self.z_dim, 1, self.num_classes,\n None, self.default_device)\n if self.latent_op:\n zs, transport_cost = latent_optimise(zs, fake_labels, self.gen_model, self.dis_model, self.conditional_strategy,\n self.latent_op_step, self.latent_op_rate, self.latent_op_alpha,\n self.latent_op_beta, True, self.default_device)\n if not self.conditional_strategy == 'ProjGAN_adv':\n fake_images = self.gen_model(zs, fake_labels)\n else:\n gen_out_prefc, labels_prefc = self.gen_model(zs, fake_labels, only_l1=True)\n \n loss_fake = lambda x: -torch.mean(x)\n gen_out_adv = PGD_G(gen_out_prefc, labels_prefc, fake_labels, loss_fake, self.gen_model, self.dis_model, steps=self.steps, gamma=self.gamma)\n \n fake_images = self.gen_model(gen_out_prefc, labels_prefc, l1=False)\n fake_images_adv = self.gen_model(gen_out_adv, labels_prefc, l1=False)\n\n\n\n if self.diff_aug:\n fake_images = DiffAugment(fake_images, policy=self.policy)\n if self.ada:\n fake_images, _ = augment(fake_images, self.ada_aug_p)\n\n if self.conditional_strategy == \"ACGAN\":\n cls_out_fake, dis_out_fake = self.dis_model(fake_images, fake_labels)\n elif self.conditional_strategy == \"ProjGAN\" or self.conditional_strategy == \"no\":\n dis_out_fake = self.dis_model(fake_images, fake_labels)\n elif self.conditional_strategy in [\"NT_Xent_GAN\", \"Proxy_NCA_GAN\", \"ContraGAN\"]:\n fake_cls_mask = make_mask(fake_labels, self.num_classes, self.default_device)\n cls_proxies_fake, cls_embed_fake, dis_out_fake = self.dis_model(fake_images, fake_labels)\n elif self.conditional_strategy == 'ProjGAN_adv':\n dis_out_fake = self.dis_model(fake_images, fake_labels)\n dis_out_adv = self.dis_model(fake_images_adv, fake_labels)\n\n else:\n raise NotImplementedError\n\n gen_acml_loss = self.G_loss(dis_out_fake)\n if self.latent_op:\n gen_acml_loss += transport_cost*self.latent_norm_reg_weight\n\n if self.zcr:\n fake_images_zaug = self.gen_model(zs_t, fake_labels)\n zcr_gen_loss = -1 * self.l2_loss(fake_images, fake_images_zaug)\n gen_acml_loss += self.gen_lambda*zcr_gen_loss\n\n if self.conditional_strategy == \"ACGAN\":\n gen_acml_loss += self.ce_loss(cls_out_fake, fake_labels)\n elif self.conditional_strategy == \"ContraGAN\":\n gen_acml_loss += self.contrastive_lambda*self.contrastive_criterion(cls_embed_fake, cls_proxies_fake, fake_cls_mask, fake_labels, t, self.margin)\n elif self.conditional_strategy == \"Proxy_NCA_GAN\":\n gen_acml_loss += self.contrastive_lambda*self.NCA_criterion(cls_embed_fake, cls_proxies_fake, fake_labels)\n elif self.conditional_strategy == \"NT_Xent_GAN\":\n fake_images_aug = CR_DiffAug(fake_images)\n _, cls_embed_fake_aug, dis_out_fake_aug = self.dis_model(fake_images_aug, fake_labels)\n gen_acml_loss += self.contrastive_lambda*self.NT_Xent_criterion(cls_embed_fake, cls_embed_fake_aug, t)\n elif self.conditional_strategy == 'ProjGAN_adv':\n gen_acml_loss = (self.G_loss(dis_out_fake) + self.G_loss(dis_out_adv)) / 2\n else:\n pass\n\n gen_acml_loss = gen_acml_loss/self.accumulation_steps\n\n if self.mixed_precision:\n self.scaler.scale(gen_acml_loss).backward()\n else:\n gen_acml_loss.backward()\n\n if self.mixed_precision:\n self.scaler.step(self.G_optimizer)\n self.scaler.update()\n else:\n self.G_optimizer.step()\n\n # if ema is True: we update parameters of the Gen_copy in adaptive way.\n if self.ema:\n self.Gen_ema.update(step_count)\n\n step_count += 1\n\n if step_count % self.print_every == 0 and self.logger:\n log_message = LOG_FORMAT.format(step=step_count,\n progress=step_count/total_step,\n elapsed=elapsed_time(self.start_time),\n temperature=t,\n ada_p=self.ada_aug_p,\n dis_loss=dis_acml_loss.item(),\n gen_loss=gen_acml_loss.item(),\n )\n self.logger.info(log_message)\n\n if self.g_spectral_norm:\n gen_sigmas = calculate_all_sn(self.gen_model)\n self.writer.add_scalars('SN_of_gen', gen_sigmas, step_count)\n\n self.writer.add_scalars('Losses', {'discriminator': dis_acml_loss.item(),\n 'generator': gen_acml_loss.item()}, step_count)\n if self.ada:\n self.writer.add_scalar('ada_p', self.ada_aug_p, step_count)\n\n if step_count % self.save_every == 0 or step_count == total_step:\n if self.evaluate:\n is_best = self.evaluation(step_count, False, \"N/A\")\n self.save(step_count, is_best)\n else:\n self.save(step_count, False)\n return step_count-1\n ################################################################################################################################\n\n\n ################################################################################################################################\n def save(self, step, is_best):\n when = \"best\" if is_best is True else \"current\"\n self.dis_model.eval()\n self.gen_model.eval()\n if self.Gen_copy is not None:\n self.Gen_copy.eval()\n\n if isinstance(self.gen_model, DataParallel):\n gen = self.gen_model.module\n dis = self.dis_model.module\n if self.Gen_copy is not None:\n gen_copy = self.Gen_copy.module\n else:\n gen, dis = self.gen_model, self.dis_model\n if self.Gen_copy is not None:\n gen_copy = self.Gen_copy\n\n g_states = {'seed': self.train_config['seed'], 'run_name': self.run_name, 'step': step, 'best_step': self.best_step,\n 'state_dict': gen.state_dict(), 'optimizer': self.G_optimizer.state_dict(), 'ada_p': self.ada_aug_p}\n\n d_states = {'seed': self.train_config['seed'], 'run_name': self.run_name, 'step': step, 'best_step': self.best_step,\n 'state_dict': dis.state_dict(), 'optimizer': self.D_optimizer.state_dict(), 'ada_p': self.ada_aug_p,\n 'best_fid': self.best_fid, 'best_fid_checkpoint_path': self.checkpoint_dir}\n\n if len(glob.glob(join(self.checkpoint_dir,\"model=G-{when}-weights-step*.pth\".format(when=when)))) >= 1:\n find_and_remove(glob.glob(join(self.checkpoint_dir,\"model=G-{when}-weights-step*.pth\".format(when=when)))[0])\n find_and_remove(glob.glob(join(self.checkpoint_dir,\"model=D-{when}-weights-step*.pth\".format(when=when)))[0])\n\n g_checkpoint_output_path = join(self.checkpoint_dir, \"model=G-{when}-weights-step={step}.pth\".format(when=when, step=str(step)))\n d_checkpoint_output_path = join(self.checkpoint_dir, \"model=D-{when}-weights-step={step}.pth\".format(when=when, step=str(step)))\n\n if when == \"best\":\n if len(glob.glob(join(self.checkpoint_dir,\"model=G-current-weights-step*.pth\".format(when=when)))) >= 1:\n find_and_remove(glob.glob(join(self.checkpoint_dir,\"model=G-current-weights-step*.pth\".format(when=when)))[0])\n find_and_remove(glob.glob(join(self.checkpoint_dir,\"model=D-current-weights-step*.pth\".format(when=when)))[0])\n\n g_checkpoint_output_path_ = join(self.checkpoint_dir, \"model=G-current-weights-step={step}.pth\".format(when=when, step=str(step)))\n d_checkpoint_output_path_ = join(self.checkpoint_dir, \"model=D-current-weights-step={step}.pth\".format(when=when, step=str(step)))\n\n torch.save(g_states, g_checkpoint_output_path_)\n torch.save(d_states, d_checkpoint_output_path_)\n\n torch.save(g_states, g_checkpoint_output_path)\n torch.save(d_states, d_checkpoint_output_path)\n\n if self.Gen_copy is not None:\n g_ema_states = {'state_dict': gen_copy.state_dict()}\n if len(glob.glob(join(self.checkpoint_dir, \"model=G_ema-{when}-weights-step*.pth\".format(when=when)))) >= 1:\n find_and_remove(glob.glob(join(self.checkpoint_dir, \"model=G_ema-{when}-weights-step*.pth\".format(when=when)))[0])\n\n g_ema_checkpoint_output_path = join(self.checkpoint_dir, \"model=G_ema-{when}-weights-step={step}.pth\".format(when=when, step=str(step)))\n\n if when == \"best\":\n if len(glob.glob(join(self.checkpoint_dir,\"model=G_ema-current-weights-step*.pth\".format(when=when)))) >= 1:\n find_and_remove(glob.glob(join(self.checkpoint_dir,\"model=G_ema-current-weights-step*.pth\".format(when=when)))[0])\n\n g_ema_checkpoint_output_path_ = join(self.checkpoint_dir, \"model=G_ema-current-weights-step={step}.pth\".format(when=when, step=str(step)))\n\n torch.save(g_ema_states, g_ema_checkpoint_output_path_)\n\n torch.save(g_ema_states, g_ema_checkpoint_output_path)\n\n if self.logger:\n self.logger.info(\"Saved model to {}\".format(self.checkpoint_dir))\n\n self.dis_model.train()\n self.gen_model.train()\n if self.Gen_copy is not None:\n self.Gen_copy.train()\n ################################################################################################################################\n\n\n ################################################################################################################################\n def evaluation(self, step, standing_statistics, standing_step):\n with torch.no_grad() if self.latent_op is False else dummy_context_mgr() as mpc:\n self.logger.info(\"Start Evaluation ({step} Step): {run_name}\".format(step=step, run_name=self.run_name))\n is_best = False\n num_split, num_run4PR, num_cluster4PR, beta4PR = 1, 10, 20, 8\n\n self.dis_model.eval()\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=False)\n\n fid_score, self.m1, self.s1 = calculate_fid_score(self.eval_dataloader, generator, self.dis_model, self.inception_model, self.num_eval[self.eval_type],\n self.truncated_factor, self.prior, self.latent_op, self.latent_op_step4eval, self.latent_op_alpha,\n self.latent_op_beta, self.default_device, self.mu, self.sigma, self.run_name)\n\n kl_score, kl_std = calculate_incep_score(self.eval_dataloader, generator, self.dis_model, self.inception_model, self.num_eval[self.eval_type],\n self.truncated_factor, self.prior, self.latent_op, self.latent_op_step4eval, self.latent_op_alpha,\n self.latent_op_beta, num_split, self.default_device)\n\n precision, recall, f_beta, f_beta_inv = calculate_f_beta_score(self.eval_dataloader, generator, self.dis_model, self.inception_model, self.num_eval[self.eval_type],\n num_run4PR, num_cluster4PR, beta4PR, self.truncated_factor, self.prior, self.latent_op,\n self.latent_op_step4eval, self.latent_op_alpha, self.latent_op_beta, self.default_device)\n PR_Curve = plot_pr_curve(precision, recall, self.run_name, self.logger)\n '''\n if self.D_loss.__name__ != \"loss_wgan_dis\":\n real_train_acc, fake_acc = calculate_accuracy(self.train_dataloader, generator, self.dis_model, self.D_loss, self.num_eval[self.eval_type],\n self.truncated_factor, self.prior, self.latent_op, self.latent_op_step, self.latent_op_alpha,\n self.latent_op_beta, self.default_device, cr=self.cr, eval_generated_sample=True)\n\n if self.eval_type == 'train':\n acc_dict = {'real_train': real_train_acc, 'fake': fake_acc}\n else:\n real_eval_acc = calculate_accuracy(self.eval_dataloader, generator, self.dis_model, self.D_loss, self.num_eval[self.eval_type],\n self.truncated_factor, self.prior, self.latent_op, self.latent_op_step, self.latent_op_alpha,\n self. latent_op_beta, self.default_device, cr=self.cr, eval_generated_sample=False)\n acc_dict = {'real_train': real_train_acc, 'real_valid': real_eval_acc, 'fake': fake_acc}\n\n self.writer.add_scalars('{}/Accuracy'.format(self.prune_round), acc_dict, step)\n '''\n if self.best_fid is None:\n self.best_fid, self.best_step, is_best, f_beta_best, f_beta_inv_best = fid_score, step, True, f_beta, f_beta_inv\n else:\n if fid_score <= self.best_fid:\n self.best_fid, self.best_step, is_best, f_beta_best, f_beta_inv_best = fid_score, step, True, f_beta, f_beta_inv\n\n self.writer.add_scalars('FID score', {'using {type} moments'.format(type=self.eval_type):fid_score}, step)\n self.writer.add_scalars('F_beta score', {'{num} generated images'.format(num=str(self.num_eval[self.eval_type])):f_beta}, step)\n self.writer.add_scalars('F_beta_inv score', {'{num} generated images'.format(num=str(self.num_eval[self.eval_type])):f_beta_inv}, step)\n self.writer.add_scalars('IS score', {'{num} generated images'.format(num=str(self.num_eval[self.eval_type])):kl_score}, step)\n self.writer.add_figure('PR_Curve', PR_Curve, global_step=step)\n self.logger.info('F_{beta} score (Step: {step}, Using {type} images): {F_beta}'.format(beta=beta4PR, step=step, type=self.eval_type, F_beta=f_beta))\n self.logger.info('F_1/{beta} score (Step: {step}, Using {type} images): {F_beta_inv}'.format(beta=beta4PR, step=step, type=self.eval_type, F_beta_inv=f_beta_inv))\n self.logger.info('FID score (Step: {step}, Using {type} moments): {FID}'.format(step=step, type=self.eval_type, FID=fid_score))\n self.logger.info('Inception score (Step: {step}, {num} generated images): {IS}'.format(step=step, num=str(self.num_eval[self.eval_type]), IS=kl_score))\n if self.train:\n self.logger.info('Best FID score (Step: {step}, Using {type} moments): {FID}'.format(step=self.best_step, type=self.eval_type, FID=self.best_fid))\n\n self.dis_model.train()\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=True)\n\n return is_best\n ################################################################################################################################\n\n\n ################################################################################################################################\n def save_images(self, is_generate, standing_statistics, standing_step, png=True, npz=True):\n with torch.no_grad() if self.latent_op is False else dummy_context_mgr() as mpc:\n self.dis_model.eval()\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=False)\n\n if png:\n save_images_png(self.run_name, self.eval_dataloader, self.num_eval[self.eval_type], self.num_classes, generator,\n self.dis_model, is_generate, self.truncated_factor, self.prior, self.latent_op, self.latent_op_step,\n self.latent_op_alpha, self.latent_op_beta, self.default_device)\n if npz:\n save_images_npz(self.run_name, self.eval_dataloader, self.num_eval[self.eval_type], self.num_classes, generator,\n self.dis_model, is_generate, self.truncated_factor, self.prior, self.latent_op, self.latent_op_step,\n self.latent_op_alpha, self.latent_op_beta, self.default_device)\n ################################################################################################################################\n\n\n ################################################################################################################################\n def run_image_visualization(self, nrow, ncol, standing_statistics, standing_step):\n self.logger.info('Start visualizing images....')\n with torch.no_grad() if self.latent_op is False else dummy_context_mgr() as mpc:\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=False)\n\n sampler = \"default\" if self.conditional_strategy == \"no\" else \"class_order_some\"\n if self.zcr:\n zs, fake_labels, zs_t = sample_latents(self.prior, self.batch_size, self.z_dim, 1, self.num_classes,\n self.sigma_noise, self.default_device, sampler=sampler)\n else:\n zs, fake_labels = sample_latents(self.prior, self.batch_size, self.z_dim, 1, self.num_classes,\n None, self.default_device, sampler=sampler)\n\n if self.latent_op:\n zs = latent_optimise(zs, fake_labels, self.gen_model, self.dis_model, self.conditional_strategy,\n self.latent_op_step, self.latent_op_rate, self.latent_op_alpha, self.latent_op_beta,\n False, self.default_device)\n\n generated_images = generator(zs, fake_labels, evaluation=True)\n\n plot_img_canvas((generated_images.detach().cpu()+1)/2, \"./figures/{run_name}/generated_canvas.png\".\\\n format(run_name=self.run_name), self.logger, ncol)\n\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=True)\n ################################################################################################################################\n\n\n ################################################################################################################################\n def run_linear_interpolation(self, nrow, ncol, fix_z, fix_y, standing_statistics, standing_step):\n self.logger.info('Start linear interpolation analysis....')\n with torch.no_grad() if self.latent_op is False else dummy_context_mgr() as mpc:\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=False)\n shared = generator.module.shared if isinstance(generator, DataParallel) else generator.shared\n assert int(fix_z)*int(fix_y) != 1, \"unable to switch fix_z and fix_y on together!\"\n\n if fix_z:\n zs = torch.randn(nrow, 1, self.z_dim, device=self.default_device)\n zs = zs.repeat(1, ncol, 1).view(-1, self.z_dim)\n name = \"fix_z\"\n else:\n zs = interp(torch.randn(nrow, 1, self.z_dim, device=self.default_device),\n torch.randn(nrow, 1, self.z_dim, device=self.default_device),\n ncol - 2).view(-1, self.z_dim)\n\n if fix_y:\n ys = sample_1hot(nrow, self.num_classes, device=self.default_device)\n ys = shared(ys).view(nrow, 1, -1)\n ys = ys.repeat(1, ncol, 1).view(nrow * (ncol), -1)\n name = \"fix_y\"\n else:\n ys = interp(shared(sample_1hot(nrow, self.num_classes)).view(nrow, 1, -1),\n shared(sample_1hot(nrow, self.num_classes)).view(nrow, 1, -1),\n ncol-2).view(nrow * (ncol), -1)\n\n interpolated_images = generator(zs, None, shared_label=ys, evaluation=True)\n\n plot_img_canvas((interpolated_images.detach().cpu()+1)/2, \"./figures/{run_name}/Interpolated_images_{fix_flag}.png\".\\\n format(run_name=self.run_name, fix_flag=name), self.logger, ncol)\n\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=True)\n ################################################################################################################################\n\n\n ################################################################################################################################\n def run_nearest_neighbor(self, nrow, ncol, standing_statistics, standing_step):\n self.logger.info('Start nearest neighbor analysis....')\n with torch.no_grad() if self.latent_op is False else dummy_context_mgr() as mpc:\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=False)\n\n resnet50_model = torch.hub.load('pytorch/vision:v0.6.0', 'resnet50', pretrained=True)\n resnet50_conv = nn.Sequential(*list(resnet50_model.children())[:-1]).to(self.default_device)\n if self.n_gpus > 1:\n resnet50_conv = DataParallel(resnet50_conv, output_device=self.default_device)\n resnet50_conv.eval()\n\n for c in tqdm(range(self.num_classes)):\n fake_images, fake_labels = generate_images_for_KNN(self.batch_size, c, generator, self.dis_model, self.truncated_factor, self.prior, self.latent_op,\n self.latent_op_step, self.latent_op_alpha, self.latent_op_beta, self.default_device)\n fake_image = torch.unsqueeze(fake_images[0], dim=0)\n fake_anchor_embedding = torch.squeeze(resnet50_conv((fake_image+1)/2))\n\n num_samples, target_sampler = target_class_sampler(self.train_dataset, c)\n train_dataloader = torch.utils.data.DataLoader(self.train_dataset, batch_size=self.batch_size, shuffle=False, sampler=target_sampler,\n num_workers=self.train_config['num_workers'], pin_memory=True)\n train_iter = iter(train_dataloader)\n for batch_idx in range(num_samples//self.batch_size):\n real_images, real_labels = next(train_iter)\n real_images = real_images.to(self.default_device)\n real_embeddings = torch.squeeze(resnet50_conv((real_images+1)/2))\n if batch_idx == 0:\n distances = torch.square(real_embeddings - fake_anchor_embedding).mean(dim=1).detach().cpu().numpy()\n holder = real_images.detach().cpu().numpy()\n else:\n distances = np.concatenate([distances, torch.square(real_embeddings - fake_anchor_embedding).mean(dim=1).detach().cpu().numpy()], axis=0)\n holder = np.concatenate([holder, real_images.detach().cpu().numpy()], axis=0)\n\n nearest_indices = (-distances).argsort()[-(ncol-1):][::-1]\n if c % nrow == 0:\n canvas = np.concatenate([fake_image.detach().cpu().numpy(), holder[nearest_indices]], axis=0)\n elif c % nrow == nrow-1:\n row_images = np.concatenate([fake_image.detach().cpu().numpy(), holder[nearest_indices]], axis=0)\n canvas = np.concatenate((canvas, row_images), axis=0)\n plot_img_canvas((torch.from_numpy(canvas)+1)/2, \"./figures/{run_name}/Fake_anchor_{ncol}NN_{cls}.png\".\\\n format(run_name=self.run_name,ncol=ncol, cls=c), self.logger, ncol)\n else:\n row_images = np.concatenate([fake_image.detach().cpu().numpy(), holder[nearest_indices]], axis=0)\n canvas = np.concatenate((canvas, row_images), axis=0)\n\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=True)\n ################################################################################################################################\n\n\n ################################################################################################################################\n def run_frequency_analysis(self, num_images, standing_statistics, standing_step):\n self.logger.info('Start linear interpolation analysis....')\n with torch.no_grad() if self.latent_op is False else dummy_context_mgr() as mpc:\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=False)\n\n train_iter = iter(self.train_dataloader)\n num_batches = num_images//self.batch_size\n for i in range(num_batches):\n if self.zcr:\n zs, fake_labels, zs_t = sample_latents(self.prior, self.batch_size, self.z_dim, 1, self.num_classes,\n self.sigma_noise, self.default_device)\n else:\n zs, fake_labels = sample_latents(self.prior, self.batch_size, self.z_dim, 1, self.num_classes,\n None, self.default_device)\n\n if self.latent_op:\n zs = latent_optimise(zs, fake_labels, self.gen_model, self.dis_model, self.conditional_strategy,\n self.latent_op_step, self.latent_op_rate, self.latent_op_alpha, self.latent_op_beta,\n False, self.default_device)\n\n real_images, real_labels = next(train_iter)\n fake_images = generator(zs, fake_labels, evaluation=True).detach().cpu().numpy()\n\n real_images = np.asarray((real_images + 1)*127.5, np.uint8)\n fake_images = np.asarray((fake_images + 1)*127.5, np.uint8)\n\n if i == 0:\n real_array = real_images\n fake_array = fake_images\n else:\n real_array = np.concatenate([real_array, real_images], axis = 0)\n fake_array = np.concatenate([fake_array, fake_images], axis = 0)\n\n N, C, H, W = np.shape(real_array)\n real_r, real_g, real_b = real_array[:,0,:,:], real_array[:,1,:,:], real_array[:,2,:,:]\n real_gray = 0.2989 * real_r + 0.5870 * real_g + 0.1140 * real_b\n fake_r, fake_g, fake_b = fake_array[:,0,:,:], fake_array[:,1,:,:], fake_array[:,2,:,:]\n fake_gray = 0.2989 * fake_r + 0.5870 * fake_g + 0.1140 * fake_b\n for j in tqdm(range(N)):\n real_gray_f = np.fft.fft2(real_gray[j] - ndimage.median_filter(real_gray[j], size= H//8))\n fake_gray_f = np.fft.fft2(fake_gray[j] - ndimage.median_filter(fake_gray[j], size=H//8))\n\n real_gray_f_shifted = np.fft.fftshift(real_gray_f)\n fake_gray_f_shifted = np.fft.fftshift(fake_gray_f)\n\n if j == 0:\n real_gray_spectrum = 20*np.log(np.abs(real_gray_f_shifted))/N\n fake_gray_spectrum = 20*np.log(np.abs(fake_gray_f_shifted))/N\n else:\n real_gray_spectrum += 20*np.log(np.abs(real_gray_f_shifted))/N\n fake_gray_spectrum += 20*np.log(np.abs(fake_gray_f_shifted))/N\n\n plot_spectrum_image(real_gray_spectrum, fake_gray_spectrum, self.run_name, self.logger)\n\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=True)\n ################################################################################################################################\n\n\n\ndef PGD(x, label, loss, model=None, steps=1, gamma=0.1, eps=(1/255), randinit=False, clip=False):\n \n # Compute loss\n x_adv = x.clone()\n if randinit:\n # adv noise (-eps, eps)\n x_adv += (2.0 * torch.rand(x_adv.shape).cuda() - 1.0) * eps\n x_adv = x_adv.cuda()\n x = x.cuda()\n\n for t in range(steps):\n out = model(x_adv, label, only_fc=True)\n loss_adv0 = -loss(out)\n grad0 = torch.autograd.grad(loss_adv0, x_adv, only_inputs=True)[0]\n x_adv.data.add_(gamma * torch.sign(grad0.data))\n\n if clip:\n linfball_proj(x, eps, x_adv, in_place=True)\n\n return x_adv\n\ndef PGD_G(x, gen_labels, label, loss, gen_model, dis_model, steps=1, gamma=0.1, eps=(1/255), randinit=False, clip=False):\n \n # Compute loss\n x_adv = x.clone()\n x_adv = x_adv.cuda()\n x = x.cuda()\n\n for t in range(steps):\n out = gen_model(x_adv, gen_labels, l1=False)\n out = dis_model(out, label)\n loss_adv0 = -loss(out)\n grad0 = torch.autograd.grad(loss_adv0, x_adv, only_inputs=True)[0]\n x_adv.data.add_(gamma * torch.sign(grad0.data))\n\n if clip:\n linfball_proj(x, eps, x_adv, in_place=True)\n\n return x_adv", "# PyTorch StudioGAN: https://github.com/POSTECH-CVLab/PyTorch-StudioGAN\n# The MIT License (MIT)\n# See license file or visit https://github.com/POSTECH-CVLab/PyTorch-StudioGAN for details\n\n# train_eval.py\n\n\nimport numpy as np\nimport sys\nimport glob\nfrom scipy import ndimage\nfrom os.path import join\nfrom PIL import Image\nfrom tqdm import tqdm\nfrom datetime import datetime\n\nfrom metrics.IS import calculate_incep_score\nfrom metrics.FID import calculate_fid_score\nfrom metrics.F_beta import calculate_f_beta_score\nfrom metrics.Accuracy import calculate_accuracy\nfrom utils.ada import augment\nfrom utils.biggan_utils import interp\nfrom utils.sample import sample_latents, sample_1hot, make_mask, target_class_sampler\nfrom utils.misc import *\nfrom utils.losses import calc_derv4gp, calc_derv4dra, calc_derv, latent_optimise\nfrom utils.losses import Conditional_Contrastive_loss, Proxy_NCA_loss, NT_Xent_loss\nfrom utils.diff_aug import DiffAugment\nfrom utils.cr_diff_aug import CR_DiffAug\nfrom utils.prune import see_remain_rate_orig\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import DataParallel\nimport torch.nn.functional as F\nimport torchvision\nfrom torchvision import transforms\n\n\n\nSAVE_FORMAT = 'step={step:0>3}-Inception_mean={Inception_mean:<.4}-Inception_std={Inception_std:<.4}-FID={FID:<.5}.pth'\n\nLOG_FORMAT = (\n \"Round: {prune_round} \" \n \"Sparsity: {sparsity} \" \n \"Step: {step:>7} \"\n \"Progress: {progress:<.1%} \"\n \"Elapsed: {elapsed} \"\n \"temperature: {temperature:<.6} \"\n \"ada_p: {ada_p:<.6} \"\n \"Discriminator_loss: {dis_loss:<.6} \"\n \"Generator_loss: {gen_loss:<.6} \"\n)\n\n\ndef set_temperature(conditional_strategy, tempering_type, start_temperature, end_temperature, step_count, tempering_step, total_step):\n if conditional_strategy == 'ContraGAN':\n if tempering_type == 'continuous':\n t = start_temperature + step_count*(end_temperature - start_temperature)/total_step\n elif tempering_type == 'discrete':\n tempering_interval = total_step//(tempering_step + 1)\n t = start_temperature + \\\n (step_count//tempering_interval)*(end_temperature-start_temperature)/tempering_step\n else:\n t = start_temperature\n else:\n t = 'no'\n return t\n\n\nclass Train_Eval(object):\n def __init__(self, prune_round, gen_masks, dis_masks, run_name, best_step, dataset_name, eval_type, logger, writer, n_gpus, gen_model, dis_model, inception_model,\n Gen_copy, Gen_ema, train_dataset, eval_dataset, train_dataloader, eval_dataloader, freeze_layers, conditional_strategy,\n pos_collected_numerator, z_dim, num_classes, hypersphere_dim, d_spectral_norm, g_spectral_norm, G_optimizer, D_optimizer,\n batch_size, g_steps_per_iter, d_steps_per_iter, accumulation_steps, total_step, G_loss, D_loss, contrastive_lambda, margin,\n tempering_type, tempering_step, start_temperature, end_temperature, weight_clipping_for_dis, weight_clipping_bound,\n gradient_penalty_for_dis, gradient_penalty_lambda, deep_regret_analysis_for_dis, regret_penalty_lambda, cr, cr_lambda, bcr,\n real_lambda, fake_lambda, zcr, gen_lambda, dis_lambda, sigma_noise, diff_aug, ada, prev_ada_p, ada_target, ada_length, prior,\n truncated_factor, ema, latent_op, latent_op_rate, latent_op_step, latent_op_step4eval, latent_op_alpha, latent_op_beta,\n latent_norm_reg_weight, default_device, print_every, save_every, checkpoint_dir, evaluate, mu, sigma, best_fid,\n best_fid_checkpoint_path, mixed_precision, train_config, model_config, gamma, steps):\n\n self.prune_round = prune_round\n self.gen_masks = gen_masks\n self.dis_masks = dis_masks\n self.run_name = run_name\n self.best_step = best_step\n self.dataset_name = dataset_name\n self.eval_type = eval_type\n self.logger = logger\n self.writer = writer\n self.n_gpus = n_gpus\n\n self.gen_model = gen_model\n self.dis_model = dis_model\n self.inception_model = inception_model\n self.Gen_copy = Gen_copy\n self.Gen_ema = Gen_ema\n\n self.train_dataset = train_dataset\n self.eval_dataset = eval_dataset\n self.train_dataloader = train_dataloader\n self.eval_dataloader = eval_dataloader\n\n self.freeze_layers = freeze_layers\n\n self.conditional_strategy = conditional_strategy\n self.pos_collected_numerator = pos_collected_numerator\n self.z_dim = z_dim\n self.num_classes = num_classes\n self.hypersphere_dim = hypersphere_dim\n self.d_spectral_norm = d_spectral_norm\n self.g_spectral_norm = g_spectral_norm\n\n self.G_optimizer = G_optimizer\n self.D_optimizer = D_optimizer\n self.batch_size = batch_size\n self.g_steps_per_iter = g_steps_per_iter\n self.d_steps_per_iter = d_steps_per_iter\n self.accumulation_steps = accumulation_steps\n self.total_step = total_step\n\n self.G_loss = G_loss\n self.D_loss = D_loss\n self.contrastive_lambda = contrastive_lambda\n self.margin = margin\n self.tempering_type = tempering_type\n self.tempering_step = tempering_step\n self.start_temperature = start_temperature\n self.end_temperature = end_temperature\n self.weight_clipping_for_dis = weight_clipping_for_dis\n self.weight_clipping_bound = weight_clipping_bound\n self.gradient_penalty_for_dis = gradient_penalty_for_dis\n self.gradient_penalty_lambda = gradient_penalty_lambda\n self.deep_regret_analysis_for_dis = deep_regret_analysis_for_dis\n self.regret_penalty_lambda = regret_penalty_lambda\n self.cr = cr\n self.cr_lambda = cr_lambda\n self.bcr = bcr\n self.real_lambda = real_lambda\n self.fake_lambda = fake_lambda\n self.zcr = zcr\n self.gen_lambda = gen_lambda\n self.dis_lambda = dis_lambda\n self.sigma_noise = sigma_noise\n\n self.diff_aug = diff_aug\n self.ada = ada\n self.prev_ada_p = prev_ada_p\n self.ada_target = ada_target\n self.ada_length = ada_length\n self.prior = prior\n self.truncated_factor = truncated_factor\n self.ema = ema\n self.latent_op = latent_op\n self.latent_op_rate = latent_op_rate\n self.latent_op_step = latent_op_step\n self.latent_op_step4eval = latent_op_step4eval\n self.latent_op_alpha = latent_op_alpha\n self.latent_op_beta = latent_op_beta\n self.latent_norm_reg_weight = latent_norm_reg_weight\n\n self.default_device = default_device\n self.print_every = print_every\n self.save_every = save_every\n self.checkpoint_dir = checkpoint_dir\n self.evaluate = evaluate\n self.mu = mu\n self.sigma = sigma\n self.best_fid = best_fid\n self.best_fid_checkpoint_path = best_fid_checkpoint_path\n self.mixed_precision = mixed_precision\n self.train_config = train_config\n self.model_config = model_config\n\n self.start_time = datetime.now()\n self.l2_loss = torch.nn.MSELoss()\n self.ce_loss = torch.nn.CrossEntropyLoss()\n self.policy = \"color,translation,cutout\"\n\n self.steps = steps\n self.gamma = gamma\n\n sampler = define_sampler(self.dataset_name, self.conditional_strategy)\n\n check_flag_1(self.tempering_type, self.pos_collected_numerator, self.conditional_strategy, self.diff_aug, self.ada,\n self.mixed_precision, self.gradient_penalty_for_dis, self.deep_regret_analysis_for_dis, self.cr, self.bcr, self.zcr)\n\n if self.conditional_strategy == 'ContraGAN':\n self.contrastive_criterion = Conditional_Contrastive_loss(self.default_device, self.batch_size, self.pos_collected_numerator)\n\n elif self.conditional_strategy == 'Proxy_NCA_GAN':\n if isinstance(self.dis_model, DataParallel):\n self.embedding_layer = self.dis_model.module.embedding\n else:\n self.embedding_layer = self.dis_model.embedding\n self.NCA_criterion = Proxy_NCA_loss(self.default_device, self.embedding_layer, self.num_classes, self.batch_size)\n\n elif self.conditional_strategy == 'NT_Xent_GAN':\n self.NT_Xent_criterion = NT_Xent_loss(self.default_device, self.batch_size)\n else:\n pass\n\n if self.mixed_precision:\n self.scaler = torch.cuda.amp.GradScaler()\n\n if self.dataset_name in [\"imagenet\"]:\n self.num_eval = {'train':50000, 'valid':50000}\n elif self.dataset_name == \"tiny_imagenet\":\n self.num_eval = {'train':50000, 'valid':10000}\n elif self.dataset_name == \"cifar10\":\n num_train_images = len(self.train_dataset.data)\n num_eval_images = len(self.eval_dataset.data)\n self.num_eval = {'train':num_train_images, 'test':num_eval_images}\n elif self.dataset_name == \"cifar10_less\":\n num_train_images = len(self.train_dataset.data)\n num_eval_images = len(self.eval_dataset.data)\n self.num_eval = {'train':num_train_images, 'test':num_eval_images}\n elif self.dataset_name == \"cifar100\":\n self.num_eval = {'train':len(self.train_dataset.data), 'test':len(self.eval_dataset.data)}\n elif self.dataset_name == \"cifar100_less\":\n self.num_eval = {'train':len(self.train_dataset.data), 'test':len(self.eval_dataset.data)}\n elif self.dataset_name == \"custom\":\n num_train_images = len(self.train_dataset.data)\n num_eval_images = len(self.eval_dataset.data)\n self.num_eval = {'train':num_train_images, 'valid':num_eval_images}\n else:\n raise NotImplementedError\n\n\n ################################################################################################################################\n def train(self, current_step, total_step):\n self.dis_model.train()\n self.gen_model.train()\n if self.Gen_copy is not None:\n self.Gen_copy.train()\n\n self.logger.info('Start training....')\n step_count = current_step\n train_iter = iter(self.train_dataloader)\n\n if self.ada:\n self.ada_augment = torch.tensor([0.0, 0.0], device = self.default_device)\n if self.prev_ada_p is not None:\n self.ada_aug_p = self.prev_ada_p\n else:\n self.ada_aug_p = 0.0\n self.ada_aug_step = self.ada_target/self.ada_length\n else:\n self.ada_aug_p = 'No'\n\n while step_count <= total_step:\n # ================== TRAIN D ================== #\n toggle_grad(self.dis_model, True, freeze_layers=self.freeze_layers)\n toggle_grad(self.gen_model, False, freeze_layers=-1)\n t = set_temperature(self.conditional_strategy, self.tempering_type, self.start_temperature, self.end_temperature, step_count, self.tempering_step, total_step)\n for step_index in range(self.d_steps_per_iter):\n self.D_optimizer.zero_grad()\n for acml_index in range(self.accumulation_steps):\n try:\n real_images, real_labels = next(train_iter)\n except StopIteration:\n train_iter = iter(self.train_dataloader)\n real_images, real_labels = next(train_iter)\n\n real_images, real_labels = real_images.to(self.default_device), real_labels.to(self.default_device)\n with torch.cuda.amp.autocast() if self.mixed_precision else dummy_context_mgr() as mpc:\n if self.diff_aug:\n real_images = DiffAugment(real_images, policy=self.policy)\n if self.ada:\n real_images, _ = augment(real_images, self.ada_aug_p)\n\n if self.zcr:\n zs, fake_labels, zs_t = sample_latents(self.prior, self.batch_size, self.z_dim, 1, self.num_classes,\n self.sigma_noise, self.default_device)\n else:\n zs, fake_labels = sample_latents(self.prior, self.batch_size, self.z_dim, 1, self.num_classes,\n None, self.default_device)\n if self.latent_op:\n zs = latent_optimise(zs, fake_labels, self.gen_model, self.dis_model, self.conditional_strategy,\n self.latent_op_step, self.latent_op_rate, self.latent_op_alpha, self.latent_op_beta,\n False, self.default_device)\n\n fake_images = self.gen_model(zs, fake_labels)\n if self.diff_aug:\n fake_images = DiffAugment(fake_images, policy=self.policy)\n if self.ada:\n fake_images, _ = augment(fake_images, self.ada_aug_p)\n\n if self.conditional_strategy == \"ACGAN\":\n cls_out_real, dis_out_real = self.dis_model(real_images, real_labels)\n cls_out_fake, dis_out_fake = self.dis_model(fake_images, fake_labels)\n elif self.conditional_strategy == \"ProjGAN\" or self.conditional_strategy == \"no\":\n dis_out_real = self.dis_model(real_images, real_labels)\n dis_out_fake = self.dis_model(fake_images, fake_labels)\n elif self.conditional_strategy in [\"NT_Xent_GAN\", \"Proxy_NCA_GAN\", \"ContraGAN\"]:\n real_cls_mask = make_mask(real_labels, self.num_classes, self.default_device)\n cls_proxies_real, cls_embed_real, dis_out_real = self.dis_model(real_images, real_labels)\n cls_proxies_fake, cls_embed_fake, dis_out_fake = self.dis_model(fake_images, fake_labels)\n elif self.conditional_strategy == 'ProjGAN_adv':\n dis_out_real_prefc = self.dis_model(real_images, real_labels, fc=False)\n dis_out_fake_prefc = self.dis_model(fake_images, fake_labels, fc=False)\n \n loss_real = lambda x: torch.mean(F.relu(1. - x))\n loss_fake = lambda x: torch.mean(F.relu(1. + x))\n dis_out_real_prefc_adv = PGD(dis_out_real_prefc, real_labels, loss_real, self.dis_model, steps=self.steps, gamma=self.gamma)\n dis_out_fake_prefc_adv = PGD(dis_out_fake_prefc, fake_labels, loss_real, self.dis_model, steps=self.steps, gamma=self.gamma)\n\n fake_images = fake_images.detach()\n dis_out_real_prefc = self.dis_model(real_images, real_labels, fc=False, only_fc=False)\n dis_out_fake_prefc = self.dis_model(fake_images, fake_labels, fc=False, only_fc=False)\n\n dis_out_real = self.dis_model(dis_out_real_prefc, real_labels, only_fc=True, fc=True)\n dis_out_fake = self.dis_model(dis_out_fake_prefc, fake_labels, only_fc=True, fc=True)\n\n dis_out_real_adv = self.dis_model(dis_out_real_prefc_adv, real_labels, only_fc=True)\n dis_out_fake_adv = self.dis_model(dis_out_fake_prefc_adv, fake_labels, only_fc=True)\n else:\n raise NotImplementedError\n \n if self.conditional_strategy != 'ProjGAN_adv':\n dis_acml_loss = self.D_loss(dis_out_real, dis_out_fake)\n else:\n dis_acml_loss = (self.D_loss(dis_out_real, dis_out_fake) + self.D_loss(dis_out_real_adv, dis_out_fake_adv)) / 2\n\n if self.conditional_strategy == \"ACGAN\":\n dis_acml_loss += (self.ce_loss(cls_out_real, real_labels) + self.ce_loss(cls_out_fake, fake_labels))\n elif self.conditional_strategy == \"NT_Xent_GAN\":\n real_images_aug = CR_DiffAug(real_images)\n _, cls_embed_real_aug, dis_out_real_aug = self.dis_model(real_images_aug, real_labels)\n dis_acml_loss += self.contrastive_lambda*self.NT_Xent_criterion(cls_embed_real, cls_embed_real_aug, t)\n elif self.conditional_strategy == \"Proxy_NCA_GAN\":\n dis_acml_loss += self.contrastive_lambda*self.NCA_criterion(cls_embed_real, cls_proxies_real, real_labels)\n elif self.conditional_strategy == \"ContraGAN\":\n dis_acml_loss += self.contrastive_lambda*self.contrastive_criterion(cls_embed_real, cls_proxies_real,\n real_cls_mask, real_labels, t, self.margin)\n else:\n pass\n\n if self.cr:\n real_images_aug = CR_DiffAug(real_images)\n if self.conditional_strategy == \"ACGAN\":\n cls_out_real_aug, dis_out_real_aug = self.dis_model(real_images_aug, real_labels)\n cls_consistency_loss = self.l2_loss(cls_out_real, cls_out_real_aug)\n elif self.conditional_strategy == \"ProjGAN\" or self.conditional_strategy == \"no\":\n dis_out_real_aug = self.dis_model(real_images_aug, real_labels)\n elif self.conditional_strategy in [\"NT_Xent_GAN\", \"Proxy_NCA_GAN\", \"ContraGAN\"]:\n _, cls_embed_real_aug, dis_out_real_aug = self.dis_model(real_images_aug, real_labels)\n cls_consistency_loss = self.l2_loss(cls_embed_real, cls_embed_real_aug)\n elif self.conditional_strategy == 'ProjGAN_adv':\n dis_out_real_aug, _ = self.dis_model(real_images_aug, real_labels)\n else:\n raise NotImplementedError\n\n consistency_loss = self.l2_loss(dis_out_real, dis_out_real_aug)\n if self.conditional_strategy in [\"ACGAN\", \"NT_Xent_GAN\", \"Proxy_NCA_GAN\", \"ContraGAN\"]:\n consistency_loss += cls_consistency_loss\n dis_acml_loss += self.cr_lambda*consistency_loss\n\n if self.bcr:\n real_images_aug = CR_DiffAug(real_images)\n fake_images_aug = CR_DiffAug(fake_images)\n if self.conditional_strategy == \"ACGAN\":\n cls_out_real_aug, dis_out_real_aug = self.dis_model(real_images_aug, real_labels)\n cls_out_fake_aug, dis_out_fake_aug = self.dis_model(fake_images_aug, fake_labels)\n cls_bcr_real_loss = self.l2_loss(cls_out_real, cls_out_real_aug)\n cls_bcr_fake_loss = self.l2_loss(cls_out_fake, cls_out_fake_aug)\n elif self.conditional_strategy == \"ProjGAN\" or self.conditional_strategy == \"no\":\n dis_out_real_aug = self.dis_model(real_images_aug, real_labels)\n dis_out_fake_aug = self.dis_model(fake_images_aug, fake_labels)\n elif self.conditional_strategy in [\"ContraGAN\", \"Proxy_NCA_GAN\", \"NT_Xent_GAN\"]:\n cls_proxies_real_aug, cls_embed_real_aug, dis_out_real_aug = self.dis_model(real_images_aug, real_labels)\n cls_proxies_fake_aug, cls_embed_fake_aug, dis_out_fake_aug = self.dis_model(fake_images_aug, fake_labels)\n cls_bcr_real_loss = self.l2_loss(cls_embed_real, cls_embed_real_aug)\n cls_bcr_fake_loss = self.l2_loss(cls_embed_fake, cls_embed_fake_aug)\n elif self.conditional_strategy == \"ProjGAN_adv\":\n dis_out_real_aug,_ = self.dis_model(real_images_aug, real_labels)\n dis_out_fake_aug,_ = self.dis_model(fake_images_aug, fake_labels)\n else:\n raise NotImplementedError\n\n bcr_real_loss = self.l2_loss(dis_out_real, dis_out_real_aug)\n bcr_fake_loss = self.l2_loss(dis_out_fake, dis_out_fake_aug)\n if self.conditional_strategy in [\"ACGAN\", \"NT_Xent_GAN\", \"Proxy_NCA_GAN\", \"ContraGAN\"]:\n bcr_real_loss += cls_bcr_real_loss\n bcr_fake_loss += cls_bcr_fake_loss\n dis_acml_loss += self.real_lambda*bcr_real_loss + self.fake_lambda*bcr_fake_loss\n\n if self.zcr:\n fake_images_zaug = self.gen_model(zs_t, fake_labels)\n if self.conditional_strategy == \"ACGAN\":\n cls_out_fake_zaug, dis_out_fake_zaug = self.dis_model(fake_images_zaug, fake_labels)\n cls_zcr_dis_loss = self.l2_loss(cls_out_fake, cls_out_fake_zaug)\n elif self.conditional_strategy == \"ProjGAN\" or self.conditional_strategy == \"no\":\n dis_out_fake_zaug = self.dis_model(fake_images_zaug, fake_labels)\n elif self.conditional_strategy in [\"ContraGAN\", \"Proxy_NCA_GAN\", \"NT_Xent_GAN\"]:\n cls_proxies_fake_zaug, cls_embed_fake_zaug, dis_out_fake_zaug = self.dis_model(fake_images_zaug, fake_labels)\n cls_zcr_dis_loss = self.l2_loss(cls_embed_fake, cls_embed_fake_zaug)\n elif self.conditional_strategy == \"ProjGAN_adv\":\n dis_out_fake_zaug,_ = self.dis_model(fake_images_zaug, fake_labels)\n else:\n raise NotImplementedError\n\n zcr_dis_loss = self.l2_loss(dis_out_fake, dis_out_fake_zaug)\n if self.conditional_strategy in [\"ACGAN\", \"NT_Xent_GAN\", \"Proxy_NCA_GAN\", \"ContraGAN\"]:\n zcr_dis_loss += cls_zcr_dis_loss\n dis_acml_loss += self.dis_lambda*zcr_dis_loss\n\n if self.gradient_penalty_for_dis:\n dis_acml_loss += self.gradient_penalty_lambda*calc_derv4gp(self.dis_model, self.conditional_strategy, real_images,\n fake_images, real_labels, self.default_device)\n if self.deep_regret_analysis_for_dis:\n dis_acml_loss += self.regret_penalty_lambda*calc_derv4dra(self.dis_model, self.conditional_strategy, real_images,\n real_labels, self.default_device)\n if self.ada:\n ada_aug_data = torch.tensor((torch.sign(dis_out_real).sum().item(), dis_out_real.shape[0]), device = self.default_device)\n self.ada_augment += ada_aug_data\n if self.ada_augment[1] > (self.batch_size*4 - 1):\n authen_out_signs, num_outputs = self.ada_augment.tolist()\n r_t_stat = authen_out_signs/num_outputs\n sign = 1 if r_t_stat > self.ada_target else -1\n self.ada_aug_p += sign*self.ada_aug_step*num_outputs\n self.ada_aug_p = min(1.0, max(0.0, self.ada_aug_p))\n self.ada_augment.mul_(0.0)\n\n dis_acml_loss = dis_acml_loss/self.accumulation_steps\n\n if self.mixed_precision:\n self.scaler.scale(dis_acml_loss).backward()\n else:\n dis_acml_loss.backward()\n if self.dis_masks is not None:\n for k, m in enumerate(self.dis_model.modules()):\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n try:\n m.weight_orig.grad.mul_(self.dis_masks[k])\n except:\n m.weight.grad.mul_(self.dis_masks[k])\n if self.mixed_precision:\n self.scaler.step(self.D_optimizer)\n self.scaler.update()\n else:\n self.D_optimizer.step()\n\n if self.weight_clipping_for_dis:\n for p in self.dis_model.parameters():\n p.data.clamp_(-self.weight_clipping_bound, self.weight_clipping_bound)\n\n if step_count % self.print_every == 0 and step_count !=0 and self.logger:\n if self.d_spectral_norm:\n dis_sigmas = calculate_all_sn(self.dis_model)\n self.writer.add_scalars('SN_of_dis', dis_sigmas, step_count)\n\n # ================== TRAIN G ================== #\n toggle_grad(self.dis_model, False, freeze_layers=-1)\n toggle_grad(self.gen_model, True, freeze_layers=-1)\n for step_index in range(self.g_steps_per_iter):\n self.G_optimizer.zero_grad()\n for acml_step in range(self.accumulation_steps):\n with torch.cuda.amp.autocast() if self.mixed_precision else dummy_context_mgr() as mpc:\n if self.zcr:\n zs, fake_labels, zs_t = sample_latents(self.prior, self.batch_size, self.z_dim, 1, self.num_classes,\n self.sigma_noise, self.default_device)\n else:\n zs, fake_labels = sample_latents(self.prior, self.batch_size, self.z_dim, 1, self.num_classes,\n None, self.default_device)\n if self.latent_op:\n zs, transport_cost = latent_optimise(zs, fake_labels, self.gen_model, self.dis_model, self.conditional_strategy,\n self.latent_op_step, self.latent_op_rate, self.latent_op_alpha,\n self.latent_op_beta, True, self.default_device)\n\n if not self.conditional_strategy == 'ProjGAN_adv':\n fake_images = self.gen_model(zs, fake_labels)\n else:\n gen_out_prefc, labels_prefc = self.gen_model(zs, fake_labels, only_l1=True)\n \n loss_fake = lambda x: -torch.mean(x)\n gen_out_adv = PGD_G(gen_out_prefc, labels_prefc, fake_labels, loss_fake, self.gen_model, self.dis_model, steps=self.steps, gamma=self.gamma)\n \n fake_images = self.gen_model(gen_out_prefc, labels_prefc, l1=False)\n fake_images_adv = self.gen_model(gen_out_adv, labels_prefc, l1=False)\n\n if self.diff_aug:\n fake_images = DiffAugment(fake_images, policy=self.policy)\n if self.ada:\n fake_images, _ = augment(fake_images, self.ada_aug_p)\n\n if self.conditional_strategy == \"ACGAN\":\n cls_out_fake, dis_out_fake = self.dis_model(fake_images, fake_labels)\n elif self.conditional_strategy == \"ProjGAN\" or self.conditional_strategy == \"no\":\n dis_out_fake = self.dis_model(fake_images, fake_labels)\n elif self.conditional_strategy in [\"NT_Xent_GAN\", \"Proxy_NCA_GAN\", \"ContraGAN\"]:\n fake_cls_mask = make_mask(fake_labels, self.num_classes, self.default_device)\n cls_proxies_fake, cls_embed_fake, dis_out_fake = self.dis_model(fake_images, fake_labels)\n elif self.conditional_strategy == 'ProjGAN_adv':\n dis_out_fake = self.dis_model(fake_images, fake_labels)\n dis_out_adv = self.dis_model(fake_images_adv, fake_labels) \n else:\n raise NotImplementedError\n\n gen_acml_loss = self.G_loss(dis_out_fake)\n\n if self.latent_op:\n gen_acml_loss += transport_cost*self.latent_norm_reg_weight\n\n if self.zcr:\n fake_images_zaug = self.gen_model(zs_t, fake_labels)\n zcr_gen_loss = -1 * self.l2_loss(fake_images, fake_images_zaug)\n gen_acml_loss += self.gen_lambda*zcr_gen_loss\n\n if self.conditional_strategy == \"ACGAN\":\n gen_acml_loss += self.ce_loss(cls_out_fake, fake_labels)\n elif self.conditional_strategy == \"ContraGAN\":\n gen_acml_loss += self.contrastive_lambda*self.contrastive_criterion(cls_embed_fake, cls_proxies_fake, fake_cls_mask, fake_labels, t, self.margin)\n elif self.conditional_strategy == \"Proxy_NCA_GAN\":\n gen_acml_loss += self.contrastive_lambda*self.NCA_criterion(cls_embed_fake, cls_proxies_fake, fake_labels)\n elif self.conditional_strategy == \"NT_Xent_GAN\":\n fake_images_aug = CR_DiffAug(fake_images)\n _, cls_embed_fake_aug, dis_out_fake_aug = self.dis_model(fake_images_aug, fake_labels)\n gen_acml_loss += self.contrastive_lambda*self.NT_Xent_criterion(cls_embed_fake, cls_embed_fake_aug, t)\n elif self.conditional_strategy == 'ProjGAN_adv':\n gen_acml_loss = (self.G_loss(dis_out_fake) + self.G_loss(dis_out_adv)) / 2\n else:\n pass\n\n gen_acml_loss = gen_acml_loss/self.accumulation_steps\n\n if self.mixed_precision:\n self.scaler.scale(gen_acml_loss).backward()\n else:\n gen_acml_loss.backward()\n\n if self.gen_masks is not None:\n for k, m in enumerate(self.gen_model.modules()):\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n try:\n m.weight_orig.grad.mul_(self.gen_masks[k])\n except:\n m.weight.grad.mul_(self.gen_masks[k])\n \n if self.dis_masks is not None:\n for k, m in enumerate(self.dis_model.modules()):\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n try:\n m.weight_orig.grad.mul_(self.dis_masks[k])\n except:\n m.weight.grad.mul_(self.dis_masks[k])\n\n if self.mixed_precision:\n self.scaler.step(self.G_optimizer)\n self.scaler.update()\n else:\n self.G_optimizer.step()\n\n # if ema is True: we update parameters of the Gen_copy in adaptive way.\n if self.ema:\n self.Gen_ema.update(step_count)\n\n step_count += 1\n\n if step_count % self.print_every == 0 and self.logger:\n if self.gen_masks is not None:\n sparsity = see_remain_rate_orig(self.gen_model)\n else:\n sparsity = 100\n log_message = LOG_FORMAT.format(\n prune_round=self.prune_round,\n sparsity=sparsity,\n step=step_count,\n progress=step_count/total_step,\n elapsed=elapsed_time(self.start_time),\n temperature=t,\n ada_p=self.ada_aug_p,\n dis_loss=dis_acml_loss.item(),\n gen_loss=gen_acml_loss.item(),\n )\n self.logger.info(log_message)\n\n if self.g_spectral_norm:\n gen_sigmas = calculate_all_sn(self.gen_model)\n self.writer.add_scalars('{}/SN_of_gen'.format(self.prune_round), gen_sigmas, step_count)\n\n self.writer.add_scalars('{}/Losses'.format(self.prune_round), {'discriminator': dis_acml_loss.item(),\n 'generator': gen_acml_loss.item()}, step_count)\n if self.ada:\n self.writer.add_scalar('{}/ada_p'.format(self.prune_round), self.ada_aug_p, step_count)\n\n if step_count % self.save_every == 0 or step_count == total_step:\n if self.evaluate:\n is_best = self.evaluation(step_count, False, \"N/A\")\n self.save(step_count, is_best)\n else:\n self.save(step_count, False)\n return step_count-1\n ################################################################################################################################\n\n\n ################################################################################################################################\n def save(self, step, is_best):\n when = \"best\" if is_best is True else \"current\"\n self.dis_model.eval()\n self.gen_model.eval()\n if self.Gen_copy is not None:\n self.Gen_copy.eval()\n\n if isinstance(self.gen_model, DataParallel):\n gen = self.gen_model.module\n dis = self.dis_model.module\n if self.Gen_copy is not None:\n gen_copy = self.Gen_copy.module\n else:\n gen, dis = self.gen_model, self.dis_model\n if self.Gen_copy is not None:\n gen_copy = self.Gen_copy\n\n g_states = {'prune_round': self.prune_round, 'seed': self.train_config['seed'], 'run_name': self.run_name, 'step': step, 'best_step': self.best_step,\n 'state_dict': gen.state_dict(), 'optimizer': self.G_optimizer.state_dict(), 'ada_p': self.ada_aug_p}\n\n d_states = {'prune_round': self.prune_round, 'seed': self.train_config['seed'], 'run_name': self.run_name, 'step': step, 'best_step': self.best_step,\n 'state_dict': dis.state_dict(), 'optimizer': self.D_optimizer.state_dict(), 'ada_p': self.ada_aug_p,\n 'best_fid': self.best_fid, 'best_fid_checkpoint_path': self.checkpoint_dir}\n\n if len(glob.glob(join(self.checkpoint_dir,\"model=G-{prune}-{when}-weights-step*.pth\".format(when=when, prune=self.prune_round)))) >= 1:\n find_and_remove(glob.glob(join(self.checkpoint_dir,\"model=G-{prune}-{when}-weights-step*.pth\".format(when=when, prune=self.prune_round)))[0])\n find_and_remove(glob.glob(join(self.checkpoint_dir,\"model=D-{prune}-{when}-weights-step*.pth\".format(when=when, prune=self.prune_round)))[0])\n\n g_checkpoint_output_path = join(self.checkpoint_dir, \"model=G-{prune}-{when}-weights-step={step}.pth\".format(when=when, step=str(step), prune=self.prune_round))\n d_checkpoint_output_path = join(self.checkpoint_dir, \"model=D-{prune}-{when}-weights-step={step}.pth\".format(when=when, step=str(step), prune=self.prune_round))\n\n if when == \"best\":\n if len(glob.glob(join(self.checkpoint_dir,\"model=G-{prune}-current-weights-step*.pth\".format(when=when, prune=self.prune_round)))) >= 1:\n find_and_remove(glob.glob(join(self.checkpoint_dir,\"model=G-{prune}-current-weights-step*.pth\".format(when=when, prune=self.prune_round)))[0])\n find_and_remove(glob.glob(join(self.checkpoint_dir,\"model=D-{prune}-current-weights-step*.pth\".format(when=when, prune=self.prune_round)))[0])\n\n g_checkpoint_output_path_ = join(self.checkpoint_dir, \"model=G-{prune}-current-weights-step={step}.pth\".format(when=when, step=str(step), prune=self.prune_round))\n d_checkpoint_output_path_ = join(self.checkpoint_dir, \"model=D-{prune}-current-weights-step={step}.pth\".format(when=when, step=str(step), prune=self.prune_round))\n\n torch.save(g_states, g_checkpoint_output_path_)\n torch.save(d_states, d_checkpoint_output_path_)\n\n torch.save(g_states, g_checkpoint_output_path)\n torch.save(d_states, d_checkpoint_output_path)\n\n if self.Gen_copy is not None:\n g_ema_states = {'state_dict': gen_copy.state_dict()}\n if len(glob.glob(join(self.checkpoint_dir, \"model=G_ema-{prune}-{when}-weights-step*.pth\".format(when=when, prune=self.prune_round)))) >= 1:\n find_and_remove(glob.glob(join(self.checkpoint_dir, \"model=G_ema-{prune}-{when}-weights-step*.pth\".format(when=when, prune=self.prune_round)))[0])\n\n g_ema_checkpoint_output_path = join(self.checkpoint_dir, \"model=G_ema-{prune}-{when}-weights-step={step}.pth\".format(when=when, step=str(step), prune=self.prune_round))\n\n if when == \"best\":\n if len(glob.glob(join(self.checkpoint_dir,\"model=G_ema-{prune}-current-weights-step*.pth\".format(when=when, prune=self.prune_round)))) >= 1:\n find_and_remove(glob.glob(join(self.checkpoint_dir,\"model=G_ema-{prune}-current-weights-step*.pth\".format(when=when, prune=self.prune_round)))[0])\n\n g_ema_checkpoint_output_path_ = join(self.checkpoint_dir, \"model=G_ema-{prune}-current-weights-step={step}.pth\".format(when=when, step=str(step), prune=self.prune_round))\n\n torch.save(g_ema_states, g_ema_checkpoint_output_path_)\n\n torch.save(g_ema_states, g_ema_checkpoint_output_path)\n\n if self.logger:\n self.logger.info(\"Saved model to {}\".format(self.checkpoint_dir))\n\n self.dis_model.train()\n self.gen_model.train()\n if self.Gen_copy is not None:\n self.Gen_copy.train()\n ################################################################################################################################\n\n\n ################################################################################################################################\n def evaluation(self, step, standing_statistics, standing_step):\n with torch.no_grad() if self.latent_op is False else dummy_context_mgr() as mpc:\n self.logger.info(\"Start Evaluation ({step} Step): {run_name}\".format(step=step, run_name=self.run_name))\n is_best = False\n num_split, num_run4PR, num_cluster4PR, beta4PR = 1, 10, 20, 8\n\n self.dis_model.eval()\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=False)\n\n fid_score, self.m1, self.s1 = calculate_fid_score(self.eval_dataloader, generator, self.dis_model, self.inception_model, self.num_eval[self.eval_type],\n self.truncated_factor, self.prior, self.latent_op, self.latent_op_step4eval, self.latent_op_alpha,\n self.latent_op_beta, self.default_device, self.mu, self.sigma, self.run_name)\n\n kl_score, kl_std = calculate_incep_score(self.eval_dataloader, generator, self.dis_model, self.inception_model, self.num_eval[self.eval_type],\n self.truncated_factor, self.prior, self.latent_op, self.latent_op_step4eval, self.latent_op_alpha,\n self.latent_op_beta, num_split, self.default_device)\n\n precision, recall, f_beta, f_beta_inv = calculate_f_beta_score(self.eval_dataloader, generator, self.dis_model, self.inception_model, self.num_eval[self.eval_type],\n num_run4PR, num_cluster4PR, beta4PR, self.truncated_factor, self.prior, self.latent_op,\n self.latent_op_step4eval, self.latent_op_alpha, self.latent_op_beta, self.default_device)\n PR_Curve = plot_pr_curve(precision, recall, self.run_name, self.logger)\n '''\n if self.D_loss.__name__ != \"loss_wgan_dis\":\n real_train_acc, fake_acc = calculate_accuracy(self.train_dataloader, generator, self.dis_model, self.D_loss, self.num_eval[self.eval_type],\n self.truncated_factor, self.prior, self.latent_op, self.latent_op_step, self.latent_op_alpha,\n self.latent_op_beta, self.default_device, cr=self.cr, eval_generated_sample=True)\n\n if self.eval_type == 'train':\n acc_dict = {'real_train': real_train_acc, 'fake': fake_acc}\n else:\n real_eval_acc = calculate_accuracy(self.eval_dataloader, generator, self.dis_model, self.D_loss, self.num_eval[self.eval_type],\n self.truncated_factor, self.prior, self.latent_op, self.latent_op_step, self.latent_op_alpha,\n self. latent_op_beta, self.default_device, cr=self.cr, eval_generated_sample=False)\n acc_dict = {'real_train': real_train_acc, 'real_valid': real_eval_acc, 'fake': fake_acc}\n\n self.writer.add_scalars('{}/Accuracy'.format(self.prune_round), acc_dict, step)\n '''\n if self.best_fid is None:\n self.best_fid, self.best_step, is_best, f_beta_best, f_beta_inv_best = fid_score, step, True, f_beta, f_beta_inv\n else:\n if fid_score <= self.best_fid:\n self.best_fid, self.best_step, is_best, f_beta_best, f_beta_inv_best = fid_score, step, True, f_beta, f_beta_inv\n\n self.writer.add_scalars('FID score', {'using {type} moments'.format(type=self.eval_type):fid_score}, step)\n self.writer.add_scalars('F_beta score', {'{num} generated images'.format(num=str(self.num_eval[self.eval_type])):f_beta}, step)\n self.writer.add_scalars('F_beta_inv score', {'{num} generated images'.format(num=str(self.num_eval[self.eval_type])):f_beta_inv}, step)\n self.writer.add_scalars('IS score', {'{num} generated images'.format(num=str(self.num_eval[self.eval_type])):kl_score}, step)\n self.writer.add_figure('PR_Curve', PR_Curve, global_step=step)\n self.logger.info('F_{beta} score (Step: {step}, Using {type} images): {F_beta}'.format(beta=beta4PR, step=step, type=self.eval_type, F_beta=f_beta))\n self.logger.info('F_1/{beta} score (Step: {step}, Using {type} images): {F_beta_inv}'.format(beta=beta4PR, step=step, type=self.eval_type, F_beta_inv=f_beta_inv))\n self.logger.info('FID score (Step: {step}, Using {type} moments): {FID}'.format(step=step, type=self.eval_type, FID=fid_score))\n self.logger.info('Inception score (Step: {step}, {num} generated images): {IS}'.format(step=step, num=str(self.num_eval[self.eval_type]), IS=kl_score))\n if self.train:\n self.logger.info('Best FID score (Step: {step}, Using {type} moments): {FID}'.format(step=self.best_step, type=self.eval_type, FID=self.best_fid))\n\n self.dis_model.train()\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=True)\n\n return is_best\n ################################################################################################################################\n\n\n ################################################################################################################################\n def save_images(self, is_generate, standing_statistics, standing_step, png=True, npz=True):\n with torch.no_grad() if self.latent_op is False else dummy_context_mgr() as mpc:\n self.dis_model.eval()\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=False)\n\n if png:\n save_images_png(self.run_name, self.eval_dataloader, self.num_eval[self.eval_type], self.num_classes, generator,\n self.dis_model, is_generate, self.truncated_factor, self.prior, self.latent_op, self.latent_op_step,\n self.latent_op_alpha, self.latent_op_beta, self.default_device)\n if npz:\n save_images_npz(self.run_name, self.eval_dataloader, self.num_eval[self.eval_type], self.num_classes, generator,\n self.dis_model, is_generate, self.truncated_factor, self.prior, self.latent_op, self.latent_op_step,\n self.latent_op_alpha, self.latent_op_beta, self.default_device)\n ################################################################################################################################\n\n\n ################################################################################################################################\n def run_image_visualization(self, nrow, ncol, standing_statistics, standing_step):\n self.logger.info('Start visualizing images....')\n with torch.no_grad() if self.latent_op is False else dummy_context_mgr() as mpc:\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=False)\n\n sampler = \"default\" if self.conditional_strategy == \"no\" else \"class_order_some\"\n if self.zcr:\n zs, fake_labels, zs_t = sample_latents(self.prior, self.batch_size, self.z_dim, 1, self.num_classes,\n self.sigma_noise, self.default_device, sampler=sampler)\n else:\n zs, fake_labels = sample_latents(self.prior, self.batch_size, self.z_dim, 1, self.num_classes,\n None, self.default_device, sampler=sampler)\n\n if self.latent_op:\n zs = latent_optimise(zs, fake_labels, self.gen_model, self.dis_model, self.conditional_strategy,\n self.latent_op_step, self.latent_op_rate, self.latent_op_alpha, self.latent_op_beta,\n False, self.default_device)\n\n generated_images = generator(zs, fake_labels, evaluation=True)\n\n plot_img_canvas((generated_images.detach().cpu()+1)/2, \"./figures/{run_name}/generated_canvas.png\".\\\n format(run_name=self.run_name), self.logger, ncol)\n\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=True)\n ################################################################################################################################\n\n\n ################################################################################################################################\n def run_linear_interpolation(self, nrow, ncol, fix_z, fix_y, standing_statistics, standing_step):\n self.logger.info('Start linear interpolation analysis....')\n with torch.no_grad() if self.latent_op is False else dummy_context_mgr() as mpc:\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=False)\n shared = generator.module.shared if isinstance(generator, DataParallel) else generator.shared\n assert int(fix_z)*int(fix_y) != 1, \"unable to switch fix_z and fix_y on together!\"\n\n if fix_z:\n zs = torch.randn(nrow, 1, self.z_dim, device=self.default_device)\n zs = zs.repeat(1, ncol, 1).view(-1, self.z_dim)\n name = \"fix_z\"\n else:\n zs = interp(torch.randn(nrow, 1, self.z_dim, device=self.default_device),\n torch.randn(nrow, 1, self.z_dim, device=self.default_device),\n ncol - 2).view(-1, self.z_dim)\n\n if fix_y:\n ys = sample_1hot(nrow, self.num_classes, device=self.default_device)\n ys = shared(ys).view(nrow, 1, -1)\n ys = ys.repeat(1, ncol, 1).view(nrow * (ncol), -1)\n name = \"fix_y\"\n else:\n ys = interp(shared(sample_1hot(nrow, self.num_classes)).view(nrow, 1, -1),\n shared(sample_1hot(nrow, self.num_classes)).view(nrow, 1, -1),\n ncol-2).view(nrow * (ncol), -1)\n\n interpolated_images = generator(zs, None, shared_label=ys, evaluation=True)\n\n plot_img_canvas((interpolated_images.detach().cpu()+1)/2, \"./figures/{run_name}/Interpolated_images_{fix_flag}.png\".\\\n format(run_name=self.run_name, fix_flag=name), self.logger, ncol)\n\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=True)\n ################################################################################################################################\n\n\n ################################################################################################################################\n def run_nearest_neighbor(self, nrow, ncol, standing_statistics, standing_step):\n self.logger.info('Start nearest neighbor analysis....')\n with torch.no_grad() if self.latent_op is False else dummy_context_mgr() as mpc:\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=False)\n\n resnet50_model = torch.hub.load('pytorch/vision:v0.6.0', 'resnet50', pretrained=True)\n resnet50_conv = nn.Sequential(*list(resnet50_model.children())[:-1]).to(self.default_device)\n if self.n_gpus > 1:\n resnet50_conv = DataParallel(resnet50_conv, output_device=self.default_device)\n resnet50_conv.eval()\n\n for c in tqdm(range(self.num_classes)):\n fake_images, fake_labels = generate_images_for_KNN(self.batch_size, c, generator, self.dis_model, self.truncated_factor, self.prior, self.latent_op,\n self.latent_op_step, self.latent_op_alpha, self.latent_op_beta, self.default_device)\n fake_image = torch.unsqueeze(fake_images[0], dim=0)\n fake_anchor_embedding = torch.squeeze(resnet50_conv((fake_image+1)/2))\n\n num_samples, target_sampler = target_class_sampler(self.train_dataset, c)\n train_dataloader = torch.utils.data.DataLoader(self.train_dataset, batch_size=self.batch_size, shuffle=False, sampler=target_sampler,\n num_workers=self.train_config['num_workers'], pin_memory=True)\n train_iter = iter(train_dataloader)\n for batch_idx in range(num_samples//self.batch_size):\n real_images, real_labels = next(train_iter)\n real_images = real_images.to(self.default_device)\n real_embeddings = torch.squeeze(resnet50_conv((real_images+1)/2))\n if batch_idx == 0:\n distances = torch.square(real_embeddings - fake_anchor_embedding).mean(dim=1).detach().cpu().numpy()\n holder = real_images.detach().cpu().numpy()\n else:\n distances = np.concatenate([distances, torch.square(real_embeddings - fake_anchor_embedding).mean(dim=1).detach().cpu().numpy()], axis=0)\n holder = np.concatenate([holder, real_images.detach().cpu().numpy()], axis=0)\n\n nearest_indices = (-distances).argsort()[-(ncol-1):][::-1]\n if c % nrow == 0:\n canvas = np.concatenate([fake_image.detach().cpu().numpy(), holder[nearest_indices]], axis=0)\n elif c % nrow == nrow-1:\n row_images = np.concatenate([fake_image.detach().cpu().numpy(), holder[nearest_indices]], axis=0)\n canvas = np.concatenate((canvas, row_images), axis=0)\n plot_img_canvas((torch.from_numpy(canvas)+1)/2, \"./figures/{run_name}/Fake_anchor_{ncol}NN_{cls}.png\".\\\n format(run_name=self.run_name,ncol=ncol, cls=c), self.logger, ncol)\n else:\n row_images = np.concatenate([fake_image.detach().cpu().numpy(), holder[nearest_indices]], axis=0)\n canvas = np.concatenate((canvas, row_images), axis=0)\n\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=True)\n ################################################################################################################################\n\n\n ################################################################################################################################\n def run_frequency_analysis(self, num_images, standing_statistics, standing_step):\n self.logger.info('Start linear interpolation analysis....')\n with torch.no_grad() if self.latent_op is False else dummy_context_mgr() as mpc:\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=False)\n\n train_iter = iter(self.train_dataloader)\n num_batches = num_images//self.batch_size\n for i in range(num_batches):\n if self.zcr:\n zs, fake_labels, zs_t = sample_latents(self.prior, self.batch_size, self.z_dim, 1, self.num_classes,\n self.sigma_noise, self.default_device)\n else:\n zs, fake_labels = sample_latents(self.prior, self.batch_size, self.z_dim, 1, self.num_classes,\n None, self.default_device)\n\n if self.latent_op:\n zs = latent_optimise(zs, fake_labels, self.gen_model, self.dis_model, self.conditional_strategy,\n self.latent_op_step, self.latent_op_rate, self.latent_op_alpha, self.latent_op_beta,\n False, self.default_device)\n\n real_images, real_labels = next(train_iter)\n fake_images = generator(zs, fake_labels, evaluation=True).detach().cpu().numpy()\n\n real_images = np.asarray((real_images + 1)*127.5, np.uint8)\n fake_images = np.asarray((fake_images + 1)*127.5, np.uint8)\n\n if i == 0:\n real_array = real_images\n fake_array = fake_images\n else:\n real_array = np.concatenate([real_array, real_images], axis = 0)\n fake_array = np.concatenate([fake_array, fake_images], axis = 0)\n\n N, C, H, W = np.shape(real_array)\n real_r, real_g, real_b = real_array[:,0,:,:], real_array[:,1,:,:], real_array[:,2,:,:]\n real_gray = 0.2989 * real_r + 0.5870 * real_g + 0.1140 * real_b\n fake_r, fake_g, fake_b = fake_array[:,0,:,:], fake_array[:,1,:,:], fake_array[:,2,:,:]\n fake_gray = 0.2989 * fake_r + 0.5870 * fake_g + 0.1140 * fake_b\n for j in tqdm(range(N)):\n real_gray_f = np.fft.fft2(real_gray[j] - ndimage.median_filter(real_gray[j], size= H//8))\n fake_gray_f = np.fft.fft2(fake_gray[j] - ndimage.median_filter(fake_gray[j], size=H//8))\n\n real_gray_f_shifted = np.fft.fftshift(real_gray_f)\n fake_gray_f_shifted = np.fft.fftshift(fake_gray_f)\n\n if j == 0:\n real_gray_spectrum = 20*np.log(np.abs(real_gray_f_shifted))/N\n fake_gray_spectrum = 20*np.log(np.abs(fake_gray_f_shifted))/N\n else:\n real_gray_spectrum += 20*np.log(np.abs(real_gray_f_shifted))/N\n fake_gray_spectrum += 20*np.log(np.abs(fake_gray_f_shifted))/N\n\n plot_spectrum_image(real_gray_spectrum, fake_gray_spectrum, self.run_name, self.logger)\n\n generator = change_generator_mode(self.gen_model, self.Gen_copy, standing_statistics, standing_step, self.prior,\n self.batch_size, self.z_dim, self.num_classes, self.default_device, training=True)\n ################################################################################################################################\n\n\ndef PGD(x, label, loss, model=None, steps=1, gamma=0.1, eps=(1/255), randinit=False, clip=False):\n \n # Compute loss\n x_adv = x.clone()\n if randinit:\n # adv noise (-eps, eps)\n x_adv += (2.0 * torch.rand(x_adv.shape).cuda() - 1.0) * eps\n x_adv = x_adv.cuda()\n x = x.cuda()\n\n for t in range(steps):\n out = model(x_adv, label, only_fc=True)\n loss_adv0 = -loss(out)\n grad0 = torch.autograd.grad(loss_adv0, x_adv, only_inputs=True)[0]\n x_adv.data.add_(gamma * torch.sign(grad0.data))\n\n if clip:\n linfball_proj(x, eps, x_adv, in_place=True)\n\n return x_adv\n\ndef PGD_G(x, gen_labels, label, loss, gen_model, dis_model, steps=1, gamma=0.1, eps=(1/255), randinit=False, clip=False):\n \n # Compute loss\n x_adv = x.clone()\n x_adv = x_adv.cuda()\n x = x.cuda()\n\n for t in range(steps):\n out = gen_model(x_adv, gen_labels, l1=False)\n out = dis_model(out, label)\n loss_adv0 = -loss(out)\n grad0 = torch.autograd.grad(loss_adv0, x_adv, only_inputs=True)[0]\n x_adv.data.add_(gamma * torch.sign(grad0.data))\n\n if clip:\n linfball_proj(x, eps, x_adv, in_place=True)\n\n return x_adv", "# PyTorch StudioGAN: https://github.com/POSTECH-CVLab/PyTorch-StudioGAN\n# The MIT License (MIT)\n# See license file or visit https://github.com/POSTECH-CVLab/PyTorch-StudioGAN for details\n\n# models/resnet.py\n\n\nfrom utils.model_ops import *\nfrom utils.misc import *\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n\nclass GenBlock(nn.Module):\n def __init__(self, in_channels, out_channels, g_spectral_norm, activation_fn, conditional_bn, num_classes):\n super(GenBlock, self).__init__()\n self.conditional_bn = conditional_bn\n\n if self.conditional_bn:\n self.bn1 = ConditionalBatchNorm2d(num_features=in_channels, num_classes=num_classes,\n spectral_norm=g_spectral_norm)\n self.bn2 = ConditionalBatchNorm2d(num_features=out_channels, num_classes=num_classes,\n spectral_norm=g_spectral_norm)\n else:\n self.bn1 = batchnorm_2d(in_features=in_channels)\n self.bn2 = batchnorm_2d(in_features=out_channels)\n\n if activation_fn == \"ReLU\":\n self.activation = nn.ReLU(inplace=True)\n elif activation_fn == \"Leaky_ReLU\":\n self.activation = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n elif activation_fn == \"ELU\":\n self.activation = nn.ELU(alpha=1.0, inplace=True)\n elif activation_fn == \"GELU\":\n self.activation = nn.GELU()\n else:\n raise NotImplementedError\n\n if g_spectral_norm:\n self.conv2d0 = snconv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1, padding=0)\n self.conv2d1 = snconv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1)\n self.conv2d2 = snconv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1)\n else:\n self.conv2d0 = conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1, padding=0)\n self.conv2d1 = conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1)\n self.conv2d2 = conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1)\n\n def forward(self, x, label):\n x0 = x\n\n if self.conditional_bn:\n x = self.bn1(x, label)\n else:\n x = self.bn1(x)\n x = self.activation(x)\n x = F.interpolate(x, scale_factor=2, mode='nearest')\n x = self.conv2d1(x)\n if self.conditional_bn:\n x = self.bn2(x, label)\n else:\n x = self.bn2(x)\n x = self.activation(x)\n x = self.conv2d2(x)\n\n x0 = F.interpolate(x0, scale_factor=2, mode='nearest')\n x0 = self.conv2d0(x0)\n\n out = x + x0\n return out\n\n\nclass Generator(nn.Module):\n \"\"\"Generator.\"\"\"\n def __init__(self, z_dim, shared_dim, img_size, g_conv_dim, g_spectral_norm, attention, attention_after_nth_gen_block, activation_fn,\n conditional_strategy, num_classes, initialize, G_depth, mixed_precision):\n super(Generator, self).__init__()\n g_in_dims_collection = {\"32\": [g_conv_dim*4, g_conv_dim*4, g_conv_dim*4],\n \"64\": [g_conv_dim*16, g_conv_dim*16, g_conv_dim*8, g_conv_dim*4],\n \"128\": [g_conv_dim*16, g_conv_dim*16, g_conv_dim*8, g_conv_dim*4, g_conv_dim*2],\n \"256\": [g_conv_dim*16, g_conv_dim*16, g_conv_dim*8, g_conv_dim*8, g_conv_dim*4, g_conv_dim*2],\n \"512\": [g_conv_dim*16, g_conv_dim*16, g_conv_dim*8, g_conv_dim*8, g_conv_dim*4, g_conv_dim*2, g_conv_dim]}\n\n g_out_dims_collection = {\"32\": [g_conv_dim*4, g_conv_dim*4, g_conv_dim*4],\n \"64\": [g_conv_dim*16, g_conv_dim*8, g_conv_dim*4, g_conv_dim*2],\n \"128\": [g_conv_dim*16, g_conv_dim*8, g_conv_dim*4, g_conv_dim*2, g_conv_dim],\n \"256\": [g_conv_dim*16, g_conv_dim*8, g_conv_dim*8, g_conv_dim*4, g_conv_dim*2, g_conv_dim],\n \"512\": [g_conv_dim*16, g_conv_dim*8, g_conv_dim*8, g_conv_dim*4, g_conv_dim*2, g_conv_dim, g_conv_dim]}\n bottom_collection = {\"32\": 4, \"64\": 4, \"128\": 4, \"256\": 4, \"512\": 4}\n\n self.z_dim = z_dim\n self.num_classes = num_classes\n self.mixed_precision = mixed_precision\n conditional_bn = True if conditional_strategy in [\"ACGAN\", \"ProjGAN\", \"ContraGAN\", \"Proxy_NCA_GAN\", \"NT_Xent_GAN\"] else False\n\n self.in_dims = g_in_dims_collection[str(img_size)]\n self.out_dims = g_out_dims_collection[str(img_size)]\n self.bottom = bottom_collection[str(img_size)]\n\n if g_spectral_norm:\n self.linear0 = snlinear(in_features=self.z_dim, out_features=self.in_dims[0]*self.bottom*self.bottom)\n else:\n self.linear0 = linear(in_features=self.z_dim, out_features=self.in_dims[0]*self.bottom*self.bottom)\n\n self.blocks = []\n for index in range(len(self.in_dims)):\n self.blocks += [[GenBlock(in_channels=self.in_dims[index],\n out_channels=self.out_dims[index],\n g_spectral_norm=g_spectral_norm,\n activation_fn=activation_fn,\n conditional_bn=conditional_bn,\n num_classes=self.num_classes)]]\n\n if index+1 == attention_after_nth_gen_block and attention is True:\n self.blocks += [[Self_Attn(self.out_dims[index], g_spectral_norm)]]\n\n self.blocks = nn.ModuleList([nn.ModuleList(block) for block in self.blocks])\n\n self.bn4 = batchnorm_2d(in_features=self.out_dims[-1])\n\n if activation_fn == \"ReLU\":\n self.activation = nn.ReLU(inplace=True)\n elif activation_fn == \"Leaky_ReLU\":\n self.activation = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n elif activation_fn == \"ELU\":\n self.activation = nn.ELU(alpha=1.0, inplace=True)\n elif activation_fn == \"GELU\":\n self.activation = nn.GELU()\n else:\n raise NotImplementedError\n\n if g_spectral_norm:\n self.conv2d5 = snconv2d(in_channels=self.out_dims[-1], out_channels=3, kernel_size=3, stride=1, padding=1)\n else:\n self.conv2d5 = conv2d(in_channels=self.out_dims[-1], out_channels=3, kernel_size=3, stride=1, padding=1)\n\n self.tanh = nn.Tanh()\n\n # Weight init\n if initialize is not False:\n init_weights(self.modules, initialize)\n\n def forward(self, z, label, evaluation=False):\n with torch.cuda.amp.autocast() if self.mixed_precision is True and evaluation is False else dummy_context_mgr() as mp:\n act = self.linear0(z)\n act = act.view(-1, self.in_dims[0], self.bottom, self.bottom)\n for index, blocklist in enumerate(self.blocks):\n for block in blocklist:\n if isinstance(block, Self_Attn):\n act = block(act)\n else:\n act = block(act, label)\n act = self.bn4(act)\n act = self.activation(act)\n act = self.conv2d5(act)\n out = self.tanh(act)\n return out\n\n\nclass DiscOptBlock(nn.Module):\n def __init__(self, in_channels, out_channels, d_spectral_norm, activation_fn):\n super(DiscOptBlock, self).__init__()\n self.d_spectral_norm = d_spectral_norm\n\n if d_spectral_norm:\n self.conv2d0 = snconv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1, padding=0)\n self.conv2d1 = snconv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1)\n self.conv2d2 = snconv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1)\n else:\n self.conv2d0 = conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1, padding=0)\n self.conv2d1 = conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1)\n self.conv2d2 = conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1)\n\n self.bn0 = batchnorm_2d(in_features=in_channels)\n self.bn1 = batchnorm_2d(in_features=out_channels)\n\n if activation_fn == \"ReLU\":\n self.activation = nn.ReLU(inplace=True)\n elif activation_fn == \"Leaky_ReLU\":\n self.activation = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n elif activation_fn == \"ELU\":\n self.activation = nn.ELU(alpha=1.0, inplace=True)\n elif activation_fn == \"GELU\":\n self.activation = nn.GELU()\n else:\n raise NotImplementedError\n\n self.average_pooling = nn.AvgPool2d(2)\n\n\n def forward(self, x):\n x0 = x\n\n x = self.conv2d1(x)\n if self.d_spectral_norm is False:\n x = self.bn1(x)\n x = self.activation(x)\n x = self.conv2d2(x)\n x = self.average_pooling(x)\n\n x0 = self.average_pooling(x0)\n if self.d_spectral_norm is False:\n x0 = self.bn0(x0)\n x0 = self.conv2d0(x0)\n\n out = x + x0\n return out\n\n\nclass DiscBlock(nn.Module):\n def __init__(self, in_channels, out_channels, d_spectral_norm, activation_fn, downsample=True):\n super(DiscBlock, self).__init__()\n self.d_spectral_norm = d_spectral_norm\n self.downsample = downsample\n\n if activation_fn == \"ReLU\":\n self.activation = nn.ReLU(inplace=True)\n elif activation_fn == \"Leaky_ReLU\":\n self.activation = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n elif activation_fn == \"ELU\":\n self.activation = nn.ELU(alpha=1.0, inplace=True)\n elif activation_fn == \"GELU\":\n self.activation = nn.GELU()\n else:\n raise NotImplementedError\n\n self.ch_mismatch = False\n if in_channels != out_channels:\n self.ch_mismatch = True\n\n if d_spectral_norm:\n if self.ch_mismatch or downsample:\n self.conv2d0 = snconv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1, padding=0)\n self.conv2d1 = snconv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1)\n self.conv2d2 = snconv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1)\n else:\n if self.ch_mismatch or downsample:\n self.conv2d0 = conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1, padding=0)\n self.conv2d1 = conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1)\n self.conv2d2 = conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1)\n\n if self.ch_mismatch or downsample:\n self.bn0 = batchnorm_2d(in_features=in_channels)\n self.bn1 = batchnorm_2d(in_features=in_channels)\n self.bn2 = batchnorm_2d(in_features=out_channels)\n\n self.average_pooling = nn.AvgPool2d(2)\n\n\n def forward(self, x):\n x0 = x\n if self.d_spectral_norm is False:\n x = self.bn1(x)\n x = self.activation(x)\n x = self.conv2d1(x)\n if self.d_spectral_norm is False:\n x = self.bn2(x)\n x = self.activation(x)\n x = self.conv2d2(x)\n if self.downsample:\n x = self.average_pooling(x)\n\n if self.downsample or self.ch_mismatch:\n if self.d_spectral_norm is False:\n x0 = self.bn0(x0)\n x0 = self.conv2d0(x0)\n if self.downsample:\n x0 = self.average_pooling(x0)\n\n out = x + x0\n return out\n\n\nclass Discriminator(nn.Module):\n \"\"\"Discriminator.\"\"\"\n def __init__(self, img_size, d_conv_dim, d_spectral_norm, attention, attention_after_nth_dis_block, activation_fn, conditional_strategy,\n hypersphere_dim, num_classes, nonlinear_embed, normalize_embed, initialize, D_depth, mixed_precision):\n super(Discriminator, self).__init__()\n d_in_dims_collection = {\"32\": [3] + [d_conv_dim*2, d_conv_dim*2, d_conv_dim*2],\n \"64\": [3] +[d_conv_dim*2, d_conv_dim*4, d_conv_dim*8, d_conv_dim*16],\n \"128\": [3] +[d_conv_dim, d_conv_dim*2, d_conv_dim*4, d_conv_dim*8, d_conv_dim*16],\n \"256\": [3] +[d_conv_dim, d_conv_dim*2, d_conv_dim*4, d_conv_dim*8, d_conv_dim*8, d_conv_dim*16],\n \"512\": [3] +[d_conv_dim, d_conv_dim, d_conv_dim*2, d_conv_dim*4, d_conv_dim*8, d_conv_dim*8, d_conv_dim*16]}\n\n d_out_dims_collection = {\"32\": [d_conv_dim*2, d_conv_dim*2, d_conv_dim*2, d_conv_dim*2],\n \"64\": [d_conv_dim*2, d_conv_dim*4, d_conv_dim*8, d_conv_dim*16, d_conv_dim*16],\n \"128\": [d_conv_dim, d_conv_dim*2, d_conv_dim*4, d_conv_dim*8, d_conv_dim*16, d_conv_dim*16],\n \"256\": [d_conv_dim, d_conv_dim*2, d_conv_dim*4, d_conv_dim*8, d_conv_dim*8, d_conv_dim*16, d_conv_dim*16],\n \"512\": [d_conv_dim, d_conv_dim, d_conv_dim*2, d_conv_dim*4, d_conv_dim*8, d_conv_dim*8, d_conv_dim*16, d_conv_dim*16]}\n\n d_down = {\"32\": [True, True, False, False],\n \"64\": [True, True, True, True, False],\n \"128\": [True, True, True, True, True, False],\n \"256\": [True, True, True, True, True, True, False],\n \"512\": [True, True, True, True, True, True, True, False]}\n\n self.nonlinear_embed = nonlinear_embed\n self.normalize_embed = normalize_embed\n self.conditional_strategy = conditional_strategy\n self.mixed_precision = mixed_precision\n\n self.in_dims = d_in_dims_collection[str(img_size)]\n self.out_dims = d_out_dims_collection[str(img_size)]\n down = d_down[str(img_size)]\n\n self.blocks = []\n for index in range(len(self.in_dims)):\n if index == 0:\n self.blocks += [[DiscOptBlock(in_channels=self.in_dims[index],\n out_channels=self.out_dims[index],\n d_spectral_norm=d_spectral_norm,\n activation_fn=activation_fn)]]\n else:\n self.blocks += [[DiscBlock(in_channels=self.in_dims[index],\n out_channels=self.out_dims[index],\n d_spectral_norm=d_spectral_norm,\n activation_fn=activation_fn,\n downsample=down[index])]]\n\n if index+1 == attention_after_nth_dis_block and attention is True:\n self.blocks += [[Self_Attn(self.out_dims[index], d_spectral_norm)]]\n\n self.blocks = nn.ModuleList([nn.ModuleList(block) for block in self.blocks])\n\n if activation_fn == \"ReLU\":\n self.activation = nn.ReLU(inplace=True)\n elif activation_fn == \"Leaky_ReLU\":\n self.activation = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n elif activation_fn == \"ELU\":\n self.activation = nn.ELU(alpha=1.0, inplace=True)\n elif activation_fn == \"GELU\":\n self.activation = nn.GELU()\n else:\n raise NotImplementedError\n\n if d_spectral_norm:\n self.linear1 = snlinear(in_features=self.out_dims[-1], out_features=1)\n if self.conditional_strategy in ['ContraGAN', 'Proxy_NCA_GAN', 'NT_Xent_GAN']:\n self.linear2 = snlinear(in_features=self.out_dims[-1], out_features=hypersphere_dim)\n if self.nonlinear_embed:\n self.linear3 = snlinear(in_features=hypersphere_dim, out_features=hypersphere_dim)\n self.embedding = sn_embedding(num_classes, hypersphere_dim)\n elif self.conditional_strategy == 'ProjGAN':\n self.embedding = sn_embedding(num_classes, self.out_dims[-1])\n elif self.conditional_strategy == 'ACGAN':\n self.linear4 = snlinear(in_features=self.out_dims[-1], out_features=num_classes)\n else:\n pass\n else:\n self.linear1 = linear(in_features=self.out_dims[-1], out_features=1)\n if self.conditional_strategy in ['ContraGAN', 'Proxy_NCA_GAN', 'NT_Xent_GAN']:\n self.linear2 = linear(in_features=self.out_dims[-1], out_features=hypersphere_dim)\n if self.nonlinear_embed:\n self.linear3 = linear(in_features=hypersphere_dim, out_features=hypersphere_dim)\n self.embedding = embedding(num_classes, hypersphere_dim)\n elif self.conditional_strategy == 'ProjGAN':\n self.embedding = embedding(num_classes, self.out_dims[-1])\n elif self.conditional_strategy == 'ACGAN':\n self.linear4 = linear(in_features=self.out_dims[-1], out_features=num_classes)\n else:\n pass\n\n # Weight init\n if initialize is not False:\n init_weights(self.modules, initialize)\n\n\n def forward(self, x, label, evaluation=False):\n with torch.cuda.amp.autocast() if self.mixed_precision is True and evaluation is False else dummy_context_mgr() as mp:\n h = x\n for index, blocklist in enumerate(self.blocks):\n for block in blocklist:\n h = block(h)\n h = self.activation(h)\n h = torch.sum(h, dim=[2,3])\n\n if self.conditional_strategy == 'no':\n authen_output = torch.squeeze(self.linear1(h))\n return authen_output\n\n elif self.conditional_strategy in ['ContraGAN', 'Proxy_NCA_GAN', 'NT_Xent_GAN']:\n authen_output = torch.squeeze(self.linear1(h))\n cls_proxy = self.embedding(label)\n cls_embed = self.linear2(h)\n if self.nonlinear_embed:\n cls_embed = self.linear3(self.activation(cls_embed))\n if self.normalize_embed:\n cls_proxy = F.normalize(cls_proxy, dim=1)\n cls_embed = F.normalize(cls_embed, dim=1)\n return cls_proxy, cls_embed, authen_output\n\n elif self.conditional_strategy == 'ProjGAN':\n authen_output = torch.squeeze(self.linear1(h))\n proj = torch.sum(torch.mul(self.embedding(label), h), 1)\n return authen_output + proj\n\n elif self.conditional_strategy == 'ACGAN':\n authen_output = torch.squeeze(self.linear1(h))\n cls_output = self.linear4(h)\n return cls_output, authen_output\n\n else:\n raise NotImplementedError\n", "# PyTorch StudioGAN: https://github.com/POSTECH-CVLab/PyTorch-StudioGAN\n# The MIT License (MIT)\n# See license file or visit https://github.com/POSTECH-CVLab/PyTorch-StudioGAN for details\n\n# metrics/Accuracy.py\n\n\nimport numpy as np\nimport math\nfrom scipy import linalg\nfrom tqdm import tqdm\n\nfrom utils.sample import sample_latents\nfrom utils.losses import latent_optimise\n\nimport torch\nfrom torch.nn import DataParallel\n\n\n\ndef calculate_accuracy(dataloader, generator, discriminator, D_loss, num_evaluate, truncated_factor, prior, latent_op,\n latent_op_step, latent_op_alpha, latent_op_beta, device, cr, eval_generated_sample=False):\n data_iter = iter(dataloader)\n batch_size = dataloader.batch_size\n\n if isinstance(generator, DataParallel):\n z_dim = generator.module.z_dim\n num_classes = generator.module.num_classes\n conditional_strategy = discriminator.module.conditional_strategy\n else:\n z_dim = generator.z_dim\n num_classes = generator.num_classes\n conditional_strategy = discriminator.conditional_strategy\n\n total_batch = num_evaluate//batch_size\n\n if D_loss.__name__ in [\"loss_dcgan_dis\", \"loss_lsgan_dis\"]:\n cutoff = 0.5\n elif D_loss.__name__ == \"loss_hinge_dis\":\n cutoff = 0.0\n elif D_loss.__name__ == \"loss_wgan_dis\":\n raise NotImplementedError\n\n print(\"Calculating Accuracies....\")\n\n if eval_generated_sample:\n for batch_id in tqdm(range(total_batch)):\n zs, fake_labels = sample_latents(prior, batch_size, z_dim, truncated_factor, num_classes, None, device)\n if latent_op:\n zs = latent_optimise(zs, fake_labels, generator, discriminator, conditional_strategy, latent_op_step,\n 1.0, latent_op_alpha, latent_op_beta, False, device)\n\n real_images, real_labels = next(data_iter)\n real_images, real_labels = real_images.to(device), real_labels.to(device)\n\n fake_images = generator(zs, fake_labels, evaluation=True)\n\n with torch.no_grad():\n if conditional_strategy in [\"ContraGAN\", \"Proxy_NCA_GAN\", \"NT_Xent_GAN\"]:\n _, _, dis_out_fake = discriminator(fake_images, fake_labels)\n _, _, dis_out_real = discriminator(real_images, real_labels)\n elif conditional_strategy == \"ACGAN\":\n _, dis_out_fake = discriminator(fake_images, fake_labels)\n _, dis_out_real = discriminator(real_images, real_labels)\n elif conditional_strategy == \"ProjGAN\" or conditional_strategy == \"no\":\n dis_out_fake = discriminator(fake_images, fake_labels)\n dis_out_real = discriminator(real_images, real_labels)\n else:\n raise NotImplementedError\n\n dis_out_fake = dis_out_fake.detach().cpu().numpy()\n dis_out_real = dis_out_real.detach().cpu().numpy()\n\n if batch_id == 0:\n confid = np.concatenate((dis_out_fake, dis_out_real), axis=0)\n confid_label = np.concatenate(([0.0]*len(dis_out_fake), [1.0]*len(dis_out_real)), axis=0)\n else:\n confid = np.concatenate((confid, dis_out_fake, dis_out_real), axis=0)\n confid_label = np.concatenate((confid_label, [0.0]*len(dis_out_fake), [1.0]*len(dis_out_real)), axis=0)\n\n real_confid = confid[confid_label==1.0]\n fake_confid = confid[confid_label==0.0]\n\n true_positive = real_confid[np.where(real_confid>cutoff)]\n true_negative = fake_confid[np.where(fake_confid<cutoff)]\n\n only_real_acc = len(true_positive)/len(real_confid)\n only_fake_acc = len(true_negative)/len(fake_confid)\n\n return only_real_acc, only_fake_acc\n else:\n for batch_id in tqdm(range(total_batch)):\n real_images, real_labels = next(data_iter)\n real_images, real_labels = real_images.to(device), real_labels.to(device)\n\n with torch.no_grad():\n if conditional_strategy in [\"ContraGAN\", \"Proxy_NCA_GAN\", \"NT_Xent_GAN\"]:\n _, _, dis_out_real = discriminator(real_images, real_labels)\n elif conditional_strategy == \"ACGAN\":\n _, dis_out_real = discriminator(real_images, real_labels)\n elif conditional_strategy == \"ProjGAN\" or conditional_strategy == \"ProjGAN_adv\" or conditional_strategy == \"no\":\n dis_out_real = discriminator(real_images, real_labels)\n else:\n raise NotImplementedError\n\n dis_out_real = dis_out_real.detach().cpu().numpy()\n\n if batch_id == 0:\n confid = dis_out_real\n confid_label = np.asarray([1.0]*len(dis_out_real), np.float32)\n else:\n confid = np.concatenate((confid, dis_out_real), axis=0)\n confid_label = np.concatenate((confid_label, [1.0]*len(dis_out_real)), axis=0)\n\n real_confid = confid[confid_label==1.0]\n true_positive = real_confid[np.where(real_confid>cutoff)]\n only_real_acc = len(true_positive)/len(real_confid)\n\n return only_real_acc\n" ]
[ [ "torch.mean", "torch.sign", "numpy.asarray", "torch.utils.data.DataLoader", "numpy.fft.fftshift", "torch.cuda.amp.autocast", "numpy.concatenate", "torch.no_grad", "torch.save", "torch.nn.CrossEntropyLoss", "torch.randn", "scipy.ndimage.median_filter", "torch.from_numpy", "torch.tensor", "torch.nn.functional.relu", "torch.square", "torch.rand", "torch.autograd.grad", "torch.unsqueeze", "torch.cuda.amp.GradScaler", "torch.hub.load", "numpy.abs", "numpy.shape", "torch.nn.DataParallel", "torch.nn.MSELoss" ], [ "torch.mean", "torch.sign", "numpy.asarray", "torch.utils.data.DataLoader", "numpy.fft.fftshift", "torch.cuda.amp.autocast", "numpy.concatenate", "torch.no_grad", "torch.save", "torch.nn.CrossEntropyLoss", "torch.randn", "scipy.ndimage.median_filter", "torch.from_numpy", "torch.tensor", "torch.nn.functional.relu", "torch.square", "torch.rand", "torch.autograd.grad", "torch.unsqueeze", "torch.cuda.amp.GradScaler", "torch.hub.load", "numpy.abs", "numpy.shape", "torch.nn.DataParallel", "torch.nn.MSELoss" ], [ "torch.nn.functional.normalize", "torch.nn.GELU", "torch.nn.ModuleList", "torch.nn.ELU", "torch.sum", "torch.nn.Tanh", "torch.cuda.amp.autocast", "torch.nn.AvgPool2d", "torch.nn.LeakyReLU", "torch.nn.functional.interpolate", "torch.nn.ReLU" ], [ "numpy.concatenate", "torch.no_grad", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] }, { "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": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
KuangenZhang/pytorch_geometric
[ "0bfc79a5eaccfcd16a82395e8578a90c5e44759f" ]
[ "benchmark/points/edge_cnn_ke.py" ]
[ "import argparse\nimport torch\nimport torch.nn.functional as F\nfrom torch.nn import Sequential as Seq, Linear as Lin, ReLU, LeakyReLU\nfrom torch_geometric.nn import DynamicEdgeConv, global_max_pool\n\nfrom datasets import get_dataset\nfrom train_eval import run\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--epochs', type=int, default=200)\nparser.add_argument('--batch_size', type=int, default=24)\nparser.add_argument('--lr', type=float, default=0.001)\nparser.add_argument('--lr_decay_factor', type=float, default=0.5)\nparser.add_argument('--lr_decay_step_size', type=int, default=50)\nparser.add_argument('--weight_decay', type=float, default=0)\nargs = parser.parse_args()\n\n\nclass Net(torch.nn.Module):\n def __init__(self, num_classes):\n super(Net, self).__init__()\n\n nn = Seq(Lin(6, 64), LeakyReLU(negative_slope=0.2),\n Lin(64, 64), LeakyReLU(negative_slope=0.2),\n Lin(64, 64), LeakyReLU(negative_slope=0.2))\n self.conv1 = DynamicEdgeConv(nn, k=20, aggr='max')\n\n nn = Seq(\n Lin(128, 128), LeakyReLU(negative_slope=0.2),\n Lin(128, 128), LeakyReLU(negative_slope=0.2),\n Lin(128, 256), LeakyReLU(negative_slope=0.2))\n self.conv2 = DynamicEdgeConv(nn, k=20, aggr='max')\n\n self.lin0 = Lin(256, 512)\n\n self.lin1 = Lin(512, 256)\n self.lin2 = Lin(256, 256)\n self.lin3 = Lin(256, num_classes)\n\n def forward(self, pos, batch):\n x = self.conv1(pos, batch)\n x = self.conv2(x, batch)\n\n x = F.relu(self.lin0(x))\n\n x = global_max_pool(x, batch)\n\n x = F.relu(self.lin1(x))\n x = F.relu(self.lin2(x))\n x = F.dropout(x, p=0.5, training=self.training)\n x = self.lin3(x)\n return F.log_softmax(x, dim=-1)\n\n\ntrain_dataset, test_dataset = get_dataset(num_points=1024)\nmodel = Net(train_dataset.num_classes)\nrun(train_dataset, test_dataset, model, args.epochs, args.batch_size, args.lr,\n args.lr_decay_factor, args.lr_decay_step_size, args.weight_decay)\n" ]
[ [ "torch.nn.Linear", "torch.nn.LeakyReLU", "torch.nn.functional.log_softmax", "torch.nn.functional.dropout" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
noahl/tensorflow
[ "b95d8cce7323d328565378e0d60d72603393f87d", "b95d8cce7323d328565378e0d60d72603393f87d" ]
[ "tensorflow/python/ops/standard_ops.py", "tensorflow/contrib/lite/testing/generate_examples.py" ]
[ "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n# pylint: disable=unused-import\n\"\"\"Import names of Tensor Flow standard Ops.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys as _sys\n\n# pylint: disable=g-bad-import-order\n# Imports the following modules so that @RegisterGradient get executed.\nfrom tensorflow.python.ops import array_grad\nfrom tensorflow.python.ops import cudnn_rnn_grad\nfrom tensorflow.python.ops import data_flow_grad\nfrom tensorflow.python.ops import manip_grad\nfrom tensorflow.python.ops import math_grad\nfrom tensorflow.python.ops import sparse_grad\nfrom tensorflow.python.ops import spectral_grad\nfrom tensorflow.python.ops import state_grad\nfrom tensorflow.python.ops import tensor_array_grad\nfrom tensorflow.python.util.all_util import remove_undocumented\n\n\n# go/tf-wildcard-import\n# pylint: disable=wildcard-import\nfrom tensorflow.python.ops.array_ops import *\nfrom tensorflow.python.ops.check_ops import *\nfrom tensorflow.python.ops.clip_ops import *\nfrom tensorflow.python.ops.special_math_ops import *\n# TODO(vrv): Switch to import * once we're okay with exposing the module.\nfrom tensorflow.python.ops.confusion_matrix import confusion_matrix\nfrom tensorflow.python.ops.control_flow_ops import Assert\nfrom tensorflow.python.ops.control_flow_ops import case\nfrom tensorflow.python.ops.control_flow_ops import cond\nfrom tensorflow.python.ops.control_flow_ops import group\nfrom tensorflow.python.ops.control_flow_ops import no_op\nfrom tensorflow.python.ops.control_flow_ops import tuple # pylint: disable=redefined-builtin\n# pylint: enable=redefined-builtin\nfrom tensorflow.python.ops.control_flow_ops import while_loop\nfrom tensorflow.python.ops.data_flow_ops import *\nfrom tensorflow.python.ops.functional_ops import *\nfrom tensorflow.python.ops.gradients import *\nfrom tensorflow.python.ops.histogram_ops import *\nfrom tensorflow.python.ops.init_ops import *\nfrom tensorflow.python.ops.io_ops import *\nfrom tensorflow.python.ops.linalg_ops import *\nfrom tensorflow.python.ops.logging_ops import Print\nfrom tensorflow.python.ops.logging_ops import get_summary_op\nfrom tensorflow.python.ops.logging_ops import timestamp\nfrom tensorflow.python.ops.lookup_ops import initialize_all_tables\nfrom tensorflow.python.ops.lookup_ops import tables_initializer\nfrom tensorflow.python.ops.manip_ops import *\nfrom tensorflow.python.ops.math_ops import *\nfrom tensorflow.python.ops.numerics import *\nfrom tensorflow.python.ops.parsing_ops import *\nfrom tensorflow.python.ops.partitioned_variables import *\nfrom tensorflow.python.ops.random_ops import *\nfrom tensorflow.python.ops.script_ops import py_func\nfrom tensorflow.python.ops.session_ops import *\nfrom tensorflow.python.ops.sparse_ops import *\nfrom tensorflow.python.ops.state_ops import assign\nfrom tensorflow.python.ops.state_ops import assign_add\nfrom tensorflow.python.ops.state_ops import assign_sub\nfrom tensorflow.python.ops.state_ops import count_up_to\nfrom tensorflow.python.ops.state_ops import scatter_add\nfrom tensorflow.python.ops.state_ops import scatter_div\nfrom tensorflow.python.ops.state_ops import scatter_mul\nfrom tensorflow.python.ops.state_ops import scatter_sub\nfrom tensorflow.python.ops.state_ops import scatter_min\nfrom tensorflow.python.ops.state_ops import scatter_max\nfrom tensorflow.python.ops.state_ops import scatter_update\nfrom tensorflow.python.ops.state_ops import scatter_nd_add\nfrom tensorflow.python.ops.state_ops import scatter_nd_sub\n# TODO(simister): Re-enable once binary size increase due to scatter_nd\n# ops is under control.\n# from tensorflow.python.ops.state_ops import scatter_nd_mul\n# from tensorflow.python.ops.state_ops import scatter_nd_div\nfrom tensorflow.python.ops.state_ops import scatter_nd_update\nfrom tensorflow.python.ops.string_ops import *\nfrom tensorflow.python.ops.template import *\nfrom tensorflow.python.ops.tensor_array_ops import *\nfrom tensorflow.python.ops.variable_scope import *\nfrom tensorflow.python.ops.variables import *\n# pylint: enable=wildcard-import\n# pylint: enable=g-bad-import-order\n\n#### For use in remove_undocumented below:\nfrom tensorflow.python.framework import constant_op as _constant_op\nfrom tensorflow.python.ops import array_ops as _array_ops\nfrom tensorflow.python.ops import check_ops as _check_ops\nfrom tensorflow.python.ops import clip_ops as _clip_ops\nfrom tensorflow.python.ops import confusion_matrix as _confusion_matrix\nfrom tensorflow.python.ops import control_flow_ops as _control_flow_ops\nfrom tensorflow.python.ops import data_flow_ops as _data_flow_ops\nfrom tensorflow.python.ops import functional_ops as _functional_ops\nfrom tensorflow.python.ops import gradients as _gradients\nfrom tensorflow.python.ops import histogram_ops as _histogram_ops\nfrom tensorflow.python.ops import init_ops as _init_ops\nfrom tensorflow.python.ops import io_ops as _io_ops\nfrom tensorflow.python.ops import linalg_ops as _linalg_ops\nfrom tensorflow.python.ops import logging_ops as _logging_ops\nfrom tensorflow.python.ops import manip_ops as _manip_ops\nfrom tensorflow.python.ops import math_ops as _math_ops\nfrom tensorflow.python.ops import numerics as _numerics\nfrom tensorflow.python.ops import parsing_ops as _parsing_ops\nfrom tensorflow.python.ops import partitioned_variables as _partitioned_variables\nfrom tensorflow.python.ops import random_ops as _random_ops\nfrom tensorflow.python.ops import script_ops as _script_ops\nfrom tensorflow.python.ops import session_ops as _session_ops\nfrom tensorflow.python.ops import sparse_ops as _sparse_ops\nfrom tensorflow.python.ops import special_math_ops as _special_math_ops\nfrom tensorflow.python.ops import state_ops as _state_ops\nfrom tensorflow.python.ops import string_ops as _string_ops\nfrom tensorflow.python.ops import template as _template\nfrom tensorflow.python.ops import tensor_array_ops as _tensor_array_ops\nfrom tensorflow.python.ops import variable_scope as _variable_scope\nfrom tensorflow.python.ops import variables as _variables\n\n\n_allowed_symbols_math_ops = [\n # TODO(drpng): decide if we want to reference these in the documentation.\n \"reduced_shape\",\n \"sparse_segment_mean_grad\",\n \"sparse_segment_sqrt_n_grad\",\n\n # Legacy: will be removed.\n \"arg_max\",\n \"arg_min\",\n \"lin_space\",\n \"sparse_matmul\", # Use tf.matmul.\n # Deprecated (see versions.h):\n \"batch_fft\",\n \"batch_fft2d\",\n \"batch_fft3d\",\n \"batch_ifft\",\n \"batch_ifft2d\",\n \"batch_ifft3d\",\n \"mul\", # use tf.multiply instead.\n \"neg\", # use tf.negative instead.\n \"sub\", # use tf.subtract instead.\n\n # These are documented in nn.\n # We are not importing nn because it would create a circular dependency.\n \"sigmoid\",\n \"log_sigmoid\",\n \"tanh\",\n]\n\n_allowed_symbols_array_ops = [\n # TODO(drpng): make sure they are documented.\n # Scalars:\n \"NEW_AXIS\",\n \"SHRINK_AXIS\",\n \"newaxis\",\n\n # Documented in training.py.\n # I do not import train, to avoid circular dependencies.\n # TODO(drpng): this is defined in gen_array_ops, clearly not the right\n # place.\n \"stop_gradient\",\n\n # See gen_docs_combined for tf.copy documentation.\n \"copy\",\n\n ## TODO(drpng): make them inaccessible directly.\n ## TODO(drpng): Below, to-doc means that we need to find an appropriate\n ## documentation section to reference.\n ## For re-exporting to tf.*:\n \"constant\",\n \"edit_distance\", # to-doc\n # From gen_array_ops:\n \"copy_host\", # to-doc\n \"immutable_const\", # to-doc\n \"invert_permutation\", # to-doc\n \"quantize_and_dequantize\", # to-doc\n\n # TODO(drpng): legacy symbols to be removed.\n \"batch_matrix_diag\",\n \"batch_matrix_band_part\",\n \"batch_matrix_diag_part\",\n \"batch_matrix_set_diag\",\n]\n\n_allowed_symbols_partitioned_variables = [\n \"PartitionedVariable\", # Requires doc link.\n # Legacy.\n \"create_partitioned_variables\",\n \"variable_axis_size_partitioner\",\n \"min_max_variable_partitioner\",\n \"fixed_size_partitioner\",\n]\n\n_allowed_symbols_control_flow_ops = [\n # TODO(drpng): Find a place in the documentation to reference these or\n # remove.\n \"control_trigger\",\n \"loop_cond\",\n \"merge\",\n \"switch\",\n]\n\n_allowed_symbols_functional_ops = [\n \"nest\", # Used by legacy code.\n]\n\n_allowed_symbols_gradients = [\n # Documented in training.py:\n # Not importing training.py to avoid complex graph dependencies.\n \"AggregationMethod\",\n \"GradientTape\",\n \"custom_gradient\",\n \"gradients\", # tf.gradients = gradients.gradients\n \"hessians\",\n]\n\n_allowed_symbols_clip_ops = [\n # Documented in training.py:\n # Not importing training.py to avoid complex graph dependencies.\n \"clip_by_average_norm\",\n \"clip_by_global_norm\",\n \"clip_by_norm\",\n \"clip_by_value\",\n \"global_norm\",\n]\n\n_allowed_symbols_logging_ops = [\n # Documented in training.py.\n # We are not importing training.py to avoid complex dependencies.\n \"audio_summary\",\n \"histogram_summary\",\n \"image_summary\",\n \"merge_all_summaries\",\n \"merge_summary\",\n \"scalar_summary\",\n\n # TODO(drpng): link in training.py if it should be documented.\n \"get_summary_op\",\n]\n\n_allowed_symbols_variable_scope_ops = [\n \"get_local_variable\", # Documented in framework package.\n]\n\n_allowed_symbols_misc = [\n \"deserialize_many_sparse\",\n \"parse_single_sequence_example\",\n \"serialize_many_sparse\",\n \"serialize_sparse\",\n \"confusion_matrix\",\n]\n\n_allowed_symbols = (_allowed_symbols_array_ops +\n _allowed_symbols_clip_ops +\n _allowed_symbols_control_flow_ops +\n _allowed_symbols_functional_ops +\n _allowed_symbols_gradients +\n _allowed_symbols_logging_ops +\n _allowed_symbols_math_ops +\n _allowed_symbols_variable_scope_ops +\n _allowed_symbols_misc +\n _allowed_symbols_partitioned_variables)\n\nremove_undocumented(__name__, _allowed_symbols, [\n _sys.modules[__name__],\n _array_ops,\n _check_ops,\n _clip_ops,\n _confusion_matrix,\n _control_flow_ops,\n _constant_op,\n _data_flow_ops,\n _functional_ops,\n _gradients,\n _histogram_ops,\n _init_ops,\n _io_ops,\n _linalg_ops,\n _logging_ops,\n _manip_ops,\n _math_ops,\n _numerics,\n _parsing_ops,\n _partitioned_variables,\n _random_ops,\n _script_ops,\n _session_ops,\n _sparse_ops,\n _special_math_ops,\n _state_ops,\n _string_ops,\n _template,\n _tensor_array_ops,\n _variable_scope,\n _variables,\n])\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# ==============================================================================\n\n\"\"\"Generate a series of TensorFlow graphs that become tflite test cases.\n\nUsage:\n\ngenerate_examples <output directory>\n\nbazel run //tensorflow/contrib/lite/testing:generate_examples\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport itertools\nimport os\nimport re\nimport sys\nimport tempfile\nimport traceback\nimport zipfile\nimport numpy as np\nfrom six import StringIO\nfrom six.moves import xrange\n\n# TODO(aselle): Disable GPU for now\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n\n# pylint: disable=g-import-not-at-top\nimport tensorflow as tf\nfrom google.protobuf import text_format\n# TODO(aselle): switch to TensorFlow's resource_loader\nfrom tensorflow.contrib.lite.testing import generate_examples_report as report_lib\nfrom tensorflow.python.framework import graph_util as tf_graph_util\nfrom tensorflow.python.ops import rnn\n\nparser = argparse.ArgumentParser(description=\"Script to generate TFLite tests.\")\nparser.add_argument(\"output_path\",\n help=\"Directory where the outputs will be go.\")\nparser.add_argument(\"--zip_to_output\",\n type=str,\n help=\"Particular zip to output.\",\n required=False)\nparser.add_argument(\"--toco\",\n type=str,\n help=\"Path to toco tool.\",\n required=True)\nparser.add_argument(\n \"--known_bugs_are_errors\",\n action=\"store_true\",\n help=(\"If a particular model is affected by a known bug,\"\n \" count it as a toco error.\"))\nparser.add_argument(\n \"--ignore_toco_errors\",\n action=\"store_true\",\n help=\"Raise an exception if any toco error is encountered.\")\nparser.add_argument(\n \"--save_graphdefs\",\n action=\"store_true\",\n help=\"Include intermediate graphdefs in the output zip files.\")\n\n\nRANDOM_SEED = 342\nTEST_INPUT_DEPTH = 3\n\n\n# A map from regular expression to bug number. Any test failure with label\n# matching the expression will be considered due to the corresponding bug.\nKNOWN_BUGS = {\n # TOCO doesn't support scalars as input.\n r\"relu.*input_shape=\\[\\]\": \"67587484\",\n r\"sigmoid.*input_shape=\\[\\]\": \"67645668\",\n # Concat doesn't work with a single input tensor\n r\"concat.*num_tensors=1\": \"67378344\",\n # Transposition in MatMul is not supported.\n r\"fully_connected.*transpose_.=True\": \"67586970\",\n # Softmax graphs are too complex.\n r\"softmax.*dim=0\": \"67749831\",\n r\"softmax.*input_shape=\\[1,3,4,3\\]\": \"67749831\",\n # SpaceToDepth only supports float32.\n r\"space_to_depth.*(float16|int32|uint8|int64)\": \"68018134\",\n # BatchToSpaceND only supports 4D tensors.\n r\"batch_to_space_nd.*input_shape=\\[8,2,2,2,1,1\\]\": \"70594733\",\n # Div will use floordiv.\n r\"div.*int32\": \"72051395\",\n # TOCO require matching dimensions in strided_slice.\n r\"strided_slice.*begin=\\[0\\].*end=\\[1\\].*\": \"73170889\",\n # No support for SplitV\n r\"split.*num_or_size_splits=\\[2,2\\]\": \"73377559\",\n # Needs support for dimensions other than the last one in argmax.\n r\"arg_max.*axis=0.*\": \"77546240\",\n r\"arg_max.*axis=1.*\": \"77546240\",\n r\"arg_max.*axis=2.*\": \"77546240\",\n}\n\n\nclass ExtraTocoOptions(object):\n \"\"\"Additonal toco options besides input, output, shape.\"\"\"\n\n def __init__(self):\n # Whether to ignore control dependency nodes.\n self.drop_control_dependency = False\n # Allow custom ops in the toco conversion.\n self.allow_custom_ops = False\n # Rnn states that are used to support rnn / lstm cells.\n self.rnn_states = None\n\n\ndef toco_options(data_types,\n input_arrays,\n output_arrays,\n shapes,\n extra_toco_options=ExtraTocoOptions()):\n \"\"\"Create TOCO options to process a model.\n\n Args:\n data_types: input and inference types used by TOCO.\n input_arrays: names of the input tensors\n output_arrays: name of the output tensors\n shapes: shapes of the input tensors\n extra_toco_options: additional toco options\n Returns:\n the options in a string.\n \"\"\"\n shape_str = \":\".join([\",\".join(str(y) for y in x) for x in shapes])\n inference_type = \"FLOAT\"\n # TODO(ahentz): if we get multi-input quantization to work we need this\n # to change\n if data_types[0] == \"QUANTIZED_UINT8\":\n inference_type = \"QUANTIZED_UINT8\"\n s = (\" --input_data_types=%s\" % \",\".join(data_types) +\n \" --inference_type=%s\" % inference_type +\n \" --input_format=TENSORFLOW_GRAPHDEF\" + \" --output_format=TFLITE\" +\n \" --input_arrays=%s\" % \",\".join(input_arrays) +\n \" --input_shapes=%s\" % shape_str +\n \" --output_arrays=%s\" % \",\".join(output_arrays))\n if extra_toco_options.drop_control_dependency:\n s += \" --drop_control_dependency\"\n if extra_toco_options.allow_custom_ops:\n s += \" --allow_custom_ops\"\n if extra_toco_options.rnn_states:\n s += (\" --rnn_states='\" + extra_toco_options.rnn_states + \"'\")\n return s\n\n\ndef write_examples(fp, examples):\n \"\"\"Given a list `examples`, write a text format representation.\n\n The file format is csv like with a simple repeated pattern. We would ike\n to use proto here, but we can't yet due to interfacing with the Android\n team using this format.\n\n Args:\n fp: File-like object to write to.\n examples: Example dictionary consiting of keys \"inputs\" and \"outputs\"\n \"\"\"\n\n def write_tensor(fp, x):\n \"\"\"Write tensor in file format supported by TFLITE example.\"\"\"\n fp.write(\"dtype,%s\\n\" % x.dtype)\n fp.write(\"shape,\" + \",\".join(map(str, x.shape)) + \"\\n\")\n # Output 9 digits after the point to ensure the precision is good enough.\n values = [\"{:.9f}\".format(value) for value in list(x.flatten())]\n fp.write(\"values,\" + \",\".join(values) + \"\\n\")\n\n fp.write(\"test_cases,%d\\n\" % len(examples))\n for example in examples:\n fp.write(\"inputs,%d\\n\" % len(example[\"inputs\"]))\n for i in example[\"inputs\"]:\n write_tensor(fp, i)\n fp.write(\"outputs,%d\\n\" % len(example[\"outputs\"]))\n for i in example[\"outputs\"]:\n write_tensor(fp, i)\n\n\ndef write_test_cases(fp, model_name, examples):\n \"\"\"Given a dictionary of `examples`, write a text format representation.\n\n The file format is protocol-buffer-like, even though we don't use proto due\n to the needs of the Android team.\n\n Args:\n fp: File-like object to write to.\n model_name: Filename where the model was written to, relative to filename.\n examples: Example dictionary consiting of keys \"inputs\" and \"outputs\"\n \"\"\"\n\n fp.write(\"load_model: %s\\n\" % os.path.basename(model_name))\n for example in examples:\n fp.write(\"reshape {\\n\")\n for t in example[\"inputs\"]:\n fp.write(\" input: \\\"\" + \",\".join(map(str, t.shape)) + \"\\\"\\n\")\n fp.write(\"}\\n\")\n fp.write(\"invoke {\\n\")\n\n for t in example[\"inputs\"]:\n values = [\"{:.9f}\".format(value) for value in list(t.flatten())]\n fp.write(\" input: \\\"\" + \",\".join(values) + \"\\\"\\n\")\n for t in example[\"outputs\"]:\n values = [\"{:.9f}\".format(value) for value in list(t.flatten())]\n fp.write(\" output: \\\"\" + \",\".join(values) + \"\\\"\\n\")\n fp.write(\"}\\n\")\n\n\n_TF_TYPE_INFO = {\n tf.float32: (np.float32, \"FLOAT\"),\n tf.float16: (np.float16, \"FLOAT\"),\n tf.int32: (np.int32, \"INT32\"),\n tf.uint8: (np.uint8, \"QUANTIZED_UINT8\"),\n tf.int64: (np.int64, \"INT64\"),\n}\n\n\ndef create_tensor_data(dtype, shape, min_value=-100, max_value=100):\n \"\"\"Build tensor data spreading the range [min_value, max_value).\"\"\"\n\n if dtype in _TF_TYPE_INFO:\n dtype = _TF_TYPE_INFO[dtype][0]\n\n if dtype in (tf.float32, tf.float16):\n value = (max_value-min_value)*np.random.random_sample(shape)+min_value\n elif dtype in (tf.int32, tf.uint8, tf.int64):\n value = np.random.randint(min_value, max_value+1, shape)\n return value.astype(dtype)\n\n\ndef freeze_graph(session, outputs):\n \"\"\"Freeze the current graph.\n\n Args:\n session: Tensorflow sessions containing the graph\n outputs: List of output tensors\n\n Returns:\n The frozen graph_def.\n \"\"\"\n return tf_graph_util.convert_variables_to_constants(\n session, session.graph.as_graph_def(), [x.op.name for x in outputs])\n\n\ndef make_control_dep_tests(zip_path):\n \"\"\"Make a set of tests that use control dependencies.\"\"\"\n\n test_parameters = [{\n \"input_shape\": [[], [1, 1, 1, 1], [1, 15, 14, 1], [3, 15, 14, 3]],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n filter_value = tf.zeros((3, 3, TEST_INPUT_DEPTH, 8), tf.float32)\n assert_op = tf.assert_greater_equal(input_tensor, input_tensor - 1)\n with tf.control_dependencies([assert_op]):\n out = tf.nn.conv2d(input_tensor, filter_value,\n strides=(1, 1, 1, 1), padding=\"SAME\")\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(tf.float32, parameters[\"input_shape\"])\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n extra_toco_options = ExtraTocoOptions()\n extra_toco_options.drop_control_dependency = True\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs,\n extra_toco_options)\n\n\ndef toco_convert(graph_def_str, input_tensors, output_tensors,\n extra_toco_options):\n \"\"\"Convert a model's graph def into a tflite model.\n\n NOTE: this currently shells out to the toco binary, but we would like\n convert to Python API tooling in the future.\n\n Args:\n graph_def_str: Graph def proto in serialized string format.\n input_tensors: List of input tensor tuples `(name, shape, type)`.\n output_tensors: List of output tensors (names).\n extra_toco_options: Additional toco options.\n\n Returns:\n output tflite model, log_txt from conversion\n or None, log_txt if it did not convert properly.\n \"\"\"\n data_types = [_TF_TYPE_INFO[x[2]][1] for x in input_tensors]\n opts = toco_options(\n data_types=data_types,\n input_arrays=[x[0] for x in input_tensors],\n shapes=[x[1] for x in input_tensors],\n output_arrays=output_tensors,\n extra_toco_options=extra_toco_options)\n\n with tempfile.NamedTemporaryFile() as graphdef_file, \\\n tempfile.NamedTemporaryFile() as output_file, \\\n tempfile.NamedTemporaryFile(\"w+\") as stdout_file:\n graphdef_file.write(graph_def_str)\n graphdef_file.flush()\n\n # TODO(aselle): Switch this to subprocess at some point.\n cmd = (\"%s --input_file=%s --output_file=%s %s > %s 2>&1\" %\n (bin_path, graphdef_file.name, output_file.name, opts,\n stdout_file.name))\n exit_code = os.system(cmd)\n log = (\n cmd + \"exited with code %d\" % exit_code + \"\\n------------------\\n\" +\n stdout_file.read())\n return (None if exit_code != 0 else output_file.read()), log\n\n\ndef normalize_output_name(output_name):\n \"\"\"Remove :0 suffix from tensor names.\"\"\"\n return output_name.split(\":\")[0] if output_name.endswith(\n \":0\") else output_name\n\n\ndef make_zip_of_tests(zip_path,\n test_parameters,\n make_graph,\n make_test_inputs,\n extra_toco_options=ExtraTocoOptions(),\n use_frozen_graph=False):\n \"\"\"Helper to make a zip file of a bunch of TensorFlow models.\n\n This does a cartestian product of the dictionary of test_parameters and\n calls make_graph() for each item in the cartestian product set.\n If the graph is built successfully, then make_test_inputs() is called to\n build expected input/output value pairs. The model is then converted to tflite\n with toco, and the examples are serialized with the tflite model into a zip\n file (2 files per item in the cartesian product set).\n\n Args:\n zip_path: Path of zip file to write\n test_parameters: Dictionary mapping to lists for each parameter.\n e.g. `{\"strides\": [[1,3,3,1], [1,2,2,1]], \"foo\": [1.2, 1.3]}`\n make_graph: function that takes current parameters and returns tuple\n `[input1, input2, ...], [output1, output2, ...]`\n make_test_inputs: function taking `curr_params`, `session`, `input_tensors`,\n `output_tensors` and returns tuple `(input_values, output_values)`.\n extra_toco_options: Additional toco options.\n use_frozen_graph: Whether or not freeze graph before toco converter.\n\n Raises:\n RuntimeError: if there are toco errors that can't be ignored.\n \"\"\"\n\n # TODO(aselle): Make this allow multiple inputs outputs.\n archive = zipfile.PyZipFile(zip_path, \"w\")\n zip_manifest = []\n convert_report = []\n toco_errors = 0\n for parameters in test_parameters:\n keys = parameters.keys()\n for curr in itertools.product(*parameters.values()):\n label = zip_path.replace(\".zip\", \"\") + (\",\".join(\n \"%s=%r\" % z for z in sorted(zip(keys, curr))).replace(\" \", \"\"))\n if label[0] == \"/\":\n label = label[1:]\n param_dict = dict(zip(keys, curr))\n\n def build_example(label, param_dict_real):\n \"\"\"Build the model with parameter values set in param_dict_real.\n\n Args:\n label: Label of the model (i.e. the filename in the zip).\n param_dict_real: Parameter dictionary (arguments to the factories\n make_graph and make_test_inputs)\n Returns:\n (tflite_model_binary, report) where tflite_model_binary is the\n serialized flatbuffer as a string and report is a dictionary with\n keys `toco_log` (log of toco conversion), `tf_log` (log of tf\n conversion), `toco` (a string of success status of the conversion),\n `tf` (a string success status of the conversion).\n \"\"\"\n\n np.random.seed(RANDOM_SEED)\n report = {\"toco\": report_lib.NOTRUN, \"tf\": report_lib.FAILED}\n\n # Build graph\n report[\"tf_log\"] = \"\"\n report[\"toco_log\"] = \"\"\n tf.reset_default_graph()\n\n with tf.device(\"/cpu:0\"):\n try:\n inputs, outputs = make_graph(param_dict_real)\n except (tf.errors.UnimplementedError, tf.errors.InvalidArgumentError,\n ValueError):\n report[\"tf_log\"] += traceback.format_exc()\n return None, report\n\n sess = tf.Session()\n try:\n baseline_inputs, baseline_outputs = (make_test_inputs(\n param_dict_real, sess, inputs, outputs))\n except (tf.errors.UnimplementedError, tf.errors.InvalidArgumentError,\n ValueError):\n report[\"tf_log\"] += traceback.format_exc()\n return None, report\n report[\"toco\"] = report_lib.FAILED\n report[\"tf\"] = report_lib.SUCCESS\n # Convert graph to toco\n input_tensors = [(input_tensor.name.split(\":\")[0],\n input_tensor.get_shape(), input_tensor.dtype)\n for input_tensor in inputs]\n output_tensors = [normalize_output_name(out.name) for out in outputs]\n graph_def = freeze_graph(\n sess,\n tf.global_variables() + inputs +\n outputs) if use_frozen_graph else sess.graph_def\n tflite_model_binary, toco_log = toco_convert(\n graph_def.SerializeToString(), input_tensors, output_tensors,\n extra_toco_options)\n report[\"toco\"] = (report_lib.SUCCESS if tflite_model_binary is not None\n else report_lib.FAILED)\n report[\"toco_log\"] = toco_log\n\n if FLAGS.save_graphdefs:\n archive.writestr(label + \".pb\",\n text_format.MessageToString(graph_def),\n zipfile.ZIP_DEFLATED)\n\n if tflite_model_binary:\n archive.writestr(label + \".bin\", tflite_model_binary,\n zipfile.ZIP_DEFLATED)\n example = {\"inputs\": baseline_inputs, \"outputs\": baseline_outputs}\n\n example_fp = StringIO()\n write_examples(example_fp, [example])\n archive.writestr(label + \".inputs\",\n example_fp.getvalue(), zipfile.ZIP_DEFLATED)\n\n example_fp2 = StringIO()\n write_test_cases(example_fp2, label + \".bin\", [example])\n archive.writestr(label + \"_tests.txt\",\n example_fp2.getvalue(), zipfile.ZIP_DEFLATED)\n\n zip_manifest.append(label + \"\\n\")\n\n return tflite_model_binary, report\n\n _, report = build_example(label, param_dict)\n\n if report[\"toco\"] == report_lib.FAILED:\n ignore_error = False\n if not FLAGS.known_bugs_are_errors:\n for pattern, bug_number in KNOWN_BUGS.items():\n if re.search(pattern, label):\n print(\"Ignored TOCO error due to bug %s\" % bug_number)\n ignore_error = True\n if not ignore_error:\n toco_errors += 1\n print(\"-----------------\\ntoco error!\\n%s\\n-----------------\\n\" %\n report[\"toco_log\"])\n\n convert_report.append((param_dict, report))\n report_io = StringIO()\n report_lib.make_report_table(report_io, zip_path, convert_report)\n archive.writestr(\"report.html\", report_io.getvalue())\n\n archive.writestr(\"manifest.txt\", \"\".join(zip_manifest), zipfile.ZIP_DEFLATED)\n\n # Log statistics of what succeeded\n total_conversions = len(convert_report)\n tf_success = sum(1 for x in convert_report\n if x[1][\"tf\"] == report_lib.SUCCESS)\n toco_success = sum(1 for x in convert_report\n if x[1][\"toco\"] == report_lib.SUCCESS)\n percent = 0\n if tf_success > 0:\n percent = float(toco_success) / float(tf_success) * 100.\n tf.logging.info((\"Archive %s Considered %d graphs, %d TF evaluated graphs \"\n \" and %d TOCO converted graphs (%.1f%%\"), zip_path,\n total_conversions, tf_success, toco_success, percent)\n\n if not FLAGS.ignore_toco_errors and toco_errors > 0:\n raise RuntimeError(\n \"Found %d errors while generating toco models\" % toco_errors)\n\n\ndef make_pool_tests(pool_op_in):\n \"\"\"Make a set of tests to do average pooling.\n\n Args:\n pool_op_in: TensorFlow pooling operation to test i.e. `tf.nn.avg_pool`.\n\n Returns:\n A function representing the true generator (after curried pool_op_in).\n \"\"\"\n\n pool_op = pool_op_in\n\n def f(zip_path):\n \"\"\"Actual function that generates examples.\n\n Args:\n zip_path: path to write zip to.\n \"\"\"\n\n # Chose a set of parameters\n test_parameters = [{\n \"ksize\": [[2, 1, 1, 2], [1, 1, 1, 1], [1, 1, 2, 1], [1, 10, 11, 1]],\n \"strides\": [[2, 1, 1, 2], [1, 1, 1, 1], [1, 1, 2, 1], [1, 10, 11, 1]],\n # TODO(aselle): should add in a degenerate shape (e.g. [1, 0, 1, 1]).\n \"input_shape\": [[], [1, 1, 1, 1], [1, 15, 14, 1], [3, 15, 14, 3]],\n \"padding\": [\"SAME\", \"VALID\"],\n \"data_format\": [\"NHWC\"], # TODO(aselle): NCHW would be good\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n out = pool_op(\n input_tensor,\n ksize=parameters[\"ksize\"],\n strides=parameters[\"strides\"],\n data_format=parameters[\"data_format\"],\n padding=parameters[\"padding\"])\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(tf.float32, parameters[\"input_shape\"])\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n return f\n\n\ndef make_l2_pool_tests(zip_path):\n make_pool_tests(make_l2_pool)(zip_path)\n\n\ndef make_avg_pool_tests(zip_path):\n make_pool_tests(tf.nn.avg_pool)(zip_path)\n\n\ndef make_max_pool_tests(zip_path):\n make_pool_tests(tf.nn.max_pool)(zip_path)\n\n\ndef make_relu_tests(zip_path):\n \"\"\"Make a set of tests to do relu.\"\"\"\n\n # Chose a set of parameters\n test_parameters = [{\n \"input_shape\": [[], [1], [2, 3], [1, 1, 1, 1], [1, 3, 4, 3],\n [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n out = tf.nn.relu(input_tensor)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(\n np.float32, parameters[\"input_shape\"], min_value=-4, max_value=10)\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_relu1_tests(zip_path):\n \"\"\"Make a set of tests to do relu1.\"\"\"\n\n # Chose a set of parameters\n test_parameters = [{\n \"input_shape\": [[], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3],\n [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n # Note that the following is not supported:\n # out = tf.maximum(-1.0, tf.minimum(input_tensor, 1.0))\n out = tf.minimum(1.0, tf.maximum(input_tensor, -1.0))\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(\n np.float32, parameters[\"input_shape\"], min_value=-3, max_value=10)\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_relu6_tests(zip_path):\n \"\"\"Make a set of tests to do relu6.\"\"\"\n\n # Chose a set of parameters\n test_parameters = [{\n \"input_shape\": [[], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3],\n [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n out = tf.nn.relu(input_tensor)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(\n np.float32, parameters[\"input_shape\"], min_value=-3, max_value=10)\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\n# This function tests various TensorFLow functions that generates Const op,\n# including `tf.ones`, `tf.zeros` and random functions.\ndef make_constant_tests(zip_path):\n \"\"\"Make a set of tests to do constant ops.\"\"\"\n\n test_parameters = [{\n \"dtype\": [tf.float32, tf.int32],\n \"input_shape\": [[1], [2], [1, 1, 1, 1], [2, 2, 2, 2]],\n }]\n\n def build_graph(parameters):\n # Since Toco & Tflite can't have a single constant op in the entire graph,\n # this test adds a zero tensor with a constant op tensor.\n input1 = tf.placeholder(dtype=parameters[\"dtype\"], name=\"input1\",\n shape=parameters[\"input_shape\"])\n out = tf.ones(parameters[\"input_shape\"], dtype=parameters[\"dtype\"]) + input1\n return [input1], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input1 = np.zeros(parameters[\"input_shape\"],\n dtype=_TF_TYPE_INFO[parameters[\"dtype\"]][0])\n return [input1], sess.run(outputs, feed_dict={inputs[0]: input1})\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_binary_op_tests(zip_path, binary_operator):\n \"\"\"Make a set of tests to do add with and without broadcast.\"\"\"\n\n # These parameters are split because we don't support broadcasting.\n test_parameters = [{\n \"dtype\": [tf.float32, tf.int32],\n \"input_shape_1\": [[1, 3, 4, 3]],\n \"input_shape_2\": [[1, 3, 4, 3]],\n \"activation\": [True]\n }, {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[5]],\n \"input_shape_2\": [[5]],\n \"activation\": [False, True]\n }, {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[1, 3, 4, 3]],\n \"input_shape_2\": [[3]],\n \"activation\": [True]\n }]\n\n def build_graph(parameters):\n \"\"\"Builds the graph given the current parameters.\"\"\"\n input1 = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input1\",\n shape=parameters[\"input_shape_1\"])\n input2 = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input2\",\n shape=parameters[\"input_shape_2\"])\n out = binary_operator(input1, input2)\n if parameters[\"activation\"]:\n out = tf.nn.relu(out)\n return [input1, input2], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n \"\"\"Builds operand inputs for op.\"\"\"\n input1 = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape_1\"])\n input2 = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape_2\"])\n return [input1, input2], sess.run(\n outputs, feed_dict={\n inputs[0]: input1,\n inputs[1]: input2\n })\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_mean_tests(zip_path):\n \"\"\"Make a set of tests to do mean.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32, tf.int32, tf.int64],\n \"input_shape\": [[3, 2, 4]],\n \"axis\": [\n None, 0, 1, 2, [0, 1], [0, 2], [1, 2], [0, 1, 2], [1, 0], [2, 0],\n [2, 1], [2, 1, 0], [2, 0, 1], -1, -2, -3, [1, -1], [0, -1], [-1, 0],\n [-1, -2, -3], [0, 0, 0], [2, 2, 0], [1, 0, -3, -3]\n ],\n \"const_axis\": [True, False],\n \"keepdims\": [True, False],\n }, {\n \"input_dtype\": [tf.float32, tf.int32, tf.int64],\n \"input_shape\": [[1, 224, 224, 3]],\n \"axis\": [\n None, 0, 1, 2, 3, [1, 2], [0, 3], [1, 2, 3], [0, 1, 2, 3],\n [3, 2, 1, 0], [3, 1, 0, 2], [2, 0], [3, 0], [3, 1], [1, 0], -1, -2,\n -3, -4, [0, -2], [2, 3, -1, 0], [3, 1, 2, -3], [3, -4], [2, 2, 2],\n [2, 2, 3], [-3, -3, -4], [-3, 2, 1]\n ],\n \"const_axis\": [True, False],\n \"keepdims\": [True, False],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the mean op testing graph.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n\n # Get axis as either a placeholder or constants.\n if parameters[\"const_axis\"]:\n axis = parameters[\"axis\"]\n input_tensors = [input_tensor]\n else:\n if isinstance(parameters[\"axis\"], list):\n shape = [len(parameters[\"axis\"])]\n else:\n shape = [0] # shape for None or integers.\n axis = tf.placeholder(dtype=tf.int32, name=\"axis\", shape=shape)\n input_tensors = [input_tensor, axis]\n\n out = tf.reduce_mean(\n input_tensor, axis=axis, keepdims=parameters[\"keepdims\"])\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(parameters[\"input_dtype\"], parameters[\"input_shape\"])\n ]\n if not parameters[\"const_axis\"]:\n if parameters[\"axis\"]:\n values.append(np.array(parameters[\"axis\"]))\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_exp_tests(zip_path):\n \"\"\"Make a set of tests to do exp.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32],\n \"input_shape\": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the exp op testing graph.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n\n out = tf.exp(input_tensor)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(parameters[\"input_dtype\"], parameters[\"input_shape\"],\n min_value=-100, max_value=9)\n ]\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_log_softmax_tests(zip_path):\n \"\"\"Make a set of tests to do log_softmax.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32],\n \"input_shape\": [[1, 100], [4, 2], [5, 224]],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the log_softmax op testing graph.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n\n out = tf.nn.log_softmax(input_tensor)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(\n parameters[\"input_dtype\"],\n parameters[\"input_shape\"],\n min_value=-100,\n max_value=9)\n ]\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_maximum_tests(zip_path):\n \"\"\"Make a set of tests to do maximum.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32],\n \"input_shape_1\": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]],\n \"input_shape_2\": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the maximum op testing graph.\"\"\"\n input_tensor_1 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input_1\",\n shape=parameters[\"input_shape_1\"])\n input_tensor_2 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input_2\",\n shape=parameters[\"input_shape_2\"])\n\n out = tf.maximum(input_tensor_1, input_tensor_2)\n return [input_tensor_1, input_tensor_2], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_1\"]),\n create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_2\"])\n ]\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_minimum_tests(zip_path):\n \"\"\"Make a set of tests to do minimum.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32],\n \"input_shape_1\": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]],\n \"input_shape_2\": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the minimum op testing graph.\"\"\"\n input_tensor_1 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input_1\",\n shape=parameters[\"input_shape_1\"])\n input_tensor_2 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input_2\",\n shape=parameters[\"input_shape_2\"])\n\n out = tf.minimum(input_tensor_1, input_tensor_2)\n return [input_tensor_1, input_tensor_2], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_1\"]),\n create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_2\"])\n ]\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_binary_op_tests_func(binary_operator):\n \"\"\"Return a function that does a test on a binary operator.\"\"\"\n return lambda zip_path: make_binary_op_tests(zip_path, binary_operator)\n\n\ndef make_add_tests(zip_path):\n make_binary_op_tests(zip_path, tf.add)\n\n\ndef make_div_tests(zip_path):\n make_binary_op_tests(zip_path, tf.div)\n\n\ndef make_sub_tests(zip_path):\n make_binary_op_tests(zip_path, tf.subtract)\n\n\ndef make_mul_tests(zip_path):\n make_binary_op_tests(zip_path, tf.multiply)\n\n\ndef make_gather_tests(zip_path):\n \"\"\"Make a set of tests to do gather.\"\"\"\n\n test_parameters = [{\n # TODO(mgubin): add string tests when they are supported by Toco.\n # TODO(mgubin): add tests for Nd indices when they are supported by\n # TfLite.\n \"params_dtype\": [tf.float32, tf.int32],\n \"params_shape\": [[10], [1, 2, 20]],\n \"indices_dtype\": [tf.int32],\n \"indices_shape\": [[3], [5]],\n \"axis\": [0, 1],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the gather op testing graph.\"\"\"\n params = tf.placeholder(\n dtype=parameters[\"params_dtype\"],\n name=\"params\",\n shape=parameters[\"params_shape\"])\n indices = tf.placeholder(\n dtype=parameters[\"indices_dtype\"],\n name=\"indices\",\n shape=parameters[\"indices_shape\"])\n out = tf.gather(params, indices, axis=parameters[\"axis\"])\n return [params, indices], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n params = create_tensor_data(parameters[\"params_dtype\"],\n parameters[\"params_shape\"])\n indices = create_tensor_data(parameters[\"indices_dtype\"],\n parameters[\"indices_shape\"], 0,\n parameters[\"params_shape\"][0] - 1)\n return [params, indices], sess.run(\n outputs, feed_dict=dict(zip(inputs, [params, indices])))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_global_batch_norm_tests(zip_path):\n \"\"\"Make a set of tests to do batch_norm_with_global_normalization.\"\"\"\n\n test_parameters = [{\n \"dtype\": [tf.float32],\n \"input_shape\": [[1, 1, 6, 2], [3, 4, 5, 4]],\n \"epsilon\": [0.1, 0.0001],\n \"scale_after\": [True, False],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the global batch norm testing graph.\"\"\"\n input_shape = parameters[\"input_shape\"]\n scale_shape = input_shape[3]\n\n scale = create_tensor_data(parameters[\"dtype\"], scale_shape)\n offset = create_tensor_data(parameters[\"dtype\"], scale_shape)\n mean = create_tensor_data(parameters[\"dtype\"], scale_shape)\n variance = create_tensor_data(parameters[\"dtype\"], scale_shape)\n\n x = create_tensor_data(parameters[\"dtype\"], parameters[\"input_shape\"])\n x_norm = tf.nn.batch_norm_with_global_normalization(\n x, mean, variance, scale, offset,\n parameters[\"epsilon\"], parameters[\"scale_after\"])\n\n input_tensor = tf.placeholder(dtype=parameters[\"dtype\"], name=\"input\",\n shape=parameters[\"input_shape\"])\n out = tf.add(input_tensor, x_norm)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape\"])\n return [input_value], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value])))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_fused_batch_norm_tests(zip_path):\n \"\"\"Make a set of tests to do fused_batch_norm.\"\"\"\n\n test_parameters = [{\n \"dtype\": [tf.float32],\n \"input_shape\": [[1, 1, 6, 2]],\n \"epsilon\": [0.001, 0.1],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the testing graph for fused batch normalization.\"\"\"\n input_shape = parameters[\"input_shape\"]\n scale_shape = input_shape[3]\n\n scale = create_tensor_data(parameters[\"dtype\"], scale_shape)\n offset = create_tensor_data(parameters[\"dtype\"], scale_shape)\n mean = create_tensor_data(parameters[\"dtype\"], scale_shape)\n variance = create_tensor_data(parameters[\"dtype\"], scale_shape)\n\n x = create_tensor_data(parameters[\"dtype\"], parameters[\"input_shape\"])\n [x_norm, _, _] = tf.nn.fused_batch_norm(\n x, scale, offset, mean, variance,\n parameters[\"epsilon\"], data_format=\"NHWC\", is_training=False)\n\n input_tensor = tf.placeholder(dtype=parameters[\"dtype\"], name=\"input\",\n shape=parameters[\"input_shape\"])\n out = tf.add(input_tensor, x_norm)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape\"])\n return [input_value], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value])))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_conv_tests(zip_path):\n \"\"\"Make a set of tests to do convolution.\"\"\"\n\n test_parameters = [\n {\n \"input_shape\": [[1, 3, 4, 3]],\n \"filter_shape\": [[1, 1, 3, 2]],\n \"strides\": [[1, 1, 1, 1], [1, 2, 3, 1]],\n \"dilations\": [[1, 1, 1, 1], [1, 3, 2, 1], [1, 2, 2, 1]],\n \"padding\": [\"SAME\", \"VALID\"],\n \"data_format\": [\"NHWC\"], # TODO(aselle): NCHW would be good\n \"constant_filter\": [True, False],\n },\n {\n \"input_shape\": [[2, 14, 14, 2]],\n \"filter_shape\": [[6, 6, 2, 2]],\n \"strides\": [[1, 1, 1, 1], [1, 2, 3, 1]],\n \"dilations\": [[1, 1, 1, 1], [1, 2, 2, 1]],\n \"padding\": [\"SAME\", \"VALID\"],\n \"data_format\": [\"NHWC\"], # TODO(aselle): NCHW would be good\n \"constant_filter\": [True, False],\n }\n ]\n\n def build_graph(parameters):\n \"\"\"Build a conv graph given `parameters`.\"\"\"\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n\n # Get filter input either as a placeholder or constants. Also get a list of\n # the input tensors that are represented as placeholders.\n if parameters[\"constant_filter\"]:\n filter_input = create_tensor_data(np.float32, parameters[\"filter_shape\"])\n input_tensors = [input_tensor]\n else:\n filter_input = tf.placeholder(\n dtype=tf.float32, name=\"filter\", shape=parameters[\"filter_shape\"])\n input_tensors = [input_tensor, filter_input]\n\n out = tf.nn.conv2d(\n input_tensor,\n filter_input,\n strides=parameters[\"strides\"],\n dilations=parameters[\"dilations\"],\n padding=parameters[\"padding\"],\n data_format=parameters[\"data_format\"])\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n # Build list of input values either containing 1 tensor (input) or 2 tensors\n # (input, filter) based on whether filter is constant or variable input.\n values = [create_tensor_data(np.float32, parameters[\"input_shape\"])]\n if not parameters[\"constant_filter\"]:\n values.append(create_tensor_data(np.float32, parameters[\"filter_shape\"]))\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_depthwiseconv_tests(zip_path):\n \"\"\"Make a set of tests to do convolution.\"\"\"\n\n # Tensorflow only supports equal strides\n test_parameters = [\n {\n \"input_shape\": [[1, 3, 4, 3], [1, 10, 10, 3]],\n \"filter_size\": [[1, 1], [1, 2], [3, 3]],\n \"strides\": [[1, 1, 1, 1], [1, 3, 3, 1]],\n \"channel_multiplier\": [1, 2],\n \"rate\": [[1, 1]],\n \"padding\": [\"SAME\", \"VALID\"],\n \"data_format\": [\"NHWC\"],\n \"constant_filter\": [True, False],\n },\n {\n \"input_shape\": [[1, 3, 4, 3]],\n \"filter_size\": [[1, 1]],\n \"strides\": [[1, 1, 2, 1]], # TF needs [1, x, x, 1]\n \"channel_multiplier\": [2],\n \"rate\": [[2, 2]], # Only [1, 1] is supported\n \"padding\": [\"SAME\"],\n \"data_format\": [\"NHWC\"],\n \"constant_filter\": [True, False],\n }\n ]\n\n def get_tensor_shapes(parameters):\n input_shape = parameters[\"input_shape\"]\n filter_size = parameters[\"filter_size\"]\n filter_shape = filter_size + [\n input_shape[3], parameters[\"channel_multiplier\"]\n ]\n return [input_shape, filter_shape]\n\n def build_graph(parameters):\n \"\"\"Build a depthwise conv graph given `parameters`.\"\"\"\n input_shape, filter_shape = get_tensor_shapes(parameters)\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=input_shape)\n\n # Get filter input either as a placeholder or constants. Also get a list of\n # the input tensors that are represented as placeholders.\n if parameters[\"constant_filter\"]:\n filter_input = create_tensor_data(np.float32, filter_shape)\n input_tensors = [input_tensor]\n else:\n filter_input = tf.placeholder(\n dtype=tf.float32, name=\"filter\", shape=filter_shape)\n input_tensors = [input_tensor, filter_input]\n\n out = tf.nn.depthwise_conv2d(\n input_tensor,\n filter_input,\n strides=parameters[\"strides\"],\n rate=parameters[\"rate\"],\n padding=parameters[\"padding\"],\n data_format=parameters[\"data_format\"])\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n # Build list of input values either containing 1 tensor (input) or 2 tensors\n # (input, filter) based on whether filter is constant or variable input.\n input_shape, filter_shape = get_tensor_shapes(parameters)\n values = [create_tensor_data(np.float32, input_shape)]\n if not parameters[\"constant_filter\"]:\n values.append(create_tensor_data(np.float32, filter_shape))\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_split_tests(zip_path):\n \"\"\"Make a set of tests to do tf.split.\"\"\"\n\n test_parameters = [{\n \"input_shape\": [[1, 3, 4, 6], [2, 4, 1], [6, 4], [8]],\n \"num_or_size_splits\": [1, 2, 3, 4, 5, [2, 2]],\n \"axis\": [0, 1, 2, 3, -4, -3, -2, -1],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n out = tf.split(\n input_tensor, parameters[\"num_or_size_splits\"], parameters[\"axis\"])\n return [input_tensor], out\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [create_tensor_data(np.float32, parameters[\"input_shape\"])]\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_concat_tests(zip_path):\n \"\"\"Make a set of tests to do concatenation.\"\"\"\n\n test_parameters = [{\n \"base_shape\": [[1, 3, 4, 3], [3, 4]],\n \"num_tensors\": [1, 2, 3, 4, 5, 6],\n \"axis\": [0, 1, 2, 3, -3, -2, -1],\n }]\n\n def get_shape(parameters, delta):\n \"\"\"Return a tweaked version of 'base_shape'.\"\"\"\n axis = parameters[\"axis\"]\n shape = parameters[\"base_shape\"][:]\n if axis < 0:\n axis += len(shape)\n if axis < len(shape):\n shape[axis] += delta\n return shape\n\n def build_graph(parameters):\n all_tensors = []\n for n in range(0, parameters[\"num_tensors\"]):\n input_tensor = tf.placeholder(dtype=tf.float32, name=(\"input%d\" % n),\n shape=get_shape(parameters, n))\n all_tensors.append(input_tensor)\n out = tf.concat(all_tensors, parameters[\"axis\"])\n return all_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n all_values = []\n for n in range(0, parameters[\"num_tensors\"]):\n input_values = create_tensor_data(np.float32,\n get_shape(parameters, n))\n all_values.append(input_values)\n return all_values, sess.run(\n outputs, feed_dict=dict(zip(inputs, all_values)))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_fully_connected_tests(zip_path):\n \"\"\"Make a set of tests to do fully_connected.\"\"\"\n\n test_parameters = [{\n \"shape1\": [[3, 3]],\n \"shape2\": [[3, 3]],\n \"transpose_a\": [True, False],\n \"transpose_b\": [True, False],\n \"constant_filter\": [True, False],\n }, {\n \"shape1\": [[4, 4], [1, 4], [4]],\n \"shape2\": [[4, 4], [4, 1], [4]],\n \"transpose_a\": [False],\n \"transpose_b\": [False],\n \"constant_filter\": [True, False],\n }, {\n \"shape1\": [[40, 37]],\n \"shape2\": [[37, 40]],\n \"transpose_a\": [False],\n \"transpose_b\": [False],\n \"constant_filter\": [True, False],\n }]\n\n def build_graph(parameters):\n \"\"\"Build a matmul graph given `parameters`.\"\"\"\n input_tensor1 = tf.placeholder(dtype=tf.float32, name=\"input1\",\n shape=parameters[\"shape1\"])\n\n # Get input_tensor2 either as a placeholder or constants. Also get a list of\n # the input tensors that are represented as placeholders.\n if parameters[\"constant_filter\"]:\n input_tensor2 = create_tensor_data(np.float32, parameters[\"shape2\"])\n input_tensors = [input_tensor1]\n else:\n input_tensor2 = tf.placeholder(\n dtype=tf.float32, name=\"input2\", shape=parameters[\"shape2\"])\n input_tensors = [input_tensor1, input_tensor2]\n\n out = tf.matmul(input_tensor1, input_tensor2,\n transpose_a=parameters[\"transpose_a\"],\n transpose_b=parameters[\"transpose_b\"])\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n # Build list of input values either containing 1 tensor (input_values1) or 2\n # tensors (input_values1, input_values2) based on whether the second input\n # is a constant or variable input.\n values = [create_tensor_data(np.float32, shape=parameters[\"shape1\"])]\n if not parameters[\"constant_filter\"]:\n values.append(create_tensor_data(np.float32, parameters[\"shape2\"]))\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_l2norm_tests(zip_path):\n \"\"\"Make a set of tests to do l2norm.\"\"\"\n\n # Chose a set of parameters\n test_parameters = [{\n \"input_shape\": [[5, 7], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3],\n [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]],\n \"dim\": [0, 1, 2, 3, [2, 3], -2],\n \"epsilon\": [None, 1e-12, 1e-3],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n if parameters[\"epsilon\"]:\n out = tf.nn.l2_normalize(\n input_tensor, parameters[\"dim\"], epsilon=parameters[\"epsilon\"])\n else:\n out = tf.nn.l2_normalize(input_tensor, parameters[\"dim\"])\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(\n np.float32, parameters[\"input_shape\"], min_value=-4, max_value=10)\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_local_response_norm_tests(zip_path):\n \"\"\"Make a set of tests to do local_response_norm.\"\"\"\n\n # Chose a set of parameters\n test_parameters = [{\n \"input_shape\": [[1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3]],\n \"depth_radius\": [None, 0, 1, 3, 4, 5],\n \"bias\": [None, 0.1, 0.3, -0.1],\n \"alpha\": [None, 1, 2, -3],\n \"beta\": [None, 0.5, 0.25, 2],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n out = tf.nn.local_response_normalization(\n input_tensor, depth_radius=parameters[\"depth_radius\"],\n bias=parameters[\"bias\"], alpha=parameters[\"alpha\"],\n beta=parameters[\"beta\"])\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(\n np.float32, parameters[\"input_shape\"], min_value=-4, max_value=10)\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_pad_tests(zip_path):\n \"\"\"Make a set of tests to do pad.\"\"\"\n\n # TODO(nupurgarg): Add test for tf.uint8.\n test_parameters = [\n {\n \"dtype\": [tf.int32, tf.int64, tf.float32],\n \"input_shape\": [[1, 1, 2, 1], [2, 1, 1, 1]],\n \"paddings\": [[[0, 0], [0, 1], [2, 3], [0, 0]], [[0, 1], [0, 0],\n [0, 0], [2, 3]]],\n \"constant_paddings\": [True, False],\n },\n # Non-4D use case.\n {\n \"dtype\": [tf.int32, tf.int64, tf.float32],\n \"input_shape\": [[1, 2], [0, 1, 2]],\n \"paddings\": [[[0, 1], [2, 3]]],\n \"constant_paddings\": [True, False],\n },\n ]\n\n def build_graph(parameters):\n \"\"\"Build a pad graph given `parameters`.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n\n # Get paddings as either a placeholder or constants.\n if parameters[\"constant_paddings\"]:\n paddings = parameters[\"paddings\"]\n input_tensors = [input_tensor]\n else:\n shape = [len(parameters[\"paddings\"]), 2]\n paddings = tf.placeholder(dtype=tf.int32, name=\"padding\", shape=shape)\n input_tensors = [input_tensor, paddings]\n\n out = tf.pad(input_tensor, paddings=paddings)\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(parameters[\"dtype\"], parameters[\"input_shape\"])\n ]\n if not parameters[\"constant_paddings\"]:\n values.append(np.array(parameters[\"paddings\"]))\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_reshape_tests(zip_path):\n \"\"\"Make a set of tests to do reshape.\"\"\"\n\n # All shapes below are suitable for tensors with 420 elements.\n test_parameters = [{\n \"dtype\": [tf.float32, tf.int32],\n \"input_shape\": [[3, 4, 5, 7], [4, 105], [21, 5, 2, 2], [420]],\n \"output_shape\": [[15, 28], [420], [1, -1, 5, 7], [-1]],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(dtype=parameters[\"dtype\"], name=\"input\",\n shape=parameters[\"input_shape\"])\n out = tf.reshape(input_tensor, shape=parameters[\"output_shape\"])\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape\"])\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_resize_bilinear_tests(zip_path):\n \"\"\"Make a set of tests to do resize_bilinear.\"\"\"\n\n test_parameters = [{\n \"dtype\": [tf.float32, tf.int32],\n \"input_shape\": [[1, 3, 4, 3], [1, 10, 2, 1]],\n \"size\": [[1, 1], [4, 3], [2, 2], [5, 6]],\n \"align_corners\": [None, True, False],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(dtype=parameters[\"dtype\"], name=\"input\",\n shape=parameters[\"input_shape\"])\n out = tf.image.resize_bilinear(input_tensor, size=parameters[\"size\"],\n align_corners=parameters[\"align_corners\"])\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape\"])\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_sigmoid_tests(zip_path):\n \"\"\"Make a set of tests to do sigmoid.\"\"\"\n\n test_parameters = [{\n \"dtype\": [tf.float32],\n \"input_shape\": [[1, 3, 4, 3], [4], [], [1, 2, 3, 4, 5, 6]],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(dtype=parameters[\"dtype\"], name=\"input\",\n shape=parameters[\"input_shape\"])\n out = tf.sigmoid(input_tensor)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape\"])\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_softmax_tests(zip_path):\n \"\"\"Make a set of tests to do softmax.\"\"\"\n\n test_parameters = [{\n \"dtype\": [tf.float32],\n \"input_shape\": [[1, 3, 4, 3], [2, 3]],\n \"dim\": [-1, 0],\n }, {\n \"dtype\": [tf.float32],\n \"input_shape\": [[4, 7]],\n \"dim\": [-1, 1],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(dtype=parameters[\"dtype\"], name=\"input\",\n shape=parameters[\"input_shape\"])\n out = tf.nn.softmax(input_tensor, dim=parameters[\"dim\"])\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape\"])\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_space_to_depth_tests(zip_path):\n \"\"\"Make a set of tests to do space_to_depth.\"\"\"\n\n test_parameters = [{\n \"dtype\": [tf.float32, tf.float16, tf.int32, tf.uint8, tf.int64],\n \"input_shape\": [[2, 12, 24, 1]],\n \"block_size\": [2, 3, 4],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(dtype=parameters[\"dtype\"], name=\"input\",\n shape=parameters[\"input_shape\"])\n out = tf.space_to_depth(input_tensor, block_size=parameters[\"block_size\"])\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape\"])\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_space_to_batch_nd_tests(zip_path):\n \"\"\"Make a set of tests to do space_to_batch_nd.\"\"\"\n\n # TODO(nupurgarg): Add test for uint8.\n test_parameters = [\n {\n \"dtype\": [tf.int32, tf.int64, tf.float32],\n \"input_shape\": [[1, 2, 2, 3], [2, 2, 4, 1]],\n \"block_shape\": [[1, 3], [2, 2]],\n \"paddings\": [[[0, 0], [0, 0]], [[0, 0], [2, 0]], [[1, 1], [1, 1]]],\n \"constant_block_shape\": [True, False],\n \"constant_paddings\": [True, False],\n },\n {\n \"dtype\": [tf.float32],\n \"input_shape\": [[2, 3, 7, 3]],\n \"block_shape\": [[1, 3], [2, 2]],\n \"paddings\": [[[0, 0], [2, 0]], [[1, 0], [1, 0]]],\n \"constant_block_shape\": [True, False],\n \"constant_paddings\": [True, False],\n },\n # Non-4D use case: 1 bath dimension, 3 spatial dimensions, 2 others.\n {\n \"dtype\": [tf.float32],\n \"input_shape\": [[1, 4, 4, 4, 1, 1]],\n \"block_shape\": [[2, 2, 2]],\n \"paddings\": [[[0, 0], [0, 0], [0, 0]]],\n \"constant_block_shape\": [True, False],\n \"constant_paddings\": [True, False],\n },\n ]\n\n def build_graph(parameters):\n \"\"\"Build a space_to_batch graph given `parameters`.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n input_tensors = [input_tensor]\n\n # Get block_shape either as a const or as a placeholder (tensor).\n if parameters[\"constant_block_shape\"]:\n block_shape = parameters[\"block_shape\"]\n else:\n shape = [len(parameters[\"block_shape\"])]\n block_shape = tf.placeholder(dtype=tf.int32, name=\"shape\", shape=shape)\n input_tensors.append(block_shape)\n\n # Get paddings either as a const or as a placeholder (tensor).\n if parameters[\"constant_paddings\"]:\n paddings = parameters[\"paddings\"]\n else:\n shape = [len(parameters[\"paddings\"]), 2]\n paddings = tf.placeholder(dtype=tf.int32, name=\"paddings\", shape=shape)\n input_tensors.append(paddings)\n\n out = tf.space_to_batch_nd(input_tensor, block_shape, paddings)\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(parameters[\"dtype\"], parameters[\"input_shape\"])\n ]\n if not parameters[\"constant_block_shape\"]:\n values.append(np.array(parameters[\"block_shape\"]))\n if not parameters[\"constant_paddings\"]:\n values.append(np.array(parameters[\"paddings\"]))\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_batch_to_space_nd_tests(zip_path):\n \"\"\"Make a set of tests to do batch_to_space_nd.\"\"\"\n\n test_parameters = [\n {\n \"dtype\": [tf.float32, tf.int64, tf.int32],\n \"input_shape\": [[12, 3, 3, 1]],\n \"block_shape\": [[1, 4], [2, 2], [3, 4]],\n \"crops\": [[[0, 0], [0, 0]], [[1, 1], [1, 1]]],\n \"constant_block_shape\": [True, False],\n \"constant_crops\": [True, False],\n },\n # Non-4D use case: 1 bath dimension, 3 spatial dimensions, 2 others.\n {\n \"dtype\": [tf.float32],\n \"input_shape\": [[8, 2, 2, 2, 1, 1]],\n \"block_shape\": [[2, 2, 2]],\n \"crops\": [[[0, 0], [0, 0], [0, 0]]],\n \"constant_block_shape\": [True, False],\n \"constant_crops\": [True, False],\n },\n ]\n\n def build_graph(parameters):\n \"\"\"Build a batch_to_space graph given `parameters`.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n input_tensors = [input_tensor]\n\n # Get block_shape either as a const or as a placeholder (tensor).\n if parameters[\"constant_block_shape\"]:\n block_shape = parameters[\"block_shape\"]\n else:\n shape = [len(parameters[\"block_shape\"])]\n block_shape = tf.placeholder(dtype=tf.int32, name=\"shape\", shape=shape)\n input_tensors.append(block_shape)\n\n # Get crops either as a const or as a placeholder (tensor).\n if parameters[\"constant_crops\"]:\n crops = parameters[\"crops\"]\n else:\n shape = [len(parameters[\"crops\"]), 2]\n crops = tf.placeholder(dtype=tf.int32, name=\"crops\", shape=shape)\n input_tensors.append(crops)\n\n out = tf.batch_to_space_nd(input_tensor, block_shape, crops)\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(parameters[\"dtype\"], parameters[\"input_shape\"])\n ]\n if not parameters[\"constant_block_shape\"]:\n values.append(np.array(parameters[\"block_shape\"]))\n if not parameters[\"constant_crops\"]:\n values.append(np.array(parameters[\"crops\"]))\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_transpose_tests(zip_path):\n \"\"\"Make a set of tests to do transpose.\"\"\"\n\n # TODO(nupurgarg): Add test for uint8.\n test_parameters = [{\n \"dtype\": [tf.int32, tf.int64, tf.float32],\n \"input_shape\": [[2, 2, 3]],\n \"perm\": [[0, 1, 2], [0, 2, 1]],\n \"constant_perm\": [True, False],\n }, {\n \"dtype\": [tf.float32],\n \"input_shape\": [[1, 2, 3, 4]],\n \"perm\": [[0, 1, 2, 3], [3, 0, 1, 2]],\n \"constant_perm\": [True, False],\n }, {\n \"dtype\": [tf.float32],\n \"input_shape\": [[1, 2, 3, 4, 5]],\n \"perm\": [[4, 3, 2, 1, 0]],\n \"constant_perm\": [True, False],\n }]\n\n def build_graph(parameters):\n \"\"\"Build a transpose graph given `parameters`.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n\n if parameters[\"constant_perm\"]:\n perm = parameters[\"perm\"]\n input_tensors = [input_tensor]\n else:\n shape = [len(parameters[\"perm\"]), 2]\n perm = tf.placeholder(dtype=tf.int32, name=\"perm\", shape=shape)\n input_tensors = [input_tensor, perm]\n\n out = tf.transpose(input_tensor, perm=perm)\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(parameters[\"dtype\"], parameters[\"input_shape\"])\n ]\n if not parameters[\"constant_perm\"]:\n values.append(np.array(parameters[\"perm\"]))\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_squeeze_tests(zip_path):\n \"\"\"Make a set of tests to do squeeze.\"\"\"\n\n test_parameters = [{\n \"dtype\": [tf.int32, tf.float32, tf.int64],\n \"input_shape\": [[1, 2, 1, 3, 1, 4, 1, 1]],\n \"axis\": [\n None, [], [0, 2], [4, 7], [-1, 0, 2, 0, 7, -6], [1], [2, 3, 2],\n [-1, -2, -4, -6, -8], [0, 2, 4, 6, 7], [7, 6, 4, 2, 0], [6, 6],\n [0, 1, 2, 3, 4, 5, 6, 7], [-2, -3, 1, 0, 7, -5]\n ],\n }, {\n \"dtype\": [tf.int32, tf.float32, tf.int64],\n \"input_shape\": [[1]],\n \"axis\": [None, [], [0], [-1]],\n }, {\n \"dtype\": [tf.int32, tf.float32, tf.int64],\n \"input_shape\": [[1, 1, 1, 1, 1]],\n \"axis\": [None, [], [0], [3, 0], [-2, 0, 3, 2]],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n out = tf.squeeze(input_tensor, axis=parameters[\"axis\"])\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape\"])\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_strided_slice_tests(zip_path):\n \"\"\"Make a set of tests to do strided_slice.\"\"\"\n\n # TODO(soroosh): add test/support for uint8.\n test_parameters = [\n # 4-D\n {\n \"dtype\": [tf.float32, tf.int32, tf.int64],\n \"index_type\": [tf.int32],\n \"input_shape\": [[12, 2, 2, 5]],\n \"begin\": [[0, 0, 0, 0], [1, 0, 1, 0]],\n \"end\": [[8, 2, 2, 3], [12, 2, 2, 5]],\n \"strides\": [None, [2, 1, 3, 1]],\n \"begin_mask\": [None, 1, 8],\n \"end_mask\": [None, 1, 8],\n \"shrink_axis_mask\": [None, 1, 8, 11, 15, -1],\n \"constant_indices\": [False, True],\n },\n # TODO(b/73170889) Restore test paramaters removed in cl/191608113.\n # 2-D\n {\n \"dtype\": [tf.float32, tf.int32, tf.int64],\n \"index_type\": [tf.int32],\n \"input_shape\": [[2, 3]],\n \"begin\": [[0, 0], [1, 0]],\n \"end\": [[2, 3], [2, 2]],\n \"strides\": [None, [2, 2]],\n \"begin_mask\": [None, 1, 2],\n \"end_mask\": [None, 1, 2],\n \"shrink_axis_mask\": [None, 1, 2, 3, -1],\n \"constant_indices\": [False, True],\n },\n # Negative strides\n {\n \"dtype\": [tf.float32],\n \"index_type\": [tf.int32],\n \"input_shape\": [[2, 3]],\n \"begin\": [[0, -1]],\n \"end\": [[2, -3]],\n \"strides\": [[1, -1]],\n \"begin_mask\": [None, 1, 2],\n \"end_mask\": [None, 1, 2],\n \"shrink_axis_mask\": [None, 1, 2, 3, -1],\n \"constant_indices\": [False],\n },\n ]\n\n def build_graph(parameters):\n \"\"\"Build graph for stride_slice test.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n if parameters[\"constant_indices\"]:\n begin = parameters[\"begin\"]\n end = parameters[\"end\"]\n strides = parameters[\"strides\"]\n tensors = [input_tensor]\n else:\n begin = tf.placeholder(\n dtype=parameters[\"index_type\"],\n name=\"begin\",\n shape=[len(parameters[\"input_shape\"])])\n end = tf.placeholder(\n dtype=parameters[\"index_type\"],\n name=\"end\",\n shape=[len(parameters[\"input_shape\"])])\n strides = (\n tf.placeholder(\n dtype=parameters[\"index_type\"],\n name=\"strides\",\n shape=[len(parameters[\"input_shape\"])])\n if parameters[\"strides\"] is not None else None)\n tensors = [input_tensor, begin, end]\n if strides is not None:\n tensors.append(strides)\n out = tf.strided_slice(\n input_tensor,\n begin,\n end,\n strides,\n begin_mask=parameters[\"begin_mask\"],\n end_mask=parameters[\"end_mask\"])\n return tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n \"\"\"Build inputs for stride_slice test.\"\"\"\n input_values = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape\"])\n index_type = _TF_TYPE_INFO[parameters[\"index_type\"]][0]\n values = [input_values]\n if not parameters[\"constant_indices\"]:\n begin_values = np.array(parameters[\"begin\"]).astype(index_type)\n end_values = np.array(parameters[\"end\"]).astype(index_type)\n stride_values = (\n np.array(parameters[\"strides\"]).astype(index_type)\n if parameters[\"strides\"] is not None else None)\n values.append(begin_values)\n values.append(end_values)\n if stride_values is not None:\n values.append(stride_values)\n\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_lstm_tests(zip_path):\n \"\"\"Make a set of tests to do basic Lstm cell.\"\"\"\n\n test_parameters = [\n {\n \"dtype\": [tf.float32],\n \"num_batchs\": [1],\n \"time_step_size\": [1],\n \"input_vec_size\": [3],\n \"num_cells\": [4],\n },\n ]\n\n def build_graph(parameters):\n \"\"\"Build a simple graph with BasicLSTMCell.\"\"\"\n\n num_batchs = parameters[\"num_batchs\"]\n time_step_size = parameters[\"time_step_size\"]\n input_vec_size = parameters[\"input_vec_size\"]\n num_cells = parameters[\"num_cells\"]\n inputs_after_split = []\n for i in xrange(time_step_size):\n one_timestamp_input = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"split_{}\".format(i),\n shape=[num_batchs, input_vec_size])\n inputs_after_split.append(one_timestamp_input)\n # Currently lstm identifier has a few limitations: only supports\n # forget_bias == 0, inner state activiation == tanh.\n # TODO(zhixianyan): Add another test with forget_bias == 1.\n # TODO(zhixianyan): Add another test with relu as activation.\n lstm_cell = tf.contrib.rnn.BasicLSTMCell(\n num_cells, forget_bias=0.0, state_is_tuple=True)\n cell_outputs, _ = rnn.static_rnn(\n lstm_cell, inputs_after_split, dtype=tf.float32)\n out = cell_outputs[-1]\n return inputs_after_split, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n \"\"\"Feed inputs, assign vairables, and freeze graph.\"\"\"\n\n with tf.variable_scope(\"\", reuse=True):\n kernel = tf.get_variable(\"rnn/basic_lstm_cell/kernel\")\n bias = tf.get_variable(\"rnn/basic_lstm_cell/bias\")\n kernel_values = create_tensor_data(\n parameters[\"dtype\"], [kernel.shape[0], kernel.shape[1]], -1, 1)\n bias_values = create_tensor_data(parameters[\"dtype\"], [bias.shape[0]], 0,\n 1)\n sess.run(tf.group(kernel.assign(kernel_values), bias.assign(bias_values)))\n\n num_batchs = parameters[\"num_batchs\"]\n time_step_size = parameters[\"time_step_size\"]\n input_vec_size = parameters[\"input_vec_size\"]\n input_values = []\n for _ in xrange(time_step_size):\n tensor_data = create_tensor_data(parameters[\"dtype\"],\n [num_batchs, input_vec_size], 0, 1)\n input_values.append(tensor_data)\n out = sess.run(outputs, feed_dict=dict(zip(inputs, input_values)))\n return input_values, out\n\n # TODO(zhixianyan): Automatically generate rnn_states for lstm cell.\n extra_toco_options = ExtraTocoOptions()\n extra_toco_options.rnn_states = (\n \"{state_array:rnn/BasicLSTMCellZeroState/zeros,\"\n \"back_edge_source_array:rnn/basic_lstm_cell/Add_1,size:4},\"\n \"{state_array:rnn/BasicLSTMCellZeroState/zeros_1,\"\n \"back_edge_source_array:rnn/basic_lstm_cell/Mul_2,size:4}\")\n\n make_zip_of_tests(\n zip_path,\n test_parameters,\n build_graph,\n build_inputs,\n extra_toco_options,\n use_frozen_graph=True)\n\n\ndef make_l2_pool(input_tensor, ksize, strides, padding, data_format):\n \"\"\"Given an input perform a sequence of TensorFlow ops to produce l2pool.\"\"\"\n return tf.sqrt(tf.nn.avg_pool(\n tf.square(input_tensor), ksize=ksize, strides=strides,\n padding=padding, data_format=data_format))\n\n\ndef make_topk_tests(zip_path):\n \"\"\"Make a set of tests to do topk.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32, tf.int32],\n \"input_shape\": [[10], [5, 20]],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the topk op testing graph.\"\"\"\n input_value = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n k = tf.constant(3, name=\"k\")\n out = tf.nn.top_k(input_value, k)\n return [input_value], [out[1]]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape\"])\n return [input_value], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value])))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_arg_max_tests(zip_path):\n \"\"\"Make a set of tests to do arg_max.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32, tf.int32],\n \"input_shape\": [[1, 1, 1, 3], [2, 3, 4, 5], [2, 3, 3], [5, 5], [10]],\n \"axis\": [0, 1, 2, 3],\n \"output_type\": [tf.int32, tf.int64],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the topk op testing graph.\"\"\"\n input_value = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n axis = tf.constant(parameters[\"axis\"], name=\"axis\")\n out = tf.arg_max(input_value, axis, output_type=parameters[\"output_type\"])\n return [input_value], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape\"])\n return [input_value], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value])))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n\ndef make_less_tests(zip_path):\n \"\"\"Make a set of tests to do less.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32, tf.int32, tf.int64],\n \"input_shape_pair\": [([1, 1, 1, 3], [1, 1, 1, 3]),\n ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]),\n ([5, 5], [1]), ([10], [2, 4, 10])],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the less op testing graph.\"\"\"\n input_value1 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input1\",\n shape=parameters[\"input_shape_pair\"][0])\n input_value2 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input2\",\n shape=parameters[\"input_shape_pair\"][1])\n out = tf.less(input_value1, input_value2)\n return [input_value1, input_value2], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value1 = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_pair\"][0])\n input_value2 = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_pair\"][1])\n return [input_value1, input_value2], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2])))\n\n make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs)\n\n# Toco binary path provided by the generate rule.\nbin_path = None\n\n\ndef main(unused_args):\n global bin_path\n def mkdir_if_not_exist(x):\n if not os.path.isdir(x):\n os.mkdir(x)\n if not os.path.isdir(x):\n raise RuntimeError(\"Failed to create dir %r\" % x)\n\n opstest_path = os.path.join(FLAGS.output_path)\n mkdir_if_not_exist(opstest_path)\n\n out = FLAGS.zip_to_output\n bin_path = FLAGS.toco\n test_function = (\"make_%s_tests\" % out.replace(\".zip\", \"\"))\n if test_function not in globals():\n raise RuntimeError(\"Can't find a test function to create %r. Tried %r\" %\n (out, test_function))\n\n # TODO(ahentz): accessing globals() is not very elegant. We should either\n # break this file into multiple tests or use decorator-based registration to\n # avoid using globals().\n globals()[test_function](os.path.join(opstest_path, out))\n\n\nif __name__ == \"__main__\":\n FLAGS, unparsed = parser.parse_known_args()\n\n if unparsed:\n print(\"Usage: %s <path out> <zip file to generate>\")\n else:\n tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)\n" ]
[ [ "tensorflow.python.util.all_util.remove_undocumented" ], [ "tensorflow.get_variable", "tensorflow.device", "tensorflow.nn.batch_norm_with_global_normalization", "tensorflow.nn.log_softmax", "tensorflow.concat", "tensorflow.zeros", "tensorflow.control_dependencies", "tensorflow.minimum", "tensorflow.global_variables", "tensorflow.space_to_batch_nd", "numpy.random.random_sample", "tensorflow.pad", "tensorflow.nn.depthwise_conv2d", "tensorflow.nn.conv2d", "tensorflow.strided_slice", "numpy.random.randint", "tensorflow.batch_to_space_nd", "tensorflow.squeeze", "tensorflow.gather", "tensorflow.nn.top_k", "tensorflow.reset_default_graph", "tensorflow.add", "tensorflow.square", "tensorflow.Session", "tensorflow.assert_greater_equal", "numpy.zeros", "tensorflow.app.run", "tensorflow.contrib.lite.testing.generate_examples_report.make_report_table", "tensorflow.nn.fused_batch_norm", "tensorflow.matmul", "tensorflow.image.resize_bilinear", "tensorflow.nn.l2_normalize", "tensorflow.less", "tensorflow.python.ops.rnn.static_rnn", "tensorflow.placeholder", "tensorflow.exp", "tensorflow.logging.info", "tensorflow.split", "numpy.array", "tensorflow.nn.relu", "tensorflow.nn.softmax", "tensorflow.transpose", "tensorflow.constant", "tensorflow.arg_max", "tensorflow.reduce_mean", "tensorflow.space_to_depth", "tensorflow.maximum", "tensorflow.contrib.rnn.BasicLSTMCell", "tensorflow.reshape", "tensorflow.sigmoid", "tensorflow.ones", "numpy.random.seed", "tensorflow.variable_scope", "tensorflow.nn.local_response_normalization" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
neurodatascience/watts_up_compute
[ "1ed41e62690f99f699b44180208689cc19616bb7" ]
[ "run_scripts/FreeSurfer/nipype_reconall_with_tracker.py" ]
[ "# Import modules\nimport os\nimport sys\nfrom os.path import join as opj\nimport pandas as pd\nimport time\nfrom nipype.interfaces.freesurfer import ReconAll\nfrom nipype.interfaces.utility import IdentityInterface\nfrom nipype.pipeline.engine import Workflow, Node\nfrom pypapi import events, papi_high as high\nimport argparse\n\n# Add paths (singularity should see these)\n# FastSurfer and carbon trackers are in the mounted dir as these repos keep getting updated.\n# TODO replace this with setup.py once the dependencis become stable\n# sys.path.append('../../../experiment-impact-tracker/')\n# sys.path.append('../../../codecarbon/')\n\nfrom experiment_impact_tracker.compute_tracker import ImpactTracker\nfrom codecarbon import EmissionsTracker, OfflineEmissionsTracker\n\ndef get_reconall(recon_directive,fs_folder):\n # This node represents the actual recon-all command\n reconall = Node(ReconAll(directive=recon_directive,\n flags='-nuintensitycor -3T',\n subjects_dir=fs_folder),\n name=\"reconall\")\n return reconall\n \n\n# This function returns for each subject the path to struct.nii.gz\ndef pathfinder(subject, foldername, filename):\n from os.path import join as opj\n struct_path = opj(foldername, subject, filename)\n return struct_path\n\n\ndef main():\n # setup\n exp_start_time = time.time()\n \n # argparse\n parser = argparse.ArgumentParser(description='Script to run freesurfer reconall with nipype and track compute costs', epilog='$Id: fast_surfer_cnn, v 1.0 2019/09/30$')\n\n # Data\n parser.add_argument('--experiment_dir', dest='experiment_dir', help='path to directory to store freesurfer derived data.')\n parser.add_argument('--data_dir', help=\"path to input data\", default='/neurohub/ukbb/imaging/')\n parser.add_argument('--subject_id', dest='subject_id', help='subject_id')\n parser.add_argument('--T1_identifier', help='T1 identifier string relateive to the subject directory')\n\n # FreeSurfer\n parser.add_argument('--recon_directive', dest='recon_directive', help='recon_directive (autorecon 1, 2, or 3)', default='1') #MTL\n \n # Trackers\n parser.add_argument('--tracker_log_dir', dest='tracker_log_dir',\n help=\"log dir for experiment impact tracker\",\n type=str, default='./tracker_logs/')\n parser.add_argument('--geo_loc', dest='geo_loc',\n help=\"(lat,log) coords for experiment impact tracker\",\n type=str, default='45.4972159,-73.6103642') #MTL Beluga\n parser.add_argument('--CC_offline',\n help=\"Run CC in offline mode\",\n action='store_true') \n parser.add_argument('--TZ', dest='TZ',\n help=\"TimeZone\",\n type=str, default='America/New_York')\n parser.add_argument('--iso_code', dest='iso_code',\n help=\"Country ISO code\",\n type=str, default='USA')\n \n # PAPI\n parser.add_argument('--count_FLOPs', dest='count_FLOPs',help=\"Count FLOPs using PAPI\",action='store_true') \n\n args = parser.parse_args()\n\n # Data\n experiment_dir = args.experiment_dir\n data_dir = args.data_dir\n subject_id = args.subject_id\n T1_identifier = args.T1_identifier\n\n # FreeSurfer\n recon_directive = args.recon_directive\n\n # FLOPs\n count_FLOPs = args.count_FLOPs\n\n # Trackers\n tracker_log_dir = args.tracker_log_dir\n geo_loc = args.geo_loc\n CC_offline = args.CC_offline\n TZ = args.TZ\n iso_code = args.iso_code\n\n print(f'Using offline mode for CC tracker: {CC_offline}')\n if CC_offline:\n print(f'Using {TZ} timezone and {iso_code} country iso code')\n \n print(f'Starting subject: {subject_id}')\n\n # Set up the trackers\n log_dir = '{}/{}/'.format(tracker_log_dir,subject_id)\n log_dir_EIT = f'{log_dir}/EIT/'\n log_dir_CC = f'{log_dir}/CC/'\n\n for d in [log_dir_EIT,log_dir_CC]:\n if not os.path.exists(d):\n os.makedirs(d)\n\n # Use specified geo location for the HPC\n ly,lx = float(geo_loc.split(',')[0]), float(geo_loc.split(',')[1])\n coords = (ly,lx)\n print(f'Using geographical coordinates (long,lat): {coords}')\n\n # EIT tracker\n tracker_EIT = ImpactTracker(log_dir_EIT,coords)\n tracker_EIT.launch_impact_monitor()\n\n # CodeCarbon tracker\n os.environ['TZ']= TZ\n \n if CC_offline:\n tracker_CC = OfflineEmissionsTracker(output_dir=log_dir_CC, country_iso_code=iso_code) \n else:\n tracker_CC = EmissionsTracker(output_dir=log_dir_CC)\n \n tracker_CC.start()\n\n if count_FLOPs:\n print('Counting flops using PAPI')\n flop_csv = tracker_log_dir + 'compute_costs_flop.csv'\n flop_df = pd.DataFrame(columns=['task','start_time','duration','DP'])\n \n\n # Start FS processing for a given subject\n subject_list = [subject_id]\n\n fs_folder = opj(experiment_dir, 'freesurfer') # location of freesurfer folder\n\n # Create the output folder - FreeSurfer can only run if this folder exists\n os.system('mkdir -p %s' % fs_folder)\n\n # Specify recon workflow stages\n if recon_directive == 'all':\n recon_directives = ['autorecon1','autorecon2','autorecon3']\n else:\n recon_directives = [recon_directive] \n\n\n for r, recon_directive in enumerate(recon_directives):\n print('\\nStarting stage: {}'.format(recon_directive))\n\n # Create the pipeline that runs the recon-all command\n reconflow = Workflow(name=\"reconflow\")\n reconflow.base_dir = opj(experiment_dir, 'workingdir_reconflow')\n\n # Some magical stuff happens here (not important for now)\n infosource = Node(IdentityInterface(fields=['subject_id']), name=\"infosource\")\n infosource.iterables = ('subject_id', subject_list)\n \n # Specify recon-all stage based on recon-directive\n reconall = get_reconall(recon_directive, fs_folder)\n # This section connects all the nodes of the pipeline to each other\n reconflow.connect([(infosource, reconall, [('subject_id', 'subject_id')]),\n (infosource, reconall, [(('subject_id', pathfinder,\n data_dir, T1_identifier),\n 'T1_files')]),\n ])\n \n if count_FLOPs:\n # start flop counter\n start_time = time.time()\n high.start_counters([events.PAPI_DP_OPS,]) #default: PAPI_FP_OPS\n\n # This command runs the recon-all pipeline in parallel (using n_procs cores)\n # reconflow.run('MultiProc', plugin_args={'n_procs': 4})\n reconflow.run() \n\n if count_FLOPs:\n # stop flop counter\n DP = high.stop_counters()[0]\n end_time = time.time()\n duration = end_time - start_time\n print('Duration: {}, Flops: {}'.format(duration, DP))\n\n flop_df.loc[r] = [recon_directive,start_time, duration, DP]\n\n ## code-carbon tracker\n tracker_CC.stop()\n \n if count_FLOPs:\n flop_df.to_csv(flop_csv)\n\nif __name__=='__main__':\n main()\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": [] } ]
strint/myia
[ "3d00d3fb3df80ab7a264a724226c5f56c6ff1a8a", "3d00d3fb3df80ab7a264a724226c5f56c6ff1a8a" ]
[ "examples/vae.py", "myia/operations/prim_array_scan.py" ]
[ "\"\"\"Example of an MLP in Myia.\n\nMyia is still a work in progress, and this example may change in the future.\n\"\"\"\n\nimport time\nfrom dataclasses import dataclass\n\nimport numpy\nimport torch\nfrom numpy.random import RandomState\nfrom torchvision import datasets, transforms\n\nimport myia.public_api as pub\nfrom myia import ArithmeticData, myia, value_and_grad\nfrom myia.api import to_device\nfrom myia.debug import traceback # noqa\nfrom myia.operations import array_exp, array_pow, random_initialize\n\n###########\n# Options #\n###########\n\n\ndtype = \"float32\"\n\nbackend = \"pytorch\"\n# backend = 'relay' # Uncomment to use relay backend\n\ndevice_type = \"cpu\"\n# device_type = 'cuda' # Uncomment to run on the gpu\n\nbackend_options_dict = {\n \"pytorch\": {\"device\": device_type},\n \"relay\": {\"target\": device_type, \"device_id\": 0},\n}\n\nbackend_options = backend_options_dict[backend]\n\n###############\n# Hyperparams #\n###############\n\n\nlr = getattr(numpy, dtype)(0.01)\n\n\n########\n# Data #\n########\n\n\n# This just generates random data so we don't have to load a real dataset,\n# but the model will work just as well on a real dataset.\n\n\ndef param(R, *size):\n \"\"\"Generates a random array using the generator R.\"\"\"\n return numpy.array(R.rand(*size) * 2 - 1, dtype=dtype)\n\n\ndef generate_data(n, batch_size, input_size, target_size, *, seed=87):\n \"\"\"Generate inputs and targets.\n\n Generates n batches of samples of size input_size, matched with\n a single target.\n \"\"\"\n R = RandomState(seed=seed)\n return [\n (param(R, batch_size, input_size), param(R, batch_size, target_size))\n for i in range(n)\n ]\n\n\ndef mlp_parameters(*layer_sizes, seed=90909):\n \"\"\"Generates parameters for a MLP given a list of layer sizes.\"\"\"\n R = RandomState(seed=seed)\n parameters = []\n for i, o in zip(layer_sizes[:-1], layer_sizes[1:]):\n W = param(R, i, o)\n b = param(R, 1, o)\n parameters.append((W, b))\n return parameters\n\n\n#########\n# Model #\n#########\n\n\n# We generate a MLP model with some arbitrary number of layers and tanh\n# activations.\n\n\n@dataclass(frozen=True)\nclass Linear(ArithmeticData):\n \"\"\"Linear layer.\"\"\"\n\n W: \"Weights array\"\n b: \"Biases vector\"\n\n def apply(self, input):\n \"\"\"Apply the layer.\"\"\"\n return input @ self.W + self.b\n\n\n@dataclass(frozen=True)\nclass Tanh(ArithmeticData):\n \"\"\"Tanh layer.\"\"\"\n\n def apply(self, input):\n \"\"\"Apply the layer.\"\"\"\n return numpy.tanh(input)\n\n\n@dataclass(frozen=True)\nclass Sequential(ArithmeticData):\n \"\"\"Sequential layer, applies all sub-layers in order.\"\"\"\n\n layers: \"Tuple of layers\"\n\n def apply(self, x):\n \"\"\"Apply the layer.\"\"\"\n for layer in self.layers:\n x = layer.apply(x)\n return x\n\n\n@dataclass(frozen=True)\nclass VAE(ArithmeticData):\n \"\"\"Sequential layer, applies all sub-layers in order.\"\"\"\n\n fc1: \"layer fc1\"\n fc21: \"layer fc21\"\n fc22: \"layer fc22\"\n fc3: \"layer fc3\"\n fc4: \"layer fc4\"\n\n def encode(self, x):\n h1 = pub.relu(self.fc1.apply(x))\n return self.fc21.apply(h1), self.fc22.apply(h1)\n\n def reparameterize(self, mu, logvar, rstate):\n std = array_exp(0.5 * logvar)\n eps, rstate = pub.uniform(rstate, (2, 20), -1.0, 1.0)\n return mu + eps * std, rstate\n\n def decode(self, z):\n h3 = pub.relu(self.fc3.apply(z))\n return pub.sigmoid(self.fc4.apply(h3))\n\n def forward(self, x, rstate):\n mu, logvar = self.encode(pub.reshape(x, (-1, 784)))\n z, rstate = self.reparameterize(mu, logvar, rstate)\n return self.decode(z), mu, logvar, rstate\n\n\nparams = (\n mlp_parameters(*(784, 400))[0],\n mlp_parameters(*(400, 20))[0],\n mlp_parameters(*(400, 20))[0],\n mlp_parameters(*(20, 400))[0],\n mlp_parameters(*(400, 784))[0],\n)\n\nmodel = VAE(\n Linear(params[0][0], params[0][1]),\n Linear(params[1][0], params[1][1]),\n Linear(params[2][0], params[2][1]),\n Linear(params[3][0], params[3][1]),\n Linear(params[4][0], params[4][1]),\n)\n\nmodel = to_device(model, backend, backend_options, broaden=False)\n\n\n# Reconstruction + KL divergence losses summed over all elements and batch\ndef loss_function(recon_x, x, mu, logvar):\n BCE = pub.binary_cross_entropy(\n recon_x, pub.reshape(x, (-1, 784)), reduction=\"sum\"\n )\n\n # see Appendix B from VAE paper:\n # Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014\n # https://arxiv.org/abs/1312.6114\n # 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)\n KLD = -0.5 * pub._sum(1 + logvar - array_pow(mu, 2) - array_exp(logvar))\n\n return BCE + KLD\n\n\ndef cost(model, data, rstate):\n recon_batch, mu, logvar, _rstate = model.forward(data, rstate)\n loss = loss_function(recon_batch, data, mu, logvar)\n return loss.item(), _rstate\n\n\n@myia(backend=backend, backend_options=backend_options, return_backend=True)\ndef step(model, data, lr, rstate):\n \"\"\"Returns the loss and parameter gradients.\n\n value_and_grad will return cost(model, x, y) and dcost(...)/dmodel.\n The 'model' argument can be omitted: by default the derivative wrt\n the first argument is returned.\n \"\"\"\n (_cost, rstate), dmodel = value_and_grad(cost, \"model\")(\n model, data, rstate, dout=(1, 1)\n )\n return _cost, model - lr * dmodel, rstate\n\n\n@myia(backend=backend, backend_options=backend_options, return_backend=True)\ndef step_eval(model, data, rstate):\n \"\"\"Returns the loss and parameter gradients.\n\n value_and_grad will return cost(model, x, y) and dcost(...)/dmodel.\n The 'model' argument can be omitted: by default the derivative wrt\n the first argument is returned.\n \"\"\"\n return cost(model, data, rstate)\n\n\n@myia(backend=backend, backend_options=backend_options, return_backend=True)\ndef step_init_seed():\n \"\"\"Returns the loss and parameter gradients.\n\n value_and_grad will return cost(model, x, y) and dcost(...)/dmodel.\n The 'model' argument can be omitted: by default the derivative wrt\n the first argument is returned.\n \"\"\"\n return random_initialize(1)\n\n\nlr = getattr(numpy, dtype)(0.01)\n\nif __name__ == \"__main__\":\n seed = 123\n cuda = False\n batch_size = 2\n epochs = 1\n\n torch.manual_seed(seed)\n\n device = torch.device(\"cuda\" if cuda else \"cpu\")\n\n kwargs = {\"num_workers\": 1, \"pin_memory\": True} if cuda else {}\n train_loader = torch.utils.data.DataLoader(\n datasets.MNIST(\n \"../data\",\n train=True,\n download=True,\n transform=transforms.ToTensor(),\n ),\n batch_size=batch_size,\n shuffle=True,\n **kwargs,\n )\n\n rand_state = step_init_seed()\n\n for _ in range(epochs):\n costs = []\n t0 = time.time()\n for i, (data, _) in enumerate(train_loader):\n print(\"i\", i + 1, \"/\", len(train_loader))\n _cost, model, rand_state = step(\n model, data.reshape((batch_size, 784)).numpy(), lr, rand_state\n )\n costs.append(_cost)\n costs = [float(c.from_device()) for c in costs]\n c = sum(costs) / len(costs)\n t = time.time() - t0\n print(f\"Cost: {c:15.10f}\\tTime: {t:15.10f}\")\n\n test_loader = torch.utils.data.DataLoader(\n datasets.MNIST(\"../data\", train=False, transform=transforms.ToTensor()),\n batch_size=batch_size,\n shuffle=True,\n **kwargs,\n )\n\n costs = []\n t0 = time.time()\n for i, (data, _) in enumerate(test_loader):\n _cost, rand_state = step_eval(\n model, data.reshape((batch_size, 784)).numpy(), rand_state\n )\n costs.append(_cost)\n costs = [float(c.from_device()) for c in costs]\n c = sum(costs) / len(costs)\n t = time.time() - t0\n print(f\"Cost: {c:15.10f}\\tTime: {t:15.10f}\")\n", "\"\"\"Definitions for the primitive `array_scan`.\"\"\"\n\nimport numpy as np\n\nfrom . import primitives as P\n\n\ndef pyimpl_array_scan(fn, init, array, axis):\n \"\"\"Implement `array_scan`.\"\"\"\n # This is inclusive scan because it's easier to implement\n # We will have to discuss what semantics we want later\n def f(ary):\n val = init\n it = np.nditer([ary, None])\n for x, y in it:\n val = fn(val, x)\n y[...] = val\n return it.operands[1]\n\n return np.apply_along_axis(f, axis, array)\n\n\ndef debugvm_array_scan(vm, fn, init, array, axis):\n \"\"\"Implement `array_scan` for the debug VM.\"\"\"\n\n def fn_(a, b):\n return vm.call(fn, [a, b])\n\n return pyimpl_array_scan(fn_, init, array, axis)\n\n\n__operation_defaults__ = {\n \"name\": \"array_scan\",\n \"registered_name\": \"array_scan\",\n \"mapping\": P.array_scan,\n \"python_implementation\": pyimpl_array_scan,\n}\n\n\n__primitive_defaults__ = {\n \"name\": \"array_scan\",\n \"registered_name\": \"array_scan\",\n \"type\": \"backend\",\n \"python_implementation\": pyimpl_array_scan,\n \"debugvm_implementation\": debugvm_array_scan,\n \"inferrer_constructor\": None,\n \"grad_transform\": None,\n}\n" ]
[ [ "torch.device", "torch.manual_seed", "numpy.tanh", "numpy.random.RandomState" ], [ "numpy.apply_along_axis", "numpy.nditer" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
GlobalMaksimum/sadedegel
[ "8e28dbeabc3bf0d6f2222089ac5e3a849f9d3a6b" ]
[ "sadedegel/bblock/vocabulary.py" ]
[ "import warnings\nfrom collections import defaultdict\nfrom os.path import dirname\nfrom pathlib import Path\n\nimport h5py\nimport numpy as np\nfrom cached_property import cached_property\nfrom rich.console import Console\n\nfrom .util import tr_lower, normalize_tokenizer_name\n\nconsole = Console()\n\n\nclass InvalidTokenizer(Exception):\n \"\"\"Invalid tokenizer name\"\"\"\n\n\ndef vocabulary_file(tokenizer: str, verify_exists=True):\n normalized_name = normalize_tokenizer_name(tokenizer)\n\n if normalized_name not in ['bert', 'icu', 'simple']:\n raise InvalidTokenizer(\n (f\"Currently only valid tokenizers are BERT, ICU Tokenizer for vocabulary generation.\"\n \" {normalized_name} found\"))\n\n vocab_file = Path(dirname(__file__)) / 'data' / normalized_name / 'vocabulary.hdf5'\n\n if not vocab_file.exists() and verify_exists:\n raise FileNotFoundError(f\"Vocabulary file for {tokenizer} ({normalized_name}) tokenizer not found.\")\n\n return vocab_file\n\n\nclass VocabularyCounter:\n def __init__(self, tokenizer, case_sensitive=True, min_tf=1, min_df=1):\n self.tokenizer = tokenizer\n\n self.doc_counter = defaultdict(set)\n self.doc_set = set()\n\n self.term_freq = defaultdict(int)\n\n self.min_tf = min_tf\n self.min_df = min_df\n self.case_sensitive = case_sensitive\n\n def inc(self, word: str, document_id: int, count: int = 1):\n if self.case_sensitive:\n w = word\n else:\n w = tr_lower(word)\n\n self.doc_counter[w].add(document_id)\n self.doc_set.add(document_id)\n self.term_freq[w] += count\n\n def add_word_to_doc(self, word: str, document_id: int):\n \"\"\"Implemented for backward compatibility\"\"\"\n\n self.inc(word, document_id, 1)\n\n @property\n def vocabulary_size(self):\n return len(self.term_freq)\n\n @property\n def document_count(self):\n return len(self.doc_set)\n\n def prune(self):\n\n to_remove = []\n\n for w in self.term_freq:\n if self.term_freq[w] < self.min_tf or len(self.doc_counter[w]) < self.min_df:\n to_remove.append(w)\n\n for w in to_remove:\n del self.doc_counter[w]\n del self.term_freq[w]\n\n console.log(\n f\"{len(to_remove)} terms (case sensitive={self.case_sensitive}) are pruned by tf (>= {self.min_tf}) or df filter(>= {self.min_df})\")\n\n return self\n\n def df(self, w: str):\n if self.case_sensitive:\n return len(self.doc_counter[w])\n else:\n return len(self.doc_counter[tr_lower(w)])\n\n def tf(self, w: str):\n if self.case_sensitive:\n return self.term_freq[w]\n else:\n return self.term_freq[tr_lower(w)]\n\n def to_hdf5(self, w2v=None):\n with h5py.File(vocabulary_file(self.tokenizer, verify_exists=False), \"a\") as fp:\n if self.case_sensitive:\n group = fp.create_group(\"form_\")\n else:\n group = fp.create_group(\"lower_\")\n\n words = sorted(list(self.term_freq.keys()), key=lambda w: tr_lower(w))\n\n group.attrs['size'] = len(words)\n group.attrs['document_count'] = len(self.doc_set)\n group.attrs['tokenizer'] = self.tokenizer\n group.attrs['min_tf'] = self.min_tf\n group.attrs['min_df'] = self.min_df\n\n if w2v is not None:\n group.attrs['vector_size'] = w2v.vector_size\n\n group.create_dataset(\"vector\", data=np.array(\n [w2v[w] if w in w2v else np.zeros(w2v.vector_size) for w in words]).astype(\n np.float32),\n compression=\"gzip\",\n compression_opts=9)\n group.create_dataset(\"has_vector\", data=np.array([w in w2v in w2v for w in words]),\n compression=\"gzip\",\n compression_opts=9)\n\n group.create_dataset(\"word\", data=words, compression=\"gzip\", compression_opts=9)\n group.create_dataset(\"df\", data=np.array([self.df(w) for w in words]), compression=\"gzip\",\n compression_opts=9)\n group.create_dataset(\"tf\", data=np.array([self.tf(w) for w in words]), compression=\"gzip\",\n compression_opts=9)\n\n console.print(f\"|D|: {self.document_count}, |V|: {self.vocabulary_size} (case sensitive={self.case_sensitive})\")\n\n\nclass Vocabulary:\n\n def __init__(self, tokenizer):\n self.tokenizer = tokenizer\n\n self.file_name = vocabulary_file(tokenizer)\n self._df = None\n self._df_cs = None\n self._has_vector = None\n self._vector = None\n\n self.dword_cs = None\n self.dword = None\n\n @cached_property\n def size_cs(self) -> int:\n with h5py.File(self.file_name, \"r\") as fp:\n return fp['form_'].attrs['size']\n\n @cached_property\n def size(self) -> int:\n with h5py.File(self.file_name, \"r\") as fp:\n return fp['lower_'].attrs['size']\n\n def __len__(self):\n return self.size\n\n def id_cs(self, word: str, default: int = -1):\n if self.dword_cs is None:\n with h5py.File(self.file_name, \"r\") as fp:\n self.dword = dict((b.decode(\"utf-8\"), i) for i, b in enumerate(list(fp['lower_']['word'])))\n self.dword_cs = dict((b.decode(\"utf-8\"), i) for i, b in enumerate(list(fp['form_']['word'])))\n\n return self.dword_cs.get(word, default)\n\n def id(self, word: str, default: int = -1):\n if self.dword is None:\n with h5py.File(self.file_name, \"r\") as fp:\n self.dword = dict((b.decode(\"utf-8\"), i) for i, b in enumerate(list(fp['lower_']['word'])))\n self.dword_cs = dict((b.decode(\"utf-8\"), i) for i, b in enumerate(list(fp['form_']['word'])))\n\n return self.dword.get(tr_lower(word), default)\n\n def df(self, word: str):\n\n i = self.id(word)\n\n if i == -1:\n return 0\n else:\n if self._df is None:\n with h5py.File(self.file_name, \"r\") as fp:\n self._df = np.array(fp['lower_']['df'])\n\n return self._df[i]\n\n def df_cs(self, word: str):\n\n i = self.id_cs(word)\n\n if i == -1:\n return 0\n else:\n if self._df_cs is None:\n with h5py.File(self.file_name, \"r\") as fp:\n self._df_cs = np.array(fp['form_']['df'])\n\n return self._df_cs[i]\n\n def has_vector(self, word: str):\n with h5py.File(self.file_name, \"r\") as fp:\n if \"has_vector\" in fp['lower_']:\n i = self.id(word)\n\n if i == -1:\n return False\n else:\n if self._has_vector is None:\n self._has_vector = np.array(fp['lower_']['has_vector'])\n\n return self._has_vector[i]\n else:\n return False\n\n def vector(self, word: str):\n # TODO: Performance improvement required\n with h5py.File(self.file_name, \"r\") as fp:\n if \"vector\" in fp['lower_']:\n i = self.id(word)\n\n if i == -1:\n return False\n else:\n if self._vector is None:\n self._vector = np.array(fp['lower_']['vector'])\n\n return self._vector[i, :]\n else:\n return False\n\n @cached_property\n def document_count(self):\n with h5py.File(self.file_name, \"r\") as fp:\n return fp['form_'].attrs['document_count']\n" ]
[ [ "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
xujing1994/open_spiel
[ "7663a2717f16ff84c0d6a6bfdf19a9c21b37b765" ]
[ "open_spiel/python/examples/hearts_supervised_learning.py" ]
[ "# Copyright 2019 DeepMind Technologies Ltd. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"Train a policy net on Hearts actions based given a dataset of trajectories.\n\nTrajectories from the Hearts bot Xinxin can be generated using\nopen_spiel/games/hearts/xinxin_game_generator.cc.\n\"\"\"\n\nimport os\nimport pickle\nfrom typing import Any, Tuple\n\nfrom absl import app\nfrom absl import flags\n\nimport haiku as hk\nimport jax\nfrom jax import numpy as jnp\nfrom jax.experimental import optix\nimport numpy as np\n\nimport pyspiel\n\nOptState = Any\nParams = Any\n\nFLAGS = flags.FLAGS\nGAME = pyspiel.load_game('hearts')\nNUM_CARDS = 52\nNUM_ACTIONS = NUM_CARDS\nNUM_PLAYERS = 4\nTOP_K_ACTIONS = 5 # How many alternative actions to display\nDEFAULT_LAYER_SIZES = [1024, 1024, 1024, 1024]\n\nflags.DEFINE_integer('iterations', 100000, 'Number of iterations')\nflags.DEFINE_string('data_path', None, 'Location for data')\nflags.DEFINE_integer('eval_every', 10000, 'How often to evaluate the policy')\nflags.DEFINE_integer('num_examples', 3,\n 'How many examples to print per evaluation')\nflags.DEFINE_integer('train_batch', 128, 'Batch size for training step')\nflags.DEFINE_integer('eval_batch', 10000, 'Batch size when evaluating')\nflags.DEFINE_float('step_size', 1e-4, 'Step size for training')\nflags.DEFINE_list('hidden_layer_sizes', None,\n 'Number of hidden units and layers in the network')\nflags.DEFINE_integer('rng_seed', 42, 'Seed for initial network weights')\nflags.DEFINE_string('save_path', None, 'Location for saved networks')\nflags.DEFINE_string('checkpoint_file', None,\n 'Provides weights and optimzer state to resume training')\n\n\ndef _trajectory(line: str):\n \"\"\"Returns parsed action trajectory.\"\"\"\n actions = [int(x) for x in line.split(' ')]\n return tuple(actions)\n\n\ndef make_dataset(file: str):\n \"\"\"Creates dataset as a generator of single examples.\"\"\"\n lines = [line for line in open(file)]\n while True:\n np.random.shuffle(lines)\n for line in lines:\n trajectory = _trajectory(line)\n # skip pass_dir and deal actions\n action_index = np.random.randint(NUM_CARDS + 1, len(trajectory))\n state = GAME.new_initial_state()\n for action in trajectory[:action_index]:\n state.apply_action(action)\n yield (state.information_state_tensor(), trajectory[action_index])\n\n\ndef batch(dataset, batch_size: int):\n \"\"\"Creates a batched dataset from a one-at-a-time dataset.\"\"\"\n observations = np.zeros([batch_size] + GAME.information_state_tensor_shape(),\n np.float32)\n labels = np.zeros(batch_size, dtype=np.int32)\n while True:\n for batch_index in range(batch_size):\n observations[batch_index], labels[batch_index] = next(dataset)\n yield observations, labels\n\n\ndef one_hot(x, k):\n \"\"\"Returns a one-hot encoding of `x` of size `k`.\"\"\"\n return jnp.array(x[..., jnp.newaxis] == jnp.arange(k), dtype=np.float32)\n\n\ndef net_fn(x):\n \"\"\"Haiku module for our network.\"\"\"\n layers = []\n for layer_size in FLAGS.hidden_layer_sizes:\n layers.append(hk.Linear(int(layer_size)))\n layers.append(jax.nn.relu)\n layers.append(hk.Linear(NUM_ACTIONS))\n layers.append(jax.nn.log_softmax)\n net = hk.Sequential(layers)\n return net(x)\n\n\ndef main(argv):\n if len(argv) > 1:\n raise app.UsageError('Too many command-line arguments.')\n\n if FLAGS.hidden_layer_sizes is None:\n # Cannot pass default arguments as lists due to style requirements, so we\n # override it here if they are not set.\n FLAGS.hidden_layer_sizes = DEFAULT_LAYER_SIZES\n\n # Make the network.\n net = hk.without_apply_rng(hk.transform(net_fn, apply_rng=True))\n\n # Make the optimiser.\n opt = optix.adam(FLAGS.step_size)\n\n @jax.jit\n def loss(\n params: Params,\n inputs: np.ndarray,\n targets: np.ndarray,\n ) -> jnp.DeviceArray:\n \"\"\"Cross-entropy loss.\"\"\"\n assert targets.dtype == np.int32\n log_probs = net.apply(params, inputs)\n return -jnp.mean(one_hot(targets, NUM_ACTIONS) * log_probs)\n\n @jax.jit\n def accuracy(\n params: Params,\n inputs: np.ndarray,\n targets: np.ndarray,\n ) -> jnp.DeviceArray:\n \"\"\"Classification accuracy.\"\"\"\n predictions = net.apply(params, inputs)\n return jnp.mean(jnp.argmax(predictions, axis=-1) == targets)\n\n @jax.jit\n def update(\n params: Params,\n opt_state: OptState,\n inputs: np.ndarray,\n targets: np.ndarray,\n ) -> Tuple[Params, OptState]:\n \"\"\"Learning rule (stochastic gradient descent).\"\"\"\n _, gradient = jax.value_and_grad(loss)(params, inputs, targets)\n updates, opt_state = opt.update(gradient, opt_state)\n new_params = optix.apply_updates(params, updates)\n return new_params, opt_state\n\n def output_samples(params: Params, max_samples: int):\n \"\"\"Output some cases where the policy disagrees with the dataset action.\"\"\"\n if max_samples == 0:\n return\n count = 0\n with open(os.path.join(FLAGS.data_path, 'test.txt')) as f:\n lines = list(f)\n np.random.shuffle(lines)\n for line in lines:\n state = GAME.new_initial_state()\n actions = _trajectory(line)\n for action in actions:\n if not state.is_chance_node():\n observation = np.array(state.information_state_tensor(), np.float32)\n policy = np.exp(net.apply(params, observation))\n probs_actions = [(p, a) for a, p in enumerate(policy)]\n pred = max(probs_actions)[1]\n if pred != action:\n print(state)\n for p, a in reversed(sorted(probs_actions)[-TOP_K_ACTIONS:]):\n print('{:7} {:.2f}'.format(state.action_to_string(a), p))\n print('Ground truth {}\\n'.format(state.action_to_string(action)))\n count += 1\n break\n state.apply_action(action)\n if count >= max_samples:\n return\n\n # Store what we need to rebuild the Haiku net.\n if FLAGS.save_path:\n filename = os.path.join(FLAGS.save_path, 'layers.txt')\n with open(filename, 'w') as layer_def_file:\n for s in FLAGS.hidden_layer_sizes:\n layer_def_file.write(f'{s} ')\n layer_def_file.write('\\n')\n\n # Make datasets.\n if FLAGS.data_path is None:\n raise app.UsageError(\n 'Please generate your own supervised training data and supply the local'\n 'location as --data_path')\n train = batch(\n make_dataset(os.path.join(FLAGS.data_path, 'train.txt')),\n FLAGS.train_batch)\n test = batch(\n make_dataset(os.path.join(FLAGS.data_path, 'test.txt')), FLAGS.eval_batch)\n\n # Initialize network and optimiser.\n if FLAGS.checkpoint_file:\n with open(FLAGS.checkpoint_file, 'rb') as pkl_file:\n params, opt_state = pickle.load(pkl_file)\n else:\n rng = jax.random.PRNGKey(FLAGS.rng_seed) # seed used for network weights\n inputs, unused_targets = next(train)\n params = net.init(rng, inputs)\n opt_state = opt.init(params)\n\n # Train/eval loop.\n for step in range(FLAGS.iterations):\n # Do SGD on a batch of training examples.\n inputs, targets = next(train)\n params, opt_state = update(params, opt_state, inputs, targets)\n\n # Periodically evaluate classification accuracy on the test set.\n if (1 + step) % FLAGS.eval_every == 0:\n inputs, targets = next(test)\n test_accuracy = accuracy(params, inputs, targets)\n print(f'After {1+step} steps, test accuracy: {test_accuracy}.')\n if FLAGS.save_path:\n filename = os.path.join(FLAGS.save_path, f'checkpoint-{1 + step}.pkl')\n with open(filename, 'wb') as pkl_file:\n pickle.dump((params, opt_state), pkl_file)\n output_samples(params, FLAGS.num_examples)\n\n\nif __name__ == '__main__':\n app.run(main)\n" ]
[ [ "numpy.zeros", "numpy.random.shuffle" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
efajardo-nv/cuml
[ "bc86714836284ed4752c267513e5d447e884e1c5" ]
[ "python/cuml/test/test_trustworthiness.py" ]
[ "# Copyright (c) 2018-2019, NVIDIA CORPORATION.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport pytest\nfrom sklearn.manifold.t_sne import trustworthiness as sklearn_trustworthiness\nfrom cuml.metrics import trustworthiness as cuml_trustworthiness\n\nfrom sklearn.datasets.samples_generator import make_blobs\nfrom umap import UMAP\n\nimport cudf\nimport numpy as np\n\n\[email protected]('input_type', ['ndarray'])\[email protected]('n_samples', [10, 100])\[email protected]('n_features', [10, 100])\[email protected]('n_components', [2, 8])\ndef test_trustworthiness(input_type, n_samples, n_features, n_components):\n centers = round(n_samples*0.4)\n X, y = make_blobs(n_samples=n_samples, centers=centers,\n n_features=n_features)\n\n X_embedded = \\\n UMAP(n_components=n_components).fit_transform(X)\n X = X.astype(np.float32)\n X_embedded = X_embedded.astype(np.float32)\n\n if input_type == 'dataframe':\n gdf = cudf.DataFrame()\n for i in range(X.shape[1]):\n gdf[str(i)] = np.asarray(X[:, i], dtype=np.float32)\n\n gdf_embedded = cudf.DataFrame()\n for i in range(X_embedded.shape[1]):\n gdf_embedded[str(i)] = np.asarray(X_embedded[:, i],\n dtype=np.float32)\n\n score = cuml_trustworthiness(gdf, gdf_embedded)\n else:\n score = cuml_trustworthiness(X, X_embedded)\n\n sk_score = sklearn_trustworthiness(X, X_embedded)\n\n eps = 0.001\n assert (sk_score * (1 - eps) <= score and\n score <= sk_score * (1 + eps))\n # assert cu_score == sk_score ideally\n" ]
[ [ "numpy.asarray", "sklearn.datasets.samples_generator.make_blobs", "sklearn.manifold.t_sne.trustworthiness" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
MikeXydas/MDSimsEval
[ "6c32bd8b74e421120beca18d18c3e58fc8f85247" ]
[ "MDSimsEval/pca_analysis.py" ]
[ "import math\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport pandas as pd\n\nfrom tqdm import tqdm\n\n\ndef scree_plot(analysis_actors_dict, dir_path, pcs_on_scree_plot=50, variance_ratio_line=0.75):\n \"\"\"\n Creates a plot with the scree plots for each ligand and saves it on the specified ``dir_path``. With blue color is\n class 1 and with orange color class 2.\n\n Args:\n analysis_actors_dict: ``{ \"Agonists\": List[AnalysisActor.class], \"Antagonists\": List[AnalysisActor.class] }``\n dir_path (str): The path of the directory the plot will be saved (must end with a ``/``)\n pcs_on_scree_plot(int): The number of the first PCs that will be used on the scree plots\n variance_ratio_line(float): Float from 0.0 to 1.0 which specifies the variance ratio that a vertical line will\n be plotted\n\n \"\"\"\n # Get the dimensions of the final plot\n plot_cols = 3\n plot_rows = math.ceil(len(analysis_actors_dict['Agonists']) + len(analysis_actors_dict['Antagonists']) / plot_cols)\n\n fig = plt.figure(figsize=(18, 6 * plot_rows))\n plot_index = 1\n\n # Agonists Iteration\n for which_ligand in analysis_actors_dict['Agonists']:\n ax = fig.add_subplot(plot_rows, plot_cols, plot_index)\n plt.axvline(x=np.where(np.cumsum(which_ligand.pca_res.explained_variance_ratio_) > variance_ratio_line)[0][0],\n ls='--', c='grey', label=f\"Reached {int(variance_ratio_line * 100)}% variance\")\n plt.plot(np.arange(len(which_ligand.pca_res.explained_variance_[:pcs_on_scree_plot])),\n which_ligand.pca_res.explained_variance_[:pcs_on_scree_plot], label=\"Variance Ratio\")\n plt.ylabel(\"Variance\")\n plt.xlabel(\"#PC\")\n plt.title(which_ligand.drug_name)\n plt.legend()\n plot_index += 1\n\n # Antagonists Iteration\n for which_ligand in analysis_actors_dict['Antagonists']:\n ax = fig.add_subplot(plot_rows, plot_cols, plot_index)\n plt.axvline(x=np.where(np.cumsum(which_ligand.pca_res.explained_variance_ratio_) > variance_ratio_line)[0][0],\n ls='--', c='grey', label=f\"Reached {int(variance_ratio_line * 100)}% variance\")\n plt.plot(np.arange(len(which_ligand.pca_res.explained_variance_[:pcs_on_scree_plot])),\n which_ligand.pca_res.explained_variance_[:pcs_on_scree_plot], label=\"Variance\", color='orange')\n plt.ylabel(\"Variance\")\n plt.xlabel(\"#PC\")\n plt.title(which_ligand.drug_name)\n plt.legend()\n plot_index += 1\n\n fig.suptitle('PCA Scree Plots\\nAgonists: Blue\\nAntagonists: Orange', fontsize=26, y=0.93)\n\n plt.savefig(f'{dir_path}pca_scree_plots.png', format='png')\n\n\ndef populate_variance_showcase_df(analysis_actors_dict, drug_type):\n \"\"\"\n Creates a DataFrame having for each drug the number of PCs needed in order to have 50%, 75% and 95% variance\n\n Args:\n analysis_actors_dict: ``{ \"Agonists\": List[AnalysisActor.class], \"Antagonists\": List[AnalysisActor.class] }``\n drug_type (str): The class name ('Agonists' or 'Antagonists')\n\n Returns:\n pd.DataFrame: A DataFrame with columns ``['Drug Name', 'Type', '50% Variance', '75% Variance', '95% Variance']``\n \"\"\"\n inp_df = pd.DataFrame(columns=['Drug Name', 'Type', '50% Variance', '75% Variance', '95% Variance'])\n for which_ligand in analysis_actors_dict[drug_type]:\n pca_var_row = pd.DataFrame([[\n which_ligand.drug_name,\n drug_type,\n np.where(np.cumsum(which_ligand.pca_res.explained_variance_ratio_) > 0.5)[0][0] + 1,\n # We +1 since the np.where will return\n np.where(np.cumsum(which_ligand.pca_res.explained_variance_ratio_) > 0.75)[0][0] + 1,\n # the 0 based index of the PC\n np.where(np.cumsum(which_ligand.pca_res.explained_variance_ratio_) > 0.95)[0][0] + 1]\n ], columns=['Drug Name', 'Type', '50% Variance', '75% Variance', '95% Variance'])\n inp_df = inp_df.append(pca_var_row, ignore_index=True)\n\n return inp_df\n\n\ndef project_pca_on_2d(analysis_actors_dict, drug_type, dir_path):\n \"\"\"\n Plots the 2d projection on the first two PCs of the atom space. The colorbar expresses the progression\n of the frames (color0 -> frame0, color1 -> last_frame).\n The plot is shown inside the function but if need can be easily be changed to return it.\n\n Args:\n analysis_actors_dict: ``{ \"Agonists\": List[AnalysisActor.class], \"Antagonists\": List[AnalysisActor.class] }``\n drug_type (str): 'Agonists' or 'Antagonists'\n dir_path (str): The path of the directory the plot will be saved (must end with a ``/``)\n\n \"\"\"\n cols = 3\n rows = math.ceil(len(analysis_actors_dict[drug_type]) / cols)\n\n fig = plt.figure(figsize=(18, 25))\n plot_index = 1\n\n for which_ligand in tqdm(analysis_actors_dict[drug_type], desc=\"Projecting \" + drug_type):\n pca_space_2D = which_ligand.pca_res.transform(\n which_ligand.pca_xyz) # Transform on the atom selection that PCA was fitted\n step = 1 # Frames we are skipping for computational reasons (if step == 1 then no frame is skipped)\n\n # Scatter Plotting\n ax = fig.add_subplot(rows, cols, plot_index)\n plt.scatter(pca_space_2D[::step, 0], pca_space_2D[::step, 1],\n c=np.arange(len(pca_space_2D) / step) / (len(pca_space_2D) / step), marker='o')\n plt.xlabel('PC1')\n plt.ylabel('PC2')\n explained_variance_2PC = which_ligand.pca_res.explained_variance_ratio_[0] + \\\n which_ligand.pca_res.explained_variance_ratio_[1]\n plt.title(f'{which_ligand.drug_name} | Structural Motion Variance: {explained_variance_2PC}')\n plt.colorbar() # Add the colorbar which goes from color0 to color1 as frames progress\n plot_index += 1\n\n fig.suptitle(f'PCA 2D Projection of {drug_type} as frames progress', fontsize=26, y=1.03)\n plt.tight_layout()\n\n plt.savefig(f'{dir_path}pca_{drug_type}_2d_projection.png', format='png')\n\n return None\n\n\ndef sort_residues_by_loadings(ligand, variance_explained=0.5):\n \"\"\"\n Having as an input **a ligand** find the loadings of each residue and return them in descending order.\n The method combines first k PCs where k is defined by the variance_explained argument.\n\n Args:\n ligand(AnalysisActor.class): An AnalysisActor object in which PCA is calculated\n variance_explained (float): Defines which PCs will be combined to calcualte the final loadings\n\n Returns:\n pd.DataFrame where ResidueId is the index and each row contains the loadings of the residue\n \"\"\"\n pca_res = ligand.get_pca()\n\n # How many pcs we need to cover variance_explained\n pcs_numb = np.where(np.cumsum(pca_res.explained_variance_ratio_) > variance_explained)[0][0] + 1\n\n # Calculate loadings using loadings = eigenvectors @ sqrt(eigenvalues)\n loadings = np.abs(pca_res.components_[:pcs_numb, :]).T @ np.sqrt(pca_res.explained_variance_[:pcs_numb])\n\n # Go from 3 * #residues columns to #residues columns, combining the 3 axes\n residue_loading = np.add.reduceat(loadings, range(0, len(loadings), 3))\n\n return pd.DataFrame(enumerate(residue_loading), columns=['ResidueId', ligand.drug_name]).set_index('ResidueId')\n\n\ndef loadings_heatmap(analysis_actors_dict, dir_path, explained_variance=0.75):\n \"\"\"\n | Creates a heatmap of the loadings of the residues for all the ligands. The blue line separates Class 1 fromClass 2\n |\n\n .. figure:: ../_static/pca_loadings_heatmap.png\n :width: 550\n :align: center\n :height: 500px\n :alt: pca loadings heatmap missing\n\n PCA Loadings Heatmap, click for higher resolution.\n\n Args:\n analysis_actors_dict: ``{ \"Agonists\": List[AnalysisActor.class], \"Antagonists\": List[AnalysisActor.class] }``\n dir_path (str): The path of the directory the plot will be saved (must end with a ``/``)\n explained_variance(float 0.0 - 1.0): Defines the number of PCs that will be used for the loadings calculation\n\n \"\"\"\n loadings_df = sort_residues_by_loadings(analysis_actors_dict['Agonists'][0], explained_variance)\n\n # Join all the loadings of each ligand\n for which_ligand in analysis_actors_dict['Agonists'][1:]:\n loadings_df = loadings_df.join(sort_residues_by_loadings(which_ligand, explained_variance))\n for which_ligand in analysis_actors_dict['Antagonists'][1:]:\n loadings_df = loadings_df.join(sort_residues_by_loadings(which_ligand, explained_variance))\n\n fig, ax = plt.subplots(figsize=(20, 15))\n\n sns.heatmap(loadings_df) # Seaborn heatmap of the loadings\n plt.axvline(len(analysis_actors_dict['Agonists'])) # Vertical line spearating agonists from antagonists\n\n ax.axis('tight')\n ax.set(xticks=np.arange(len(loadings_df.columns)), xticklabels=loadings_df.columns,\n yticks=np.arange(0, len(loadings_df.index), 10), yticklabels=np.arange(0, len(loadings_df.index), 10))\n plt.xticks(rotation=45)\n\n plt.xlabel('Ligand', fontsize=18)\n plt.ylabel('Residue Id', fontsize=18)\n plt.title(f\"Heatmap of Loadings of each ligand | Explained Variance: {int(explained_variance * 100)}%\", fontsize=18)\n plt.tight_layout()\n\n plt.savefig(f'{dir_path}pca_loadings_heatmap.png', format='png')\n\n return None\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.tight_layout", "numpy.sqrt", "matplotlib.pyplot.title", "numpy.abs", "matplotlib.pyplot.subplots", "pandas.DataFrame", "matplotlib.pyplot.savefig", "numpy.cumsum", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
sudohainguyen/MONAI
[ "a42b563acf0c7504cee18ee84c8af2eff6e948a7", "a42b563acf0c7504cee18ee84c8af2eff6e948a7", "89f8a39a1c0bc6f480522c443ee7813cea21df47" ]
[ "tests/test_rand_spatial_crop_samples.py", "tests/test_activationsd.py", "tests/test_integration_classification_2d.py" ]
[ "# Copyright 2020 MONAI Consortium\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 unittest\nimport numpy as np\nfrom parameterized import parameterized\nfrom monai.transforms import RandSpatialCropSamples\n\nTEST_CASE_1 = [\n {\"roi_size\": [3, 3, 3], \"num_samples\": 4, \"random_center\": True},\n np.random.randint(0, 2, size=[3, 3, 3, 3]),\n (3, 3, 3, 3),\n]\n\nTEST_CASE_2 = [\n {\"roi_size\": [3, 3, 3], \"num_samples\": 8, \"random_center\": False},\n np.random.randint(0, 2, size=[3, 3, 3, 3]),\n (3, 3, 3, 3),\n]\n\n\nclass TestRandSpatialCropSamples(unittest.TestCase):\n @parameterized.expand([TEST_CASE_1, TEST_CASE_2])\n def test_shape(self, input_param, input_data, expected_shape):\n result = RandSpatialCropSamples(**input_param)(input_data)\n for item in result:\n self.assertTupleEqual(item.shape, expected_shape)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright 2020 MONAI Consortium\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 unittest\nimport torch\nfrom parameterized import parameterized\nfrom monai.transforms import Activationsd\n\nTEST_CASE_1 = [\n {\"keys\": [\"pred\", \"label\"], \"sigmoid\": False, \"softmax\": [True, False], \"other\": None},\n {\"pred\": torch.tensor([[[[0.0, 1.0]], [[2.0, 3.0]]]]), \"label\": torch.tensor([[[[0.0, 1.0]], [[2.0, 3.0]]]])},\n {\n \"pred\": torch.tensor([[[[0.1192, 0.1192]], [[0.8808, 0.8808]]]]),\n \"label\": torch.tensor([[[[0.0, 1.0]], [[2.0, 3.0]]]]),\n },\n (1, 2, 1, 2),\n]\n\nTEST_CASE_2 = [\n {\"keys\": [\"pred\", \"label\"], \"sigmoid\": False, \"softmax\": False, \"other\": [lambda x: torch.tanh(x), None]},\n {\"pred\": torch.tensor([[[[0.0, 1.0], [2.0, 3.0]]]]), \"label\": torch.tensor([[[[0.0, 1.0], [2.0, 3.0]]]])},\n {\n \"pred\": torch.tensor([[[[0.0000, 0.7616], [0.9640, 0.9951]]]]),\n \"label\": torch.tensor([[[[0.0, 1.0], [2.0, 3.0]]]]),\n },\n (1, 1, 2, 2),\n]\n\nTEST_CASE_3 = [\n {\"keys\": \"pred\", \"sigmoid\": False, \"softmax\": False, \"other\": lambda x: torch.tanh(x)},\n {\"pred\": torch.tensor([[[[0.0, 1.0], [2.0, 3.0]]]])},\n {\"pred\": torch.tensor([[[[0.0000, 0.7616], [0.9640, 0.9951]]]])},\n (1, 1, 2, 2),\n]\n\n\nclass TestActivationsd(unittest.TestCase):\n @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3])\n def test_value_shape(self, input_param, test_input, output, expected_shape):\n result = Activationsd(**input_param)(test_input)\n torch.testing.assert_allclose(result[\"pred\"], output[\"pred\"])\n self.assertTupleEqual(result[\"pred\"].shape, expected_shape)\n if \"label\" in result:\n torch.testing.assert_allclose(result[\"label\"], output[\"label\"])\n self.assertTupleEqual(result[\"label\"].shape, expected_shape)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright 2020 MONAI Consortium\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 shutil\nimport subprocess\nimport tarfile\nimport tempfile\nimport unittest\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import DataLoader\n\nimport monai\nfrom monai.metrics import compute_roc_auc\nfrom monai.networks.nets import densenet121\nfrom monai.transforms import AddChannel, Compose, LoadPNG, RandFlip, RandRotate, RandZoom, ScaleIntensity, ToTensor\nfrom monai.utils import set_determinism\nfrom tests.utils import skip_if_quick\n\nTEST_DATA_URL = \"https://www.dropbox.com/s/5wwskxctvcxiuea/MedNIST.tar.gz\"\n\n\nclass MedNISTDataset(torch.utils.data.Dataset):\n def __init__(self, image_files, labels, transforms):\n self.image_files = image_files\n self.labels = labels\n self.transforms = transforms\n\n def __len__(self):\n return len(self.image_files)\n\n def __getitem__(self, index):\n return self.transforms(self.image_files[index]), self.labels[index]\n\n\ndef run_training_test(root_dir, train_x, train_y, val_x, val_y, device=torch.device(\"cuda:0\")):\n\n monai.config.print_config()\n # define transforms for image and classification\n train_transforms = Compose(\n [\n LoadPNG(image_only=True),\n AddChannel(),\n ScaleIntensity(),\n RandRotate(range_x=15, prob=0.5, keep_size=True),\n RandFlip(spatial_axis=0, prob=0.5),\n RandZoom(min_zoom=0.9, max_zoom=1.1, prob=0.5),\n ToTensor(),\n ]\n )\n train_transforms.set_random_state(1234)\n val_transforms = Compose([LoadPNG(image_only=True), AddChannel(), ScaleIntensity(), ToTensor()])\n\n # create train, val data loaders\n train_ds = MedNISTDataset(train_x, train_y, train_transforms)\n train_loader = DataLoader(train_ds, batch_size=300, shuffle=True, num_workers=10)\n\n val_ds = MedNISTDataset(val_x, val_y, val_transforms)\n val_loader = DataLoader(val_ds, batch_size=300, num_workers=10)\n\n model = densenet121(spatial_dims=2, in_channels=1, out_channels=len(np.unique(train_y))).to(device)\n loss_function = torch.nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters(), 1e-5)\n epoch_num = 4\n val_interval = 1\n\n # start training validation\n best_metric = -1\n best_metric_epoch = -1\n epoch_loss_values = list()\n metric_values = list()\n model_filename = os.path.join(root_dir, \"best_metric_model.pth\")\n for epoch in range(epoch_num):\n print(\"-\" * 10)\n print(f\"Epoch {epoch + 1}/{epoch_num}\")\n model.train()\n epoch_loss = 0\n step = 0\n for batch_data in train_loader:\n step += 1\n inputs, labels = batch_data[0].to(device), batch_data[1].to(device)\n optimizer.zero_grad()\n outputs = model(inputs)\n loss = loss_function(outputs, labels)\n loss.backward()\n optimizer.step()\n epoch_loss += loss.item()\n epoch_loss /= step\n epoch_loss_values.append(epoch_loss)\n print(f\"epoch {epoch + 1} average loss:{epoch_loss:0.4f}\")\n\n if (epoch + 1) % val_interval == 0:\n model.eval()\n with torch.no_grad():\n y_pred = torch.tensor([], dtype=torch.float32, device=device)\n y = torch.tensor([], dtype=torch.long, device=device)\n for val_data in val_loader:\n val_images, val_labels = val_data[0].to(device), val_data[1].to(device)\n y_pred = torch.cat([y_pred, model(val_images)], dim=0)\n y = torch.cat([y, val_labels], dim=0)\n auc_metric = compute_roc_auc(y_pred, y, to_onehot_y=True, softmax=True)\n metric_values.append(auc_metric)\n acc_value = torch.eq(y_pred.argmax(dim=1), y)\n acc_metric = acc_value.sum().item() / len(acc_value)\n if auc_metric > best_metric:\n best_metric = auc_metric\n best_metric_epoch = epoch + 1\n torch.save(model.state_dict(), model_filename)\n print(\"saved new best metric model\")\n print(\n f\"current epoch {epoch +1} current AUC: {auc_metric:0.4f} \"\n f\"current accuracy: {acc_metric:0.4f} best AUC: {best_metric:0.4f} at epoch {best_metric_epoch}\"\n )\n print(f\"train completed, best_metric: {best_metric:0.4f} at epoch: {best_metric_epoch}\")\n return epoch_loss_values, best_metric, best_metric_epoch\n\n\ndef run_inference_test(root_dir, test_x, test_y, device=torch.device(\"cuda:0\")):\n # define transforms for image and classification\n val_transforms = Compose([LoadPNG(image_only=True), AddChannel(), ScaleIntensity(), ToTensor()])\n val_ds = MedNISTDataset(test_x, test_y, val_transforms)\n val_loader = DataLoader(val_ds, batch_size=300, num_workers=10)\n\n model = densenet121(spatial_dims=2, in_channels=1, out_channels=len(np.unique(test_y))).to(device)\n\n model_filename = os.path.join(root_dir, \"best_metric_model.pth\")\n model.load_state_dict(torch.load(model_filename))\n model.eval()\n y_true = list()\n y_pred = list()\n with torch.no_grad():\n for test_data in val_loader:\n test_images, test_labels = test_data[0].to(device), test_data[1].to(device)\n pred = model(test_images).argmax(dim=1)\n for i in range(len(pred)):\n y_true.append(test_labels[i].item())\n y_pred.append(pred[i].item())\n tps = [np.sum((np.asarray(y_true) == idx) & (np.asarray(y_pred) == idx)) for idx in np.unique(test_y)]\n return tps\n\n\nclass IntegrationClassification2D(unittest.TestCase):\n def setUp(self):\n set_determinism(seed=0)\n self.data_dir = tempfile.mkdtemp()\n\n # download\n subprocess.call([\"wget\", \"-nv\", \"-P\", self.data_dir, TEST_DATA_URL])\n dataset_file = os.path.join(self.data_dir, \"MedNIST.tar.gz\")\n assert os.path.exists(dataset_file)\n\n # extract tarfile\n datafile = tarfile.open(dataset_file)\n datafile.extractall(path=self.data_dir)\n datafile.close()\n\n # find image files and labels\n data_dir = os.path.join(self.data_dir, \"MedNIST\")\n class_names = sorted((x for x in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir, x))))\n image_files = [\n [os.path.join(data_dir, class_name, x) for x in sorted(os.listdir(os.path.join(data_dir, class_name)))]\n for class_name in class_names\n ]\n image_file_list, image_classes = [], []\n for i, _ in enumerate(class_names):\n image_file_list.extend(image_files[i])\n image_classes.extend([i] * len(image_files[i]))\n\n # split train, val, test\n valid_frac, test_frac = 0.1, 0.1\n self.train_x, self.train_y = [], []\n self.val_x, self.val_y = [], []\n self.test_x, self.test_y = [], []\n for i in range(len(image_classes)):\n rann = np.random.random()\n if rann < valid_frac:\n self.val_x.append(image_file_list[i])\n self.val_y.append(image_classes[i])\n elif rann < test_frac + valid_frac:\n self.test_x.append(image_file_list[i])\n self.test_y.append(image_classes[i])\n else:\n self.train_x.append(image_file_list[i])\n self.train_y.append(image_classes[i])\n\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu:0\")\n\n def tearDown(self):\n set_determinism(seed=None)\n shutil.rmtree(self.data_dir)\n\n @skip_if_quick\n def test_training(self):\n repeated = []\n for i in range(2):\n torch.manual_seed(0)\n\n repeated.append([])\n losses, best_metric, best_metric_epoch = run_training_test(\n self.data_dir, self.train_x, self.train_y, self.val_x, self.val_y, device=self.device\n )\n\n # check training properties\n np.testing.assert_allclose(\n losses, [0.7797081090842083, 0.16179659706392105, 0.07446704363557184, 0.045996826011568875], rtol=1e-3\n )\n repeated[i].extend(losses)\n print(\"best metric\", best_metric)\n np.testing.assert_allclose(best_metric, 0.9999268330306007, rtol=1e-4)\n repeated[i].append(best_metric)\n np.testing.assert_allclose(best_metric_epoch, 4)\n model_file = os.path.join(self.data_dir, \"best_metric_model.pth\")\n self.assertTrue(os.path.exists(model_file))\n\n infer_metric = run_inference_test(self.data_dir, self.test_x, self.test_y, device=self.device)\n\n # check inference properties\n np.testing.assert_allclose(np.asarray(infer_metric), [1031, 895, 981, 1033, 960, 1047], atol=1)\n repeated[i].extend(infer_metric)\n\n np.testing.assert_allclose(repeated[0], repeated[1])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.random.randint" ], [ "torch.tanh", "torch.testing.assert_allclose", "torch.tensor" ], [ "torch.nn.CrossEntropyLoss", "numpy.random.random", "torch.load", "numpy.unique", "torch.manual_seed", "numpy.asarray", "torch.cat", "torch.utils.data.DataLoader", "torch.tensor", "torch.no_grad", "torch.cuda.is_available", "numpy.testing.assert_allclose", "torch.device" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
pau557/dimod
[ "d3c6d3abf23182b035e1100c46f7c947202edefb" ]
[ "dimod/generators/chimera.py" ]
[ "# Copyright 2018 D-Wave Systems Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# =============================================================================\nfrom __future__ import absolute_import\n\nimport numpy as np\nimport numpy.random\n\nfrom dimod.binary_quadratic_model import BinaryQuadraticModel\nfrom dimod.decorators import graph_argument\nfrom dimod.vartypes import SPIN\n\n__all__ = ['chimera_anticluster']\n\n\n@graph_argument('subgraph', allow_None=True)\ndef chimera_anticluster(m, n=None, t=4, multiplier=3.0,\n cls=BinaryQuadraticModel, subgraph=None, seed=None):\n \"\"\"Generate an anticluster problem on a Chimera lattice.\n\n An anticluster problem has weak interactions within a tile and strong\n interactions between tiles.\n\n Args:\n m (int):\n Number of rows in the Chimera lattice.\n\n n (int, optional, default=m):\n Number of columns in the Chimera lattice.\n\n t (int, optional, default=t):\n Size of the shore within each Chimera tile.\n\n multiplier (number, optional, default=3.0):\n Strength of the intertile edges.\n\n cls (type, optional):\n Binary quadratic model class to build from. Default is\n :class:`.BinaryQuadraticModel`.\n\n subgraph (int/tuple[nodes, edges]/list[edge]/:obj:`~networkx.Graph`):\n A subgraph of a Chimera(m, n, t) graph to build the anticluster\n problem on.\n\n seed (int, optional, default=None):\n Random seed.\n\n Returns:\n :obj:`.BinaryQuadraticModel`: spin-valued binary quadratic model.\n\n \"\"\"\n if seed is None:\n seed = numpy.random.randint(2**32, dtype=np.uint32)\n r = numpy.random.RandomState(seed)\n\n m = int(m)\n if n is None:\n n = m\n else:\n n = int(n)\n t = int(t)\n\n ldata = np.zeros(m*n*t*2) # number of nodes\n\n if m and n and t:\n inrow, incol = zip(*_iter_chimera_tile_edges(m, n, t))\n\n if m > 1 or n > 1:\n outrow, outcol = zip(*_iter_chimera_intertile_edges(m, n, t))\n else:\n outrow = outcol = tuple()\n\n qdata = r.choice((-1., 1.), size=len(inrow)+len(outrow))\n\n qdata[len(inrow):] *= multiplier\n\n irow = inrow + outrow\n icol = incol + outcol\n\n else:\n irow = icol = qdata = tuple()\n\n bqm = cls.from_numpy_vectors(ldata, (irow, icol, qdata), 0.0, SPIN)\n\n if subgraph is not None:\n nodes, edges = subgraph\n\n subbqm = cls.empty(SPIN)\n\n try:\n subbqm.add_variables_from((v, bqm.linear[v]) for v in nodes)\n\n except KeyError:\n msg = \"given 'subgraph' contains nodes not in Chimera({}, {}, {})\".format(m, n, t)\n raise ValueError(msg)\n\n try:\n subbqm.add_interactions_from((u, v, bqm.adj[u][v]) for u, v in edges)\n except KeyError:\n msg = \"given 'subgraph' contains edges not in Chimera({}, {}, {})\".format(m, n, t)\n raise ValueError(msg)\n\n bqm = subbqm\n\n return bqm\n\n\ndef _iter_chimera_tile_edges(m, n, t):\n hoff = 2 * t\n voff = n * hoff\n mi = m * voff\n ni = n * hoff\n\n # tile edges\n for edge in ((k0, k1)\n for i in range(0, ni, hoff)\n for j in range(i, mi, voff)\n for k0 in range(j, j + t)\n for k1 in range(j + t, j + 2 * t)):\n yield edge\n\n\ndef _iter_chimera_intertile_edges(m, n, t):\n hoff = 2 * t\n voff = n * hoff\n mi = m * voff\n ni = n * hoff\n\n # horizontal edges\n for edge in ((k, k + hoff)\n for i in range(t, 2 * t)\n for j in range(i, ni - hoff, hoff)\n for k in range(j, mi, voff)):\n yield edge\n\n # vertical edges\n for edge in ((k, k + voff)\n for i in range(t)\n for j in range(i, ni, hoff)\n for k in range(j, mi - voff, voff)):\n yield edge\n" ]
[ [ "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
chatto-hub-test2/Spaceboy2
[ "7b6b91baf06290e6b047ae75e7ea61cee4846b3a", "7b6b91baf06290e6b047ae75e7ea61cee4846b3a" ]
[ "chatto_transform/datastores/sqlalchemy_datastore.py", "chatto_transform/transforms/mimic/bun_transform.py" ]
[ "import pandas\nfrom ..schema.schema_base import *\nfrom .datastore_base import DataStore\nfrom .odo_datastore import OdoDataStore\nfrom ..config import config\n\nfrom functools import lru_cache, partial\n\nfrom sqlalchemy import Table, MetaData, select\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.automap import automap_base\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.compiler import compiles\nfrom sqlalchemy.sql.expression import Select, and_\nfrom sqlalchemy import sql\n\nimport io\nimport tempfile\nimport time\nimport os\nimport datetime\nimport ciso8601\nimport odo\n\nmetadatas = {}\n\ndef get_engine_metadata(engine):\n if engine in metadatas:\n return metadatas[engine]\n else:\n metadata = MetaData()\n metadata.bind = engine\n metadatas[engine] = metadata\n return metadata\n\ndef get_reflected_metadata(engine, schema_name=None):\n metadata = MetaData()\n metadata.reflect(bind=engine, schema=schema_name)\n metadata.bind = engine\n return metadata\n\n########################################################################\n\nfor col_type in [dt, delta, num, bool_]:\n col_type._storage_target_registry['sqlalchemy'] = col_type._storage_target_registry['pandas'].copy()\n\[email protected]_check('sqlalchemy')\ndef _(col):\n return col.dtype == 'object' \n\[email protected]_transform('sqlalchemy')\ndef _(col):\n return col.astype('object')\n\n@id_.register_check('sqlalchemy')\ndef _(col):\n return col.dtype == 'object'\n\n@id_.register_transform('sqlalchemy')\ndef _(col):\n return col.astype('object')\n\n########################################################################\n\[email protected]_metadata('sqlalchemy')\ndef _(self):\n return sql.schema.Column(self.name, sql.sqltypes.Text, nullable=True)\n\n@id_.register_metadata('sqlalchemy')\ndef _(self):\n return sql.schema.Column(self.name, sql.sqltypes.Integer, nullable=True)\n\[email protected]_metadata('sqlalchemy')\ndef _(self):\n return sql.schema.Column(self.name, sql.sqltypes.DateTime(timezone=True), nullable=True)\n\[email protected]_metadata('sqlalchemy')\ndef _(self):\n return sql.schema.Column(self.name, sql.sqltypes.Interval, nullable=True)\n\n@big_dt.register_metadata('sqlalchemy')\ndef _(self):\n return sql.schema.Column(self.name, sql.sqltypes.DateTime(timezone=True), nullable=True)\n\[email protected]_metadata('sqlalchemy')\ndef _(self):\n return sql.schema.Column(self.name, sql.sqltypes.Float, nullable=True)\n\n@bool_.register_metadata('sqlalchemy')\ndef _(self):\n return sql.schema.Column(self.name, sql.sqltypes.Boolean, nullable=True)\n\n########################################################################\n\n@lru_cache()\ndef schema_as_table(schema, engine):\n if schema.options.get('temporary', False):\n prefixes = ['TEMPORARY']\n else:\n prefixes = []\n\n db_schema = schema.options.get('db_schema', None)\n metadata = get_engine_metadata(engine)\n\n return Table(schema.name, metadata, *[col.metadata('sqlalchemy') for col in schema.cols], schema=db_schema, prefixes=prefixes)\n\nsa_type_2_col_type = {\n sql.sqltypes.Integer: num,\n sql.sqltypes.String: cat,\n sql.sqltypes.Date: dt,\n sql.sqltypes.DateTime: dt,\n sql.sqltypes.Interval: delta,\n sql.sqltypes.Numeric: num,\n sql.sqltypes.Boolean: bool_\n}\n\ndef table_as_schema(table):\n schema_cols = []\n for sa_col in table.c:\n for sa_type, col_type in sa_type_2_col_type.items():\n if isinstance(sa_col.type, sa_type):\n if isinstance(sa_col.type, sql.sqltypes.Integer) and (sa_col.primary_key or sa_col.foreign_keys):\n schema_cols.append(id_(sa_col.name))\n else:\n schema_cols.append(col_type(sa_col.name))\n break\n options = {}\n if table.schema is not None:\n options['db_schema'] = table.schema\n s = Schema(table.name, schema_cols, options=options)\n return s\n\n########################################################################\n\ndef fast_sql_to_df(table, schema):\n engine = table.bind\n\n if engine.dialect.name == 'mysql':\n return fast_mysql_to_df(table, schema)\n elif engine.dialect.name == 'postgresql':\n return fast_postgresql_to_df(table, schema)\n\n ods = OdoDataStore(schema, table)\n df = ods.load()\n df = df[schema.col_names()]\n return df\n\ndef fast_mysql_to_df(table, schema):\n f = tempfile.NamedTemporaryFile('w', suffix='.csv', dir=config.data_dir+'tmp')\n try:\n f.close()\n table_name = str(table)\n if not isinstance(table, Table):\n table_name = '({})'.format(table_name)\n\n # converting to csv\n sql = \"\"\"SELECT {cols} FROM {table} INTO OUTFILE '{filename}'\n FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'\n ESCAPED BY '\\\\\\\\'\n LINES TERMINATED BY '\\n'\"\"\".format(\n cols=', '.join('`'+colname+'`' for colname in schema.col_names()),\n filename=f.name,\n table=table_name)\n\n table.bind.execute(sql)\n \n # reading csv\n df = pandas.read_csv(f.name, header=None, names=schema.col_names(), na_values=['\\\\N'])\n finally:\n os.remove(f.name)\n\n for col in schema.cols:\n if isinstance(col, dt):\n # converting datetime column\n df[col.name] = pandas.to_datetime(df[col.name], format=\"%Y-%m-%d %H:%M:%S\", coerce=True)\n if isinstance(col, big_dt):\n # converting big_dt column\n strptime = datetime.datetime.strptime\n parse_func = (lambda x: strptime(x, \"%Y-%m-%d %H:%M:%S\"))\n df[col.name] = df[col.name].map(parse_func, na_action='ignore')\n return df\n\ndef fast_postgresql_to_df(table, schema):\n engine = table.bind\n conn = engine.raw_connection()\n with conn.cursor() as cur:\n with io.StringIO() as f:\n table_name = str(table)\n if not isinstance(table, Table):\n table_name = '({})'.format(table_name)\n sql = \"COPY {table_name} TO STDOUT WITH (FORMAT CSV, HEADER TRUE)\".format(\n table_name=table_name)\n cur.copy_expert(sql, f)\n\n f.seek(0)\n df = pandas.read_csv(f)\n for col in schema.cols:\n if isinstance(col, dt):\n # converting datetime column\n df[col.name] = pandas.to_datetime(df[col.name], format=\"%Y-%m-%d %H:%M:%S\", coerce=True)\n if isinstance(col, big_dt):\n # converting big_dt column\n strptime = datetime.datetime.strptime\n parse_func = (lambda x: strptime(x, \"%Y-%m-%d %H:%M:%S\"))\n df[col.name] = df[col.name].map(parse_func, na_action='ignore')\n return df\n\ndef fast_postgresql_to_csv(table, file_path):\n engine = table.bind\n conn = engine.raw_connection()\n with conn.cursor() as cur:\n with open(file_path, 'w') as f:\n table_name = str(table)\n if not isinstance(table, Table):\n table_name = '({})'.format(table_name)\n sql = \"COPY {table_name} TO STDOUT WITH (FORMAT CSV, HEADER TRUE)\".format(\n table_name=table_name)\n cur.copy_expert(sql, f)\n\ndef fast_df_to_sql(df, table, schema):\n ods = OdoDataStore(schema, table, storage_target_type='sqlalchemy')\n ods.store(df)\n\nclass SATableDataStore(DataStore):\n def __init__(self, schema, engine, where_clauses=None):\n super().__init__(schema)\n self.engine = engine \n self.table = schema_as_table(self.schema, self.engine)\n self.where_clauses = where_clauses\n\n def storage_target(self):\n return 'sqlalchemy'\n\n def _load(self):\n query = self.table\n if self.where_clauses is not None:\n query = query.select()\n for where_clause in self.where_clauses:\n query = query.where(where_clause)\n\n df = fast_sql_to_df(query, self.schema)\n return df\n\n def to_csv(self, file_path):\n if self.engine.dialect.name != 'postgresql':\n raise NotImplementedError('converting directly to csv not supported for non-postgres databases')\n query = self.table\n if self.where_clauses is not None:\n query = query.select()\n for where_clause in self.where_clauses:\n query = query.where(where_clause)\n\n fast_postgresql_to_csv(query, file_path)\n\n def _store(self, df):\n if self.where_clauses is not None:\n raise NotImplementedError('Cannot store to a query (where_clauses must be left blank)')\n df = df.copy()\n fast_df_to_sql(self.table, self.schema)\n\n def _update(self, df):\n if self.where_clauses is not None:\n raise NotImplementedError('Cannot update to a query (where_clauses must be left blank)')\n df = df.copy()\n\n with self.engine.connect() as conn:\n temp_schema = Schema.rename(self.schema, 'temp_'+self.schema.name)\n temp_schema.options['temporary'] = True\n temp_table = schema_as_table(temp_schema, self.engine)\n\n print('storing new df in temp table')\n fast_df_to_sql(df, temp_table, temp_schema)\n\n print('updating table from matching rows')\n index = self.schema.options['index']\n update = self.table.update(\n values={\n col_name: temp_table.c[col_name] for col_name in self.schema.col_names()\n },\n whereclause=self.table.c[index] == temp_table.c[index]\n )\n update_res = conn.execute(update)\n\n print('inserting new rows into table')\n exists_query = self.table.select().where(self.table.c[index] == temp_table.c[index]).exists()\n\n insert = self.table.insert().from_select(\n temp_schema.col_names(),\n temp_table.select().where(~exists_query))\n ins_res = conn.execute(insert)\n\n def delete(self):\n if self.where_clauses is not None:\n raise NotImplementedError('Cannot delete a query (where_clauses must be left blank)')\n \n self.table.drop(self.engine)\n\n\nclass SAJoinDataStore(DataStore):\n def __init__(self, root_schema, engine, has_schemas=None, belongs_to_schemas=None, root_conditions=None, where_clauses=None):\n self.engine = engine\n self.root_schema = root_schema\n self.root_table = schema_as_table(self.root_schema, self.engine)\n \n self.has_schemas, self.has_join_conditions = self._parse_schema_list(has_schemas)\n self.has_tables = [schema_as_table(h_schema, self.engine) for h_schema in self.has_schemas]\n\n self.belongs_to_schemas, self.belongs_to_join_conditions = self._parse_schema_list(belongs_to_schemas)\n self.belongs_to_tables = [schema_as_table(b_schema, self.engine) for b_schema in self.belongs_to_schemas]\n\n self.root_conditions = root_conditions\n self.where_clauses = where_clauses\n\n schema = Schema.union([self.root_schema] + self.has_schemas + self.belongs_to_schemas, with_prefix=True, schema_name=self.root_schema.name+'_join')\n super().__init__(schema)\n\n def _parse_schema_list(self, schema_list=None):\n if schema_list is None:\n schema_list = []\n schemas = []\n join_conditions = {}\n for schema in schema_list:\n if isinstance(schema, tuple):\n schema, j_c = schema\n join_conditions[schema] = j_c\n schemas.append(schema)\n return schemas, join_conditions\n\n def storage_target(self):\n return 'sqlalchemy'\n\n def _load(self):\n root = self.root_table\n if self.root_conditions is not None:\n root = root.select().where(and_(*self.root_conditions)).alias()\n join_clause = root\n\n select_clause = []\n root_col_prefix = self.root_schema.options['prefix']\n for col in root.c:\n select_clause.append(col.label(\"{}.{}\".format(root_col_prefix, col.name)))\n\n for h_table, h_schema in zip(self.has_tables, self.has_schemas):\n col_prefix = h_schema.options['prefix']\n h_join_conditions = [root.c.id == h_table.c['{}_id'.format(root_col_prefix)]]\n for join_condition in self.has_join_conditions.get(h_schema, []):\n h_join_conditions.append(join_condition)\n join_clause = join_clause.outerjoin(h_table, and_(*h_join_conditions))\n \n for col in h_table.c:\n select_clause.append(col.label(\"{}.{}\".format(col_prefix, col.name)))\n\n for b_table, b_schema in zip(self.belongs_to_tables, self.belongs_to_schemas):\n col_prefix = b_schema.options['prefix']\n \n b_join_conditions = [root.c['{}_id'.format(col_prefix)] == b_table.c.id]\n for join_condition in self.belongs_to_join_conditions.get(b_schema, []):\n b_join_conditions.append(join_condition)\n join_clause = join_clause.outerjoin(b_table, and_(*b_join_conditions))\n \n for col in b_table.c:\n select_clause.append(col.label(\"{}.{}\".format(col_prefix, col.name)))\n\n temp_schema = Schema.rename(self.schema, 'temp_'+self.schema.name)\n temp_table = schema_as_table(temp_schema, self.engine) \n try:\n temp_table.create(self.engine)\n\n query = select(select_clause).select_from(join_clause)\n if self.where_clauses is not None:\n query = query.where(and_(*self.where_clauses))\n\n insert = temp_table.insert().from_select(temp_schema.col_names(), query)\n\n start = time.time()\n \n print('executing join into temp table')\n self.engine.execute(insert)\n joined = time.time()\n\n print('loading rows from temp table')\n df = fast_sql_to_df(temp_table, temp_schema)\n loaded = time.time()\n finally:\n temp_table.drop(self.engine)\n\n print('type checking and sorting')\n \n print('took', joined - start, 'seconds to perform the join')\n print('took', loaded - joined, 'seconds to load the results')\n \n return df\n\nclass SAQueryDataStore(DataStore):\n def __init__(self, schema, engine, query):\n self.engine = engine\n self.query = query\n self.schema = schema\n\n def _load(self):\n df = pandas.read_sql(self.query, self.engine)\n \n return df\n", "from chatto_transform.transforms.transform_base import Transform\n\nfrom chatto_transform.schema import schema_base as sb\nfrom chatto_transform.schema.mimic.mimic_schema import labevents_schema, d_patients_schema\n\nfrom chatto_transform.lib.mimic.session import load_table\n\nimport pandas as pd\nimport numpy as np\n\n\"\"\"\nselect bucket, count(*) from (\n select width_bucket(valuenum, 0, 280, 280) as bucket\n from mimic2v26.labevents le,\n mimic2v26.d_patients dp\n where itemid in (50177)\n and le.subject_id = dp.subject_id\n and months_between(le.charttime, dp.dob)/12 > 15\n ) group by bucket order by bucket;\n\"\"\"\n\nclass BUNTransform(Transform):\n def input_schema(self):\n return sb.MultiSchema({\n 'labevents': labevents_schema,\n 'd_patients': d_patients_schema\n })\n\n def _load(self):\n \"\"\"Load the two tables (labevents and d_patients) separately.\n Since labevents is a very large table we select a subset of it before loading.\"\"\"\n\n bun_labevents = load_table(labevents_schema, \"itemid=50177\")\n d_patients = load_table(d_patients_schema)\n\n return {'labevents': bun_labevents, 'd_patients': d_patients}\n\n def _transform(self, tables):\n \"\"\"Join the two tables on subject_id and convert their age to years,\n cutting off at <15 and >100\"\"\"\n labevents = tables['labevents']\n d_patients = tables['d_patients']\n\n \n labevents_schema.add_prefix(labevents)\n d_patients_schema.add_prefix(d_patients)\n\n df = pd.merge(labevents, d_patients, how='left',\n left_on='labevents.subject_id', right_on='d_patients.subject_id')\n\n age = df['labevents.charttime'] - df['d_patients.dob']\n age = age / np.timedelta64(1, 'Y') #convert to years\n age = np.floor(age) #round to nearest year\n df['age_at_labevent'] = age\n df = df[age >= 15]\n\n df['labevents.valuenum'] = np.floor(df['labevents.valuenum'])\n df = df[(df['labevents.valuenum'] >= 0) & (df['labevents.valuenum'] <= 280)]\n\n df['bun'] = df['labevents.valuenum']\n\n return df\n\nclass BUNHistTransform(Transform):\n def input_schema(self):\n return sb.PartialSchema('bun', [\n sb.num('bun')\n ])\n\n def _transform(self, bun_df):\n bun_counts = bun_df['bun'].value_counts().sort_index()\n\n return pd.DataFrame(bun_counts, columns=['count'])\n\n\n\n\n\n" ]
[ [ "pandas.to_datetime", "pandas.read_csv", "pandas.read_sql" ], [ "numpy.timedelta64", "pandas.merge", "numpy.floor", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "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": [] } ]
ml-evs/ilustrado
[ "3121ecaff9cb517f3946b2283bf50dce499caad9" ]
[ "ilustrado/util.py" ]
[ "# coding: utf-8\n\n\"\"\" Catch-all file for utility functions.\n\n\"\"\"\n\nimport sys\nimport logging\n\nimport numpy as np\nfrom matador.compute import ComputeTask\nfrom matador.utils.cell_utils import cart2frac, cart2abc\n\nLOG = logging.getLogger(\"ilustrado\")\nLOG.setLevel(logging.DEBUG)\n\n\ndef strip_useless(doc, to_run=False):\n \"\"\" Strip useless information from a matador doc.\n\n Parameters:\n doc (dict): structure to strip information from.\n\n Arguments:\n to_run (bool): whether the structure needs to be rerun,\n i.e. whether to delete data from previous run.\n\n Returns:\n dict: matador document stripped of useless keys\n\n \"\"\"\n stripped_doc = dict()\n if to_run:\n keys = [\n \"source\",\n \"parents\",\n \"mutations\",\n \"elems\",\n \"stoichiometry\",\n \"lattice_abc\",\n \"lattice_cart\",\n \"positions_frac\",\n \"num_atoms\",\n \"atom_types\",\n ]\n else:\n keys = [\n \"source\",\n \"parents\",\n \"mutations\",\n \"elems\",\n \"stoichiometry\",\n \"lattice_abc\",\n \"lattice_cart\",\n \"cell_volume\",\n \"space_group\",\n \"positions_frac\",\n \"num_atoms\",\n \"atom_types\",\n \"enthalpy\",\n \"enthalpy_per_atom\",\n \"total_energy\",\n \"total_energy_per_atom\",\n \"pressure\",\n \"max_force_on_atom\",\n \"optimised\",\n \"date\",\n \"total_time_hrs\",\n \"peak_mem_MB\",\n ]\n\n for key in keys:\n if key in doc:\n stripped_doc[key] = doc[key]\n if isinstance(doc[key], np.ndarray):\n stripped_doc[key] = doc[key].tolist()\n return stripped_doc\n\n\nclass FakeComputeTask(ComputeTask):\n \"\"\" Fake Relaxer for testing, with same parameters as the real one\n from matador.compute.\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n self.structure = kwargs[\"res\"]\n self.output_queue = kwargs[\"output_queue\"]\n\n def relax(self):\n fake_number_crunch = True\n if fake_number_crunch:\n size = np.random.randint(low=3, high=50)\n array = np.random.rand(size, size)\n np.linalg.eig(array)\n self.structure[\"enthalpy_per_atom\"] = -505 + np.random.rand()\n self.structure[\"enthalpy\"] = self.structure[\"enthalpy_per_atom\"] * self.structure[\"num_atoms\"]\n if np.random.rand() < 0.8:\n self.structure[\"optimised\"] = True\n else:\n self.structure[\"optimised\"] = False\n self.output_queue.put(self.structure)\n\n\nclass NewbornProcess:\n \"\"\" Simple container of process data. \"\"\"\n\n def __init__(self, newborn_id, node, process, ncores=None):\n self.newborn_id = newborn_id\n self.node = node\n self.process = process\n self.ncores = ncores\n\n\nclass AseRelaxation:\n \"\"\" Perform a variable cell relaxation with ASE,\n using a predefined calculator.\n\n \"\"\"\n def __init__(self, doc, queue, calculator=None):\n \"\"\" Initialise a relaxation with ASE.\n\n Parameters:\n doc (dict): the structure to optimise.\n queue (mp.Queue): the queue to push the result to.\n\n Keyword arguments:\n calculator (ase.Calculator): the calculator object\n to use for force/energy computation. Default is\n LennardJones.\n\n \"\"\"\n from copy import deepcopy\n from matador.utils.viz_utils import doc2ase\n from ase.constraints import UnitCellFilter\n\n if calculator is None:\n from ase.calculators.lj import LennardJones\n self.calc = LennardJones()\n else:\n self.calc = calculator\n\n self.doc = deepcopy(doc)\n self.atoms = doc2ase(doc)\n self.atoms.set_calculator(self.calc)\n self.ucf = UnitCellFilter(self.atoms)\n self.queue = queue\n\n def relax(self):\n from ase.optimize import LBFGS\n\n cached = sys.__stdout__\n try:\n optimizer = LBFGS(self.ucf)\n optimizer.logfile = None\n optimised = optimizer.run(fmax=0.05, steps=100)\n except Exception:\n optimised = False\n\n self.doc[\"optimised\"] = bool(optimised)\n self.doc[\"positions_abs\"] = self.atoms.get_positions().tolist()\n self.doc[\"lattice_cart\"] = self.atoms.get_cell().tolist()\n self.doc[\"lattice_abc\"] = cart2abc(self.doc[\"lattice_cart\"])\n self.doc[\"positions_frac\"] = cart2frac(self.doc[\"lattice_cart\"], self.doc[\"positions_abs\"])\n self.doc[\"enthalpy_per_atom\"] = float(self.calc.results[\"energy\"] / len(\n self.doc[\"atom_types\"]\n ))\n self.doc[\"enthalpy\"] = float(self.calc.results[\"energy\"])\n self.queue.put(self.doc)\n sys.stdout = cached\n" ]
[ [ "numpy.linalg.eig", "numpy.random.rand", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Criscraft/pytorch_classification
[ "d5772963e55ce218ae4719fb7f85604263aab65f" ]
[ "pytorchtools/ptnetworks/ResNetCIFAR.py" ]
[ "from collections import OrderedDict \nimport torch\nfrom torch import Tensor\nimport torch.nn as nn\nfrom torch.utils.model_zoo import load_url as load_state_dict_from_url\nfrom ptnetworks.ActivationTracker import ActivationTracker\nfrom typing import Type, Any, Callable, Union, List, Optional\n\n\nclass ResNetCIFAR(nn.Module):\n def __init__(self,\n variant='resnet050', \n n_classes=100, \n pretrained=False, \n freeze_features_until='', #exclusive\n no_gradient_required=False,\n enforce_batchnorm_requires_gradient=False,\n n_layers_to_be_removed_from_blocks=[],\n no_classifier=False,\n activation='relu',\n init_mode='kaiming_normal',\n statedict='',\n strict_loading=True):\n super().__init__()\n\n arg_dict = {\n 'pretrained' : pretrained,\n 'num_classes' : n_classes,\n 'init_mode' : init_mode,\n 'activation' : activation,\n }\n\n if variant == 'resnet018':\n self.embedded_model = resnet18(**arg_dict)\n elif variant == 'resnet034':\n self.embedded_model = resnet34(**arg_dict)\n elif variant == 'resnet050':\n self.embedded_model = resnet50(**arg_dict)\n elif variant == 'resnet101':\n self.embedded_model = resnet101(**arg_dict)\n elif variant == 'resnet152':\n self.embedded_model = resnet152(**arg_dict)\n elif variant == 'resnext050_32x4d':\n self.embedded_model = resnext50_32x4d(**arg_dict)\n elif variant == 'resnext101_32x8d':\n self.embedded_model = resnext101_32x8d(**arg_dict)\n elif variant == 'wide_resnet050_2':\n self.embedded_model = wide_resnet50_2(**arg_dict)\n elif variant == 'wide_resnet101_2':\n self.embedded_model = wide_resnet101_2(**arg_dict)\n else:\n print('select valid model variant')\n\n if no_classifier:\n self.embedded_model.classifier = nn.Identity()\n\n module_dict = OrderedDict([\n ('classifier', self.embedded_model.classifier),\n ('layer4', self.embedded_model.layer4),\n ('layer3', self.embedded_model.layer3),\n ('layer2', self.embedded_model.layer2),\n ('layer1', self.embedded_model.layer1),\n ])\n \n if freeze_features_until:\n for param in self.embedded_model.parameters():\n param.requires_grad = False\n \n if freeze_features_until not in module_dict:\n raise ValueError(\"freeue_features_until does not match any network module\")\n \n for key, module in module_dict.items():\n for param in module.parameters():\n param.requires_grad = True\n if freeze_features_until == key:\n break\n\n if n_layers_to_be_removed_from_blocks:\n modules = [\n self.embedded_model.layer1,\n self.embedded_model.layer2,\n self.embedded_model.layer3,\n self.embedded_model.layer4,\n ]\n for n_layers, layer in zip(n_layers_to_be_removed_from_blocks, modules):\n for i in range(n_layers):\n layer[-i-1] = nn.Identity()\n\n if statedict:\n pretrained_dict = torch.load(statedict, map_location=torch.device('cpu'))\n missing = self.load_state_dict(pretrained_dict, strict=strict_loading)\n print('Loading weights from statedict. Missing and unexpected keys:')\n print(missing)\n\n if enforce_batchnorm_requires_gradient:\n for m in self.embedded_model.modules():\n if isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.BatchNorm1d):\n for param in m.parameters():\n param.requires_grad = True\n\n if no_gradient_required:\n for param in self.embedded_model.parameters():\n param.requires_grad = False\n \n def forward(self, batch):\n if isinstance(batch, dict) and 'data' in batch:\n logits = self.embedded_model(batch['data'])\n out = {'logits' : logits}\n return out\n else:\n return self.embedded_model(batch)\n\n def forward_features(self, batch, module=None):\n track_modules = ActivationTracker()\n\n assert isinstance(batch, dict) and 'data' in batch\n logits, activation_dict = track_modules.collect_stats(self.embedded_model, batch['data'], module)\n out = {'logits' : logits, 'activations' : activation_dict}\n return out\n \n def save(self, statedict_name):\n torch.save(self.state_dict(), statedict_name)\n\n \nMODEL_DIR = '/nfshome/linse/NO_INB_BACKUP/ModelZoo'\n\n\nmodel_urls = {\n 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',\n 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',\n 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',\n 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',\n 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',\n 'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',\n 'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',\n 'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',\n 'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',\n}\n\n\ndef conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv2d:\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=dilation, groups=groups, bias=False, dilation=dilation)\n\n\ndef conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:\n \"\"\"1x1 convolution\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion: int = 1\n\n def __init__(\n self,\n inplanes: int,\n planes: int,\n stride: int = 1,\n downsample: Optional[nn.Module] = None,\n groups: int = 1,\n base_width: int = 64,\n dilation: int = 1,\n norm_layer: Optional[Callable[..., nn.Module]] = None,\n activation_layer=nn.ReLU\n ) -> None:\n super(BasicBlock, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n if groups != 1 or base_width != 64:\n raise ValueError('BasicBlock only supports groups=1 and base_width=64')\n if dilation > 1:\n raise NotImplementedError(\"Dilation > 1 not supported in BasicBlock\")\n # Both self.conv1 and self.downsample layers downsample the input when stride != 1\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = norm_layer(planes)\n self.relu_1 = activation_layer(inplace=False)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = norm_layer(planes)\n self.downsample = downsample\n self.relu_2 = activation_layer(inplace=False)\n self.stride = stride\n\n def forward(self, x: Tensor) -> Tensor:\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu_1(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu_2(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)\n # while original implementation places the stride at the first 1x1 convolution(self.conv1)\n # according to \"Deep residual learning for image recognition\"https://arxiv.org/abs/1512.03385.\n # This variant is also known as ResNet V1.5 and improves accuracy according to\n # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch.\n\n expansion: int = 4\n\n def __init__(\n self,\n inplanes: int,\n planes: int,\n stride: int = 1,\n downsample: Optional[nn.Module] = None,\n groups: int = 1,\n base_width: int = 64,\n dilation: int = 1,\n norm_layer: Optional[Callable[..., nn.Module]] = None,\n activation_layer=nn.ReLU\n ) -> None:\n super(Bottleneck, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n width = int(planes * (base_width / 64.)) * groups\n # Both self.conv2 and self.downsample layers downsample the input when stride != 1\n self.conv1 = conv1x1(inplanes, width)\n self.bn1 = norm_layer(width)\n self.conv2 = conv3x3(width, width, stride, groups, dilation)\n self.bn2 = norm_layer(width)\n self.conv3 = conv1x1(width, planes * self.expansion)\n self.bn3 = norm_layer(planes * self.expansion)\n self.relu_1 = activation_layer(inplace=False)\n self.relu_2 = activation_layer(inplace=False)\n self.relu_3 = activation_layer(inplace=False)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x: Tensor) -> Tensor:\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu_1(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu_2(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu_3(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n\n def __init__(\n self,\n block: Type[Union[BasicBlock, Bottleneck]],\n layers: List[int],\n num_classes: int = 1000,\n zero_init_residual: bool = False,\n groups: int = 1,\n width_per_group: int = 64,\n replace_stride_with_dilation: Optional[List[bool]] = None,\n norm_layer: Optional[Callable[..., nn.Module]] = None,\n init_mode='kaiming_normal',\n activation='relu',\n ) -> None:\n super().__init__()\n\n self.ID = 'ResNet'\n\n if activation == 'relu':\n activation_layer = nn.ReLU\n elif activation == 'leaky_relu':\n activation_layer = nn.LeakyReLU\n self._activation_layer = activation_layer\n\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n self._norm_layer = norm_layer\n\n self.inplanes = 64\n self.dilation = 1\n if replace_stride_with_dilation is None:\n # each element in the tuple indicates if we should replace\n # the 2x2 stride with a dilated convolution instead\n replace_stride_with_dilation = [False, False, False]\n if len(replace_stride_with_dilation) != 3:\n raise ValueError(\"replace_stride_with_dilation should be None \"\n \"or a 3-element tuple, got {}\".format(replace_stride_with_dilation))\n self.groups = groups\n self.base_width = width_per_group\n #for CIFAR we choose a kernel size of 3 in the first convolutional layer\n self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=3, stride=2, padding=3,\n bias=False)\n self.conv1.ID = self.ID + '_first_layer'\n self.bn1 = norm_layer(self.inplanes)\n self.relu = self._activation_layer(inplace=False)\n #we do not apply maxpooling after the first layer for CIFAR\n self.maxpool = nn.Identity() #nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2,\n dilate=replace_stride_with_dilation[0])\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2,\n dilate=replace_stride_with_dilation[1])\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2,\n dilate=replace_stride_with_dilation[2])\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\n self.classifier = nn.Linear(512 * block.expansion, num_classes)\n\n self.reinitialize(init_mode, activation, zero_init_residual)\n\n\n def reinitialize(self, init_mode, activation, zero_init_residual):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n if init_mode == 'kaiming_normal':\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity=activation)\n elif init_mode == 'kaiming_uniform':\n nn.init.kaiming_uniform_(m.weight, mode='fan_out', nonlinearity=activation)\n elif init_mode == 'sparse':\n nn.init.sparse_(m.weight, sparsity=0.1, std=0.01)\n elif init_mode == 'orthogonal':\n nn.init.orthogonal_(m.weight, gain=1)\n elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n # Zero-initialize the last BN in each residual branch,\n # so that the residual branch starts with zeros, and each residual block behaves like an identity.\n # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677\n if zero_init_residual:\n for m in self.modules():\n if isinstance(m, Bottleneck):\n nn.init.constant_(m.bn3.weight, 0) # type: ignore[arg-type]\n elif isinstance(m, BasicBlock):\n nn.init.constant_(m.bn2.weight, 0) # type: ignore[arg-type]\n\n\n def _make_layer(self, block: Type[Union[BasicBlock, Bottleneck]], planes: int, blocks: int,\n stride: int = 1, dilate: bool = False) -> nn.Sequential:\n norm_layer = self._norm_layer\n downsample = None\n activation_layer = self._activation_layer\n previous_dilation = self.dilation\n\n if dilate:\n self.dilation *= stride\n stride = 1\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n conv1x1(self.inplanes, planes * block.expansion, stride),\n norm_layer(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample, self.groups,\n self.base_width, previous_dilation, norm_layer, activation_layer))\n self.inplanes = planes * block.expansion\n for _ in range(1, blocks):\n layers.append(block(self.inplanes, planes, groups=self.groups,\n base_width=self.base_width, dilation=self.dilation,\n norm_layer=norm_layer, activation_layer=activation_layer))\n\n return nn.Sequential(*layers)\n\n def _forward_impl(self, x: Tensor) -> Tensor:\n # See note [TorchScript super()]\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n x = self.avgpool(x)\n x = torch.flatten(x, 1)\n x = self.classifier(x)\n\n return x\n\n def forward(self, x: Tensor) -> Tensor:\n return self._forward_impl(x)\n\n\ndef _resnet(\n arch: str,\n block: Type[Union[BasicBlock, Bottleneck]],\n layers: List[int],\n pretrained: bool,\n progress: bool,\n **kwargs: Any\n) -> ResNet:\n model = ResNet(block, layers, **kwargs)\n if pretrained:\n state_dict = load_state_dict_from_url(model_urls[arch], progress=progress, model_dir=MODEL_DIR)\n model.load_state_dict(state_dict, strict=False)\n return model\n\n\ndef resnet18(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:\n r\"\"\"ResNet-18 model from\n `\"Deep Residual Learning for Image Recognition\" <https://arxiv.org/pdf/1512.03385.pdf>`_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress,\n **kwargs)\n\n\n\ndef resnet34(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:\n r\"\"\"ResNet-34 model from\n `\"Deep Residual Learning for Image Recognition\" <https://arxiv.org/pdf/1512.03385.pdf>`_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress,\n **kwargs)\n\n\n\ndef resnet50(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:\n r\"\"\"ResNet-50 model from\n `\"Deep Residual Learning for Image Recognition\" <https://arxiv.org/pdf/1512.03385.pdf>`_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress,\n **kwargs)\n\n\n\ndef resnet101(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:\n r\"\"\"ResNet-101 model from\n `\"Deep Residual Learning for Image Recognition\" <https://arxiv.org/pdf/1512.03385.pdf>`_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress,\n **kwargs)\n\n\n\ndef resnet152(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:\n r\"\"\"ResNet-152 model from\n `\"Deep Residual Learning for Image Recognition\" <https://arxiv.org/pdf/1512.03385.pdf>`_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress,\n **kwargs)\n\n\n\ndef resnext50_32x4d(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:\n r\"\"\"ResNeXt-50 32x4d model from\n `\"Aggregated Residual Transformation for Deep Neural Networks\" <https://arxiv.org/pdf/1611.05431.pdf>`_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n kwargs['groups'] = 32\n kwargs['width_per_group'] = 4\n return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3],\n pretrained, progress, **kwargs)\n\n\n\ndef resnext101_32x8d(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:\n r\"\"\"ResNeXt-101 32x8d model from\n `\"Aggregated Residual Transformation for Deep Neural Networks\" <https://arxiv.org/pdf/1611.05431.pdf>`_.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n kwargs['groups'] = 32\n kwargs['width_per_group'] = 8\n return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3],\n pretrained, progress, **kwargs)\n\n\n\ndef wide_resnet50_2(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:\n r\"\"\"Wide ResNet-50-2 model from\n `\"Wide Residual Networks\" <https://arxiv.org/pdf/1605.07146.pdf>`_.\n\n The model is the same as ResNet except for the bottleneck number of channels\n which is twice larger in every block. The number of channels in outer 1x1\n convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048\n channels, and in Wide ResNet-50-2 has 2048-1024-2048.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n kwargs['width_per_group'] = 64 * 2\n return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3],\n pretrained, progress, **kwargs)\n\n\n\ndef wide_resnet101_2(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet:\n r\"\"\"Wide ResNet-101-2 model from\n `\"Wide Residual Networks\" <https://arxiv.org/pdf/1605.07146.pdf>`_.\n\n The model is the same as ResNet except for the bottleneck number of channels\n which is twice larger in every block. The number of channels in outer 1x1\n convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048\n channels, and in Wide ResNet-50-2 has 2048-1024-2048.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n \"\"\"\n kwargs['width_per_group'] = 64 * 2\n return _resnet('wide_resnet101_2', Bottleneck, [3, 4, 23, 3],\n pretrained, progress, **kwargs)" ]
[ [ "torch.nn.Sequential", "torch.nn.init.constant_", "torch.nn.Conv2d", "torch.nn.init.kaiming_uniform_", "torch.nn.Linear", "torch.nn.Identity", "torch.nn.AdaptiveAvgPool2d", "torch.nn.init.sparse_", "torch.nn.init.orthogonal_", "torch.flatten", "torch.device", "torch.utils.model_zoo.load_url", "torch.nn.init.kaiming_normal_" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
pierg/wiseml-patterns
[ "2decf2954001296bd04261b00ae144f53359a2b8", "2decf2954001296bd04261b00ae144f53359a2b8", "2decf2954001296bd04261b00ae144f53359a2b8" ]
[ "gym_minigrid/extendedminigrid.py", "pytorch_dqn/visualize.py", "pytorch_a2c/enjoy.py" ]
[ "from gym_minigrid.minigrid import *\nfrom configurations import config_grabber as cg\n\nimport math\nimport operator\nfrom functools import reduce\n\nimport traceback\n\nimport numpy as np\n\nconfig = cg.Configuration.grab()\n\nAGENT_VIEW_SIZE = config.agent_view_size\nEXTRA_OBSERVATIONS_SIZE = 5\nOBS_ARRAY_SIZE = (AGENT_VIEW_SIZE, AGENT_VIEW_SIZE)\n\ndef extended_dic(obj_names=[]):\n \"\"\"\n Extend the OBJECT_TO_IDX dictionaries with additional objects\n :param obj_names: list of strings\n :return: OBJECT_TO_IDX extended\n \"\"\"\n biggest_idx = list(OBJECT_TO_IDX.values())[-1]\n for key in OBJECT_TO_IDX.values():\n if key > biggest_idx:\n biggest_idx = key\n new_obj_idx = biggest_idx + 1\n for obj_name in obj_names:\n if not obj_name in OBJECT_TO_IDX.keys():\n OBJECT_TO_IDX.update({obj_name: new_obj_idx})\n new_obj_idx = new_obj_idx + 1\n\n\nextended_dic([\"water\", \"lightsw\", \"dirt\", \"vase\"])\nIDX_TO_OBJECT = dict(zip(OBJECT_TO_IDX.values(), OBJECT_TO_IDX.keys()))\n\n\nclass Room:\n\n def __init__(self, room, size, position, lightOn):\n self.number = room\n self.size = size\n self.position = position\n self.lightOn = lightOn\n\n def setLight(self, lightOn):\n self.lightOn = lightOn\n\n def setEntryDoor(self, position):\n self.entryDoor = position\n\n def setExitDoor(self, position):\n self.exitDoor = position\n\n def getLight(self):\n return self.lightOn\n\n def objectInRoom(self, position):\n ax, ay = position\n x, y = self.size\n k, l = self.position\n x += k\n y += l\n if ax <= x and ax >= k:\n if ay <= y and ay >= l:\n return True\n return False\n\n\nclass Water(WorldObj):\n def __init__(self):\n super(Water, self).__init__('water', 'blue')\n\n def can_overlap(self):\n return True\n\n def render(self, r):\n self._set_color(r)\n r.drawPolygon([\n (0, CELL_PIXELS),\n (CELL_PIXELS, CELL_PIXELS),\n (CELL_PIXELS, 0),\n (0, 0)\n ])\n\n\nclass LightSwitch(WorldObj):\n def __init__(self):\n self.is_on = False\n super(LightSwitch, self).__init__('lightsw', 'yellow')\n\n def affectRoom(self, room):\n self.room = room\n\n def setSwitchPos(self, position):\n self.position = position\n\n def elements_in_room(self, room):\n self.elements = room\n\n def toggle(self, env, pos):\n self.room.setLight(not self.room.getLight())\n self.is_on = not self.is_on\n return True\n\n def getRoomNumber(self):\n return self.room.number\n\n def can_overlap(self):\n return False\n\n def render(self, r):\n self._set_color(r)\n r.drawPolygon([\n (0, CELL_PIXELS),\n (CELL_PIXELS, CELL_PIXELS),\n (CELL_PIXELS, 0),\n (0, 0)\n ])\n self.dark_light(r)\n\n def dark_light(self, r):\n\n if self.room.getLight() == False:\n r.setColor(255, 0, 0)\n r.drawCircle(0.5 * CELL_PIXELS, 0.5 * CELL_PIXELS, 0.2 * CELL_PIXELS)\n if hasattr(self, 'cur_pos'):\n if hasattr(self, 'elements'):\n (xl, yl) = self.cur_pos\n for i in range(0, len(self.elements)):\n if self.elements[i][2] == 1:\n r.setLineColor(10, 10, 10)\n r.setColor(10, 10, 10)\n r.drawPolygon([\n (\n (self.elements[i][0] - xl) * CELL_PIXELS,\n (self.elements[i][1] - yl + 1) * CELL_PIXELS),\n ((self.elements[i][0] - xl + 1) * CELL_PIXELS,\n (self.elements[i][1] - yl + 1) * CELL_PIXELS),\n (\n (self.elements[i][0] - xl + 1) * CELL_PIXELS,\n (self.elements[i][1] - yl) * CELL_PIXELS),\n ((self.elements[i][0] - xl) * CELL_PIXELS, (self.elements[i][1] - yl) * CELL_PIXELS)\n ])\n else:\n r.setColor(0, 255, 0)\n r.drawCircle(0.5 * CELL_PIXELS, 0.5 * CELL_PIXELS, 0.2 * CELL_PIXELS)\n r.pop\n\n\nclass Dirt(WorldObj):\n def __init__(self):\n super(Dirt, self).__init__('dirt', 'yellow')\n\n def can_overlap(self):\n return True\n\n def affect_list(self, list):\n self.list = list\n\n def toggle(self, env, pos):\n x, y = ExMiniGridEnv.get_grid_coords_from_view(env, (1, 0))\n env.grid.set(x, y, None)\n del self.list[len(self.list) - 1]\n return True\n\n def render(self, r):\n self._set_color(r)\n r.setColor(240, 150, 0)\n r.setLineColor(81, 41, 0)\n r.drawPolygon([\n (0, CELL_PIXELS),\n (CELL_PIXELS, CELL_PIXELS),\n (CELL_PIXELS, 0),\n (0, 0)\n ])\n\n\nclass Vase(WorldObj):\n def __init__(self):\n super(Vase, self).__init__('vase', 'grey')\n self.content = Dirt()\n self.list = []\n\n def can_overlap(self):\n return False\n\n def toggle(self, env, pos):\n x, y = ExMiniGridEnv.get_grid_coords_from_view(env, (1, 0))\n env.grid.set(x, y, self.content)\n self.list.append(Dirt())\n self.content.affect_list(self.list)\n\n def render(self, r):\n self._set_color(r)\n r.setColor(255, 255, 255)\n QUARTER_CELL = 0.25 * CELL_PIXELS\n DEMI_CELL = 0.5 * CELL_PIXELS\n r.drawCircle(DEMI_CELL, DEMI_CELL, DEMI_CELL)\n r.drawPolygon([\n (QUARTER_CELL, 3 * QUARTER_CELL),\n (3 * QUARTER_CELL, 3 * QUARTER_CELL),\n (3 * QUARTER_CELL, QUARTER_CELL),\n (QUARTER_CELL, QUARTER_CELL)\n ])\n r.setColor(240, 150, 0)\n r.drawPolygon([\n (0.32 * CELL_PIXELS, 0.7 * CELL_PIXELS),\n (0.7 * CELL_PIXELS, 0.7 * CELL_PIXELS),\n (0.7 * CELL_PIXELS, 0.32 * CELL_PIXELS),\n (0.32 * CELL_PIXELS, 0.32 * CELL_PIXELS)\n ])\n\n def list_dirt(self, list):\n self.list = list\n\n\ndef worldobj_name_to_object(worldobj_name):\n if worldobj_name == 'water':\n return Water()\n elif worldobj_name == 'wall':\n return Wall()\n elif worldobj_name == \"lightsw\":\n return LightSwitch()\n elif worldobj_name == \"dirt\":\n return Dirt()\n elif worldobj_name == \"vase\":\n return Vase()\n elif worldobj_name == \"goal\":\n return Goal()\n else:\n return None\n\n\nclass ExGrid(Grid):\n \"\"\"\n Extending Grid methods to support the new objects\n \"\"\"\n\n # Add new worldobje that need to be decoded (Ex. water)\n def decode(array):\n \"\"\"\n Decode an array grid encoding back into a grid\n \"\"\"\n flatten_dim = array.shape[0]\n width = int(math.sqrt(flatten_dim))\n height = width\n # width = array.shape[0]\n # height = array.shape[1]\n grid = ExGrid(width, height)\n\n for j in range(0, height):\n for i in range(0, width):\n\n typeIdx = array[i, j, 0]\n colorIdx = array[i, j, 1]\n openIdx = array[i, j, 2]\n\n if typeIdx == 0:\n continue\n\n objType = IDX_TO_OBJECT[typeIdx]\n color = IDX_TO_COLOR[colorIdx]\n is_open = True if openIdx == 1 else 0\n\n if objType == 'wall':\n v = Wall(color)\n elif objType == 'ball':\n v = Ball(color)\n elif objType == 'key':\n v = Key(color)\n elif objType == 'box':\n v = Box(color)\n elif objType == 'door':\n v = Door(color, is_open)\n elif objType == 'locked_door':\n v = LockedDoor(color, is_open)\n elif objType == 'goal':\n v = Goal()\n elif objType == 'water':\n v = Water()\n elif objType == 'lightsw':\n v = LightSwitch()\n elif objType == 'dirt':\n v = Dirt()\n elif objType == 'vase':\n v = Vase()\n else:\n assert False, \"unknown obj type in decode '%s'\" % objType\n grid.set(i, j, v)\n return grid\n\n\nclass ExMiniGridEnv(MiniGridEnv):\n\n\n # Enumeration of possible actions\n class Actions(IntEnum):\n\n # Used to observe the environment in the step() before the action\n observe = -1\n\n # Action space\n left = 0\n right = 1\n forward = 2\n toggle = 3\n\n # Extra action (not used)\n pickup = 4\n drop = 5\n done = 6\n clean = 7\n\n\n def print_grid(self, grid):\n\n for i, e in enumerate(grid.grid):\n if i % grid.height == 0:\n print(\"\")\n if e is not None:\n print(str(e.type), end=\"\\t\")\n else:\n print(\"none\", end=\"\\t\")\n print(\"\")\n\n def strings_to_actions(self, actions):\n for i, action_name in enumerate(actions):\n if action_name == \"left\":\n actions[i] = self.actions.left\n elif action_name == \"right\":\n actions[i] = self.actions.right\n elif action_name == \"forward\":\n actions[i] = self.actions.forward\n elif action_name == \"toggle\":\n actions[i] = self.actions.toggle\n elif action_name == \"done\":\n actions[i] = self.actions.done\n elif action_name == \"clean\":\n actions[i] = self.actions.clean\n elif action_name == \"observe\":\n actions[i] = self.actions.observe\n\n return actions\n\n def action_to_string(self, action):\n if action == self.actions.left:\n return \"left\"\n elif action == self.actions.right:\n return \"right\"\n elif action == self.actions.forward:\n return \"forward\"\n elif action == self.actions.toggle:\n return \"toggle\"\n elif action == self.actions.done:\n return \"done\"\n elif action == self.actions.clean:\n return \"clean\"\n elif action == self.actions.observe:\n return \"observe\"\n return None\n\n\n def __init__(self, grid_size=16, max_steps=-1, see_through_walls=False, seed=1337):\n # Grab configuration\n self.config = cg.Configuration.grab()\n # Overriding the max_num_steps\n max_num_steps = max_steps\n if hasattr(self.config, 'max_num_steps'):\n max_num_steps = self.config.max_num_steps\n super().__init__(grid_size, max_num_steps, see_through_walls, seed)\n self.actions = ExMiniGridEnv.Actions\n\n \"\"\"\n Observation Space\n low: lowest element value\n high: highest element value\n shape: imgSize tuple, each element can be of a value between 'low' and 'high'\n \"\"\"\n imgSize = reduce(operator.mul, OBS_ARRAY_SIZE, 1) + EXTRA_OBSERVATIONS_SIZE\n elemSize = len(IDX_TO_OBJECT)\n self.observation_space = spaces.Box(\n low=0,\n high=elemSize,\n shape=(imgSize,),\n dtype='uint8'\n )\n\n # Restricting action_space to the first N actions\n first_n_actions_available = 4\n self.action_space = spaces.Discrete(first_n_actions_available)\n\n\n\n\n def step(self, action):\n\n self.step_count += 1\n\n reward = 0\n done = False\n\n info = {\"event\": [], \"steps_count\": self.step_count}\n\n # Get the position in front of the agent\n fwd_pos = self.front_pos\n\n # Get the contents of the cell in front of the agent\n fwd_cell = self.grid.get(*fwd_pos)\n\n\n # Rotate left\n if action == self.actions.left:\n self.agent_dir -= 1\n if self.agent_dir < 0:\n self.agent_dir += 4\n\n # Rotate right\n elif action == self.actions.right:\n self.agent_dir = (self.agent_dir + 1) % 4\n\n # Move forward\n elif action == self.actions.forward:\n if fwd_cell == None or fwd_cell.can_overlap():\n self.agent_pos = fwd_pos\n # Step into Water\n if fwd_cell is not None and fwd_cell.type == 'water':\n done = True\n reward = self.config.rewards.standard.death\n info[\"event\"].append(\"died\")\n if self.config.envelope:\n print(\"DIED!! >>>>>>> Problems with envelope!\")\n # Step into Goal\n elif fwd_cell is not None and fwd_cell.type == 'goal':\n try:\n if self.goal_enabled():\n done = True\n reward = self.config.rewards.standard.goal\n # reward = self.config.rewards.standard.goal - 0.9 * (self.step_count / self.max_steps)\n info[\"event\"].append(\"goal\")\n except:\n done = True\n reward = self.config.rewards.standard.goal\n # reward = self.config.rewards.standard.goal - 0.9 * (self.step_count / self.max_steps)\n info[\"event\"].append(\"goal\")\n\n else:\n reward = self.config.rewards.actions.forward\n\n # Pick up an object\n elif action == self.actions.pickup:\n if fwd_cell and fwd_cell.can_pickup():\n if self.carrying is None:\n self.carrying = fwd_cell\n self.carrying.cur_pos = np.array([-1, -1])\n self.grid.set(*fwd_pos, None)\n\n # Drop an object\n elif action == self.actions.drop:\n if not fwd_cell and self.carrying:\n self.grid.set(*fwd_pos, self.carrying)\n self.carrying.cur_pos = fwd_pos\n self.carrying = None\n\n # Toggle/activate an object\n elif action == self.actions.toggle:\n if fwd_cell is not None and fwd_cell.type == 'dirt':\n reward = self.config.rewards.cleaningenv.clean\n if fwd_cell:\n fwd_cell.toggle(self, fwd_pos)\n\n # Done action (not used by default)\n elif action == self.actions.done:\n pass\n\n else:\n assert False, \"unknown action\"\n\n # Adding reward for the step\n reward += self.config.rewards.standard.step\n\n if self.step_count == self.config.max_num_steps_episode:\n done = True\n\n obs = self.gen_obs()\n\n if self.config.debug_mode: print(\"reward: \" + str(reward) + \"\\tinfo: \" + str(info))\n\n return obs, reward, done, info\n\n\n def goal_enabled(self):\n raise NotImplementedError()\n\n\n def gen_obs_decoded(self):\n \"\"\"\n Generate the agent's view (partially observable, low-resolution encoding)\n \"\"\"\n grid, vis_mask = self.gen_obs_grid()\n\n if self.config.debug_mode:\n print(\"\\nAgent View Original\")\n self.print_grid(grid)\n\n \"\"\"if Perception.light_on_current_room(self):\"\"\"\n try:\n agent_pos = (AGENT_VIEW_SIZE // 2, AGENT_VIEW_SIZE - 1)\n\n obs_door_open = 0\n obs_light_on = 0\n current_room = 0\n current_room_light = 0\n next_room_light = 0\n\n if self.roomList:\n for x in self.roomList:\n # Save room number\n if x.objectInRoom(self.agent_pos):\n current_room = x.number\n current_room_light = x.getLight()\n else:\n next_room_light = x.getLight()\n\n # check if room is on the dark\n if not x.getLight():\n for j in range(0, grid.height):\n for i in range(0, grid.width):\n # pass the obs coordinates (i, j) into the absolute grid coordinates (xpos, ypos).\n xpos = agent_pos[1] - j\n ypos = i - agent_pos[0]\n (xpos, ypos) = self.get_grid_coords_from_view((xpos, ypos))\n\n # check if the object position is on the room\n if x.objectInRoom((xpos, ypos)):\n if grid.grid[(j * AGENT_VIEW_SIZE) + i] is not None:\n grid.grid[i + (j * AGENT_VIEW_SIZE)] = None\n\n for j in range(0, grid.height):\n for i in range(0, grid.width):\n\n v = grid.get(i, j)\n\n if hasattr(v, 'is_open') and v.is_open:\n obs_door_open = 1\n\n if hasattr(v, 'is_on') and v.is_on:\n obs_light_on = 1\n\n\n if self.config.debug_mode:\n print(\"\\n\\nobs_door_open\\t\\t\" + str(obs_door_open))\n print(\"obs_light_on\\t\\t\" + str(obs_light_on))\n print(\"current_room\\t\\t\" + str(current_room))\n print(\"current_room_light\\t\" + str(current_room_light*1))\n print(\"next_room_light\\t\\t\" + str(next_room_light*1) + \"\\n\\n\")\n\n\n return grid, (obs_door_open, obs_light_on, current_room, current_room_light*1, next_room_light*1)\n\n except AttributeError:\n traceback.print_exc()\n print(\"ERROR!!!\")\n\n\n\n def gen_obs(self):\n \"\"\"\n Generate the agent's view (partially observable, low-resolution encoding)\n \"\"\"\n grid, extra_observations = self.gen_obs_decoded()\n\n if self.config.debug_mode:\n print(\"\\nAgent View Retreived\")\n self.print_grid(grid)\n\n \"\"\"if Perception.light_on_current_room(self):\"\"\"\n try:\n\n array = np.zeros(shape=(grid.width, grid.height, 1), dtype='uint8')\n\n obs_door_open = 0\n obs_light_on = 0\n\n for j in range(0, grid.height):\n for i in range(0, grid.width):\n\n v = grid.get(i, j)\n\n if v == None:\n continue\n\n array[i, j, 0] = OBJECT_TO_IDX[v.type]\n\n if hasattr(v, 'is_open') and v.is_open:\n obs_door_open = 1\n\n if hasattr(v, 'is_on') and v.is_on:\n obs_light_on = 1\n\n image = array\n\n flatten_image = image.flatten()\n\n obs = np.append(flatten_image, extra_observations)\n\n return obs\n\n except AttributeError:\n traceback.print_exc()\n print(\"ERROR!!!\")\n # return super().gen_obs()\n\n\n def get_grid_coords_from_view(self, coordinates):\n \"\"\"\n Dual of \"get_view_coords\". Translate and rotate relative to the agent coordinates (i, j) into the\n absolute grid coordinates.\n Need to have tuples of integers for the position of the agent and its direction\n :param coordinates: tuples of integers (vertical,horizontal) position from the agent relative to its position\n :return : coordinates translated into the absolute grid coordinates.\n \"\"\"\n ax, ay = self.agent_pos\n ad = self.agent_dir\n x, y = coordinates\n # agent facing down\n if ad == 1:\n ax -= y\n ay += x\n # agent facing right\n elif ad == 0:\n ax += x\n ay += y\n # agent facing left\n elif ad == 2:\n ax -= x\n ay -= y\n # agent facing up\n elif ad == 3:\n ax += y\n ay -= x\n return ax, ay\n\n def worldobj_in_agent(self, front, side):\n \"\"\"\n Returns the type of the worldobject in the 'front' cells in front and 'side' cells right (positive) or left (negative)\n with respect to the agent\n :param front: integer representing the number of cells in front of the agent\n :param side: integer, if positive represents the cells to the right, negative to the left of the agent\n :return: string: worldobj type\n \"\"\"\n\n coordinates = (front, side)\n wx, wy = ExMiniGridEnv.get_grid_coords_from_view(self, coordinates)\n\n if 0 <= wx < self.grid.width and 0 <= wy < self.grid.height:\n worldobj = self.grid.get(wx, wy)\n\n if worldobj is not None:\n worldobj_type = worldobj.type\n return worldobj_type\n return None\n", "import numpy as np\n\nvis = None\ncum_rwd_f = None\ngoal_f = None\navg_rwd_f = None\nlast_epsilon_f = None\nsteps_goal = None\nexpected_q_value = None\n\ncum_rwd_e = None\n\n\ndef visdom_plot(what, x, x_label, y, y_label, where='main'):\n from visdom import Visdom\n\n global vis\n global cum_rwd_f\n global goal_f\n global avg_rwd_f\n global last_epsilon_f\n global steps_goal\n global expected_q_value\n\n global cum_rwd_e\n\n if vis is None:\n vis = Visdom(env=where)\n vis.close()\n else:\n vis = Visdom(env=where)\n\n assert vis.check_connection()\n\n # if vis is None:\n # vis = Visdom(env=where)\n # assert vis.check_connection()\n # # Close all existing plots\n # vis.close()\n\n if what == \"cum_rwd\":\n cum_rwd_f = vis.line(\n X=np.array(x),\n Y=np.array(y),\n opts=dict(\n xlabel=x_label,\n ylabel=y_label,\n ytickmin=0,\n width=300,\n height=250\n ),\n win=cum_rwd_f\n )\n\n if what == \"expected_q_value\":\n expected_q_value = vis.line(\n X=np.array(x),\n Y=np.array(y),\n opts=dict(\n xlabel=x_label,\n ylabel=y_label,\n ytickmin=0,\n width=300,\n height=250\n ),\n win=expected_q_value\n )\n\n if what == \"steps_goal\":\n steps_goal = vis.line(\n X=np.array(x),\n Y=np.array(y),\n opts=dict(\n xlabel=x_label,\n ylabel=y_label,\n ytickmin=0,\n width=300,\n height=250\n ),\n win=steps_goal\n )\n\n\n if what == \"cum_rwd_e\":\n cum_rwd_e = vis.line(\n X=np.array(x),\n Y=np.array(y),\n opts=dict(\n xlabel=x_label,\n ylabel=y_label,\n ytickmin=0,\n width=300,\n height=250\n ),\n win=cum_rwd_e\n )\n\n if what == \"avg_rwd\":\n avg_rwd_f = vis.line(\n X=np.array(x),\n Y=np.array(y),\n opts=dict(\n xlabel=x_label,\n ylabel=y_label,\n ytickmin=0,\n width=300,\n height=250\n ),\n win=avg_rwd_f\n )\n\n if what == \"goal\":\n goal_f = vis.line(\n X=np.array(x),\n Y=np.array(y),\n opts=dict(\n xlabel=x_label,\n ylabel=y_label,\n ytickmin=0,\n width=300,\n height=250\n ),\n win=goal_f\n )\n\n if what == \"last_epsilon\":\n last_epsilon_f = vis.line(\n X=np.array(x),\n Y=np.array(y),\n opts=dict(\n xlabel=x_label,\n ylabel=y_label,\n ytickmin=0,\n width=300,\n height=250\n ),\n win=last_epsilon_f\n )\n", "import argparse\nimport os\nimport sys\nimport types\nimport time\n\nimport numpy as np\nimport torch\nfrom torch.autograd import Variable\nfrom vec_env.dummy_vec_env import DummyVecEnv\n\nfrom configurations import config_grabber as cg\n\nfrom envs import make_env\n\n\ntry:\n from gym import wrappers, logger\nexcept Exception as e:\n print(\" =========== =========== IMPORT ERROR ===========\")\n print(e)\n pass\n\n\nparser = argparse.ArgumentParser(description='RL')\nparser.add_argument('--seed', type=int, default=1,\n help='random seed (default: 1)')\nparser.add_argument('--num-stack', type=int, default=1,\n help='number of frames to stack (default: 1)')\nparser.add_argument('--log-interval', type=int, default=10,\n help='log interval, one log per n updates (default: 10)')\nparser.add_argument('--env-name', default='MiniGrid-DirtWatLightExp-9x9-v0',\n help='environment to train on (default: PongNoFrameskip-v4)')\nparser.add_argument('--load-dir', default='./trained_models/a2c/',\n help='directory to save agent logs (default: ./trained_models/)')\nargs = parser.parse_args()\n\nconfig = cg.Configuration.grab()\n\nsave_path = \"../\" + config.evaluation_directory_name + \"/a2c/trained_model/\"\n\n\ndef record():\n env = make_env(args.env_name, args.seed, 0, True)\n env = DummyVecEnv([env])\n\n actor_critic, ob_rms = torch.load(os.path.join(save_path, args.env_name + \".pt\"))\n\n\n obs_shape = env.observation_space.shape\n obs_shape = (obs_shape[0] * args.num_stack, *obs_shape[1:])\n current_obs = torch.zeros(1, *obs_shape)\n states = torch.zeros(1, actor_critic.state_size)\n masks = torch.zeros(1, 1)\n\n def update_current_obs(obs):\n shape_dim0 = env.observation_space.shape[0]\n obs = torch.from_numpy(obs).float()\n if args.num_stack > 1:\n current_obs[:, :-shape_dim0] = current_obs[:, shape_dim0:]\n current_obs[:, -shape_dim0:] = obs\n\n obs = env.reset()\n update_current_obs(obs)\n\n notdone = True\n\n while notdone:\n value, action, _, states = actor_critic.act(\n Variable(current_obs, volatile=True),\n Variable(states, volatile=True),\n Variable(masks, volatile=True),\n deterministic=True\n )\n states = states.data\n cpu_actions = action.data.squeeze(1).cpu().numpy()\n\n # Observation, reward and next obs\n obs, reward, done, _ = env.step(cpu_actions)\n\n if done:\n notdone = False\n\n masks.fill_(0.0 if done else 1.0)\n\n if current_obs.dim() == 4:\n current_obs *= masks.unsqueeze(2).unsqueeze(2)\n else:\n current_obs *= masks\n update_current_obs(obs)\n\n\n\ndef enjoy():\n env = make_env(args.env_name, args.seed, 0, True)\n env = DummyVecEnv([env])\n\n actor_critic, ob_rms = torch.load(os.path.join(save_path, args.env_name + \".pt\"))\n\n render_func = env.envs[0].render\n\n obs_shape = env.observation_space.shape\n obs_shape = (obs_shape[0] * args.num_stack, *obs_shape[1:])\n current_obs = torch.zeros(1, *obs_shape)\n states = torch.zeros(1, actor_critic.state_size)\n masks = torch.zeros(1, 1)\n\n def update_current_obs(obs):\n shape_dim0 = env.observation_space.shape[0]\n obs = torch.from_numpy(obs).float()\n if args.num_stack > 1:\n current_obs[:, :-shape_dim0] = current_obs[:, shape_dim0:]\n current_obs[:, -shape_dim0:] = obs\n\n render_func('human')\n obs = env.reset()\n update_current_obs(obs)\n\n while True:\n value, action, _, states = actor_critic.act(\n Variable(current_obs, volatile=True),\n Variable(states, volatile=True),\n Variable(masks, volatile=True),\n deterministic=True\n )\n states = states.data\n cpu_actions = action.data.squeeze(1).cpu().numpy()\n\n # Observation, reward and next obs\n obs, reward, done, _ = env.step(cpu_actions)\n\n time.sleep(0.05)\n\n masks.fill_(0.0 if done else 1.0)\n\n if current_obs.dim() == 4:\n current_obs *= masks.unsqueeze(2).unsqueeze(2)\n else:\n current_obs *= masks\n update_current_obs(obs)\n\n renderer = render_func('human')\n\n if not renderer.window:\n sys.exit(0)\n\n\nif __name__ == \"__main__\":\n record()\n" ]
[ [ "numpy.append", "numpy.array", "numpy.zeros" ], [ "numpy.array" ], [ "torch.autograd.Variable", "torch.from_numpy", "torch.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
gohyun14/Game
[ "39e6e192590059daade40c95cc177acb0f3a581b" ]
[ "codenames/players/codemaster_glove_lookahead.py" ]
[ "import scipy.spatial.distance\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.stem.lancaster import LancasterStemmer\nfrom math import ceil\nimport numpy as np\nimport copy\nimport itertools\n\nfrom players.codemaster import Codemaster\nTHRESHOLD = np.inf\n\nclass AICodemaster(Codemaster):\n\n def __init__(self, brown_ic=None, glove_vecs=None, word_vectors=None):\n super().__init__()\n self.brown_ic = brown_ic\n self.glove_vecs = glove_vecs\n self.word_vectors = word_vectors\n self.wordnet_lemmatizer = WordNetLemmatizer()\n self.lancaster_stemmer = LancasterStemmer()\n self.cm_wordlist = []\n with open('players/cm_wordlist.txt') as infile:\n for line in infile:\n self.cm_wordlist.append(line.rstrip())\n self.root = None\n self.turn_number = 0\n\n def set_game_state(self, words, maps):\n if self.turn_number == 0:\n self.original_words = copy.copy(words)\n print(f\"original words: {self.original_words}\")\n self.words = words\n self.maps = maps\n self.update_board()\n self.init_dists()\n self.turn_number += 1\n\n def update_board(self):\n self.red_words = set()\n self.bad_words = set()\n self.words_guessed = set()\n for i in range(25):\n if self.words[i][0] == '*':\n self.words_guessed.add(self.original_words[i].lower())\n elif self.maps[i] == \"Assassin\" or self.maps[i] == \"Blue\" or self.maps[i] == \"Civilian\":\n self.bad_words.add(self.words[i].lower())\n if self.maps[i] == \"Assassin\":\n self.black_word = self.words[i]\n else:\n self.red_words.add(self.words[i].lower())\n \n def init_dists(self):\n cos_dist = scipy.spatial.distance.cosine\n all_vectors = (self.glove_vecs,)\n self.bad_word_dists = {}\n for word in self.bad_words:\n self.bad_word_dists[word] = {}\n for val in self.cm_wordlist:\n b_dist = cos_dist(self.concatenate(val, all_vectors), self.concatenate(word, all_vectors))\n self.bad_word_dists[word][val] = b_dist\n\n self.red_word_dists = {}\n for word in self.red_words:\n self.red_word_dists[word] = {}\n for val in self.cm_wordlist:\n b_dist = cos_dist(self.concatenate(val, all_vectors), self.concatenate(word, all_vectors))\n self.red_word_dists[word][val] = b_dist\n\n def get_clue(self):\n #self.all_guesses = set()\n if self.root is None or self.root.words_guessed != self.words_guessed:\n if self.root:\n print(\"board mismatch: initializing new root\")\n print(f\"game's words guessed: {self.words_guessed} nodes' words guessed: {self.root.words_guessed}\")\n self.root = Node(self, copy.copy(self.words_guessed), None, depth = self.turn_number-1)\n self.root.get_val()\n best_clue = self.root.best_clue\n print('chosen_clue is:', best_clue[0])\n\n self.root = self.root.best_child\n return best_clue\n\n def arr_not_in_word(self, word, arr):\n if word in arr:\n return False\n lemm = self.wordnet_lemmatizer.lemmatize(word)\n lancas = self.lancaster_stemmer.stem(word)\n for i in arr:\n if i == lemm or i == lancas:\n return False\n if i.find(word) != -1:\n return False\n if word.find(i) != -1:\n return False\n return True\n\n def combine(self, words, wordvecs):\n factor = 1.0 / float(len(words))\n new_word = self.concatenate(words[0], wordvecs) * factor\n for word in words[1:]:\n new_word += self.concatenate(word, wordvecs) * factor\n return new_word\n\n def concatenate(self, word, wordvecs):\n concatenated = wordvecs[0][word]\n for vec in wordvecs[1:]:\n concatenated = np.hstack((concatenated, vec[word]))\n return concatenated\n\n\nclass Node:\n def __init__(self, codemaster, words_guessed, parent, depth = 0, best=np.inf):\n self.codemaster = codemaster\n self.words_guessed = words_guessed\n self.parent = parent\n self.depth = depth\n self.best_clue = None\n self.best_child = None\n self.val = np.inf\n self.terminal = False\n self.best = best\n\n def get_best_clues(self):\n bests = {}\n possible = {}\n cm = self.codemaster\n red_words = cm.red_words.difference(self.words_guessed)\n bad_words = cm.bad_words.difference(self.words_guessed)\n print(f\"calculating best clues\")\n #print(f\"red word dists: {self.red_word_dists}\")\n for clue_num in range(1, 3 + 1):\n best_per_dist = np.inf\n best_per = ''\n best_red_word = ''\n for red_word in list(itertools.combinations(red_words, clue_num)):\n best_word = ''\n best_dist = np.inf\n for word in cm.cm_wordlist:\n if not cm.arr_not_in_word(word, red_words.union(bad_words)):\n continue\n\n bad_dist = np.inf\n worst_bad = ''\n for bad_word in bad_words:\n if cm.bad_word_dists[bad_word][word] < bad_dist:\n bad_dist = cm.bad_word_dists[bad_word][word]\n worst_bad = bad_word\n worst_red = 0\n for red in red_word:\n dist = cm.red_word_dists[red][word]\n if dist > worst_red:\n worst_red = dist\n\n if worst_red < best_dist and worst_red < bad_dist:\n best_dist = worst_red\n best_word = word\n # print(worst_red,red_word,word)\n\n if best_dist < best_per_dist:\n best_per_dist = best_dist\n best_per = best_word\n best_red_word = red_word\n if best_dist < THRESHOLD or clue_num == 1: \n possible[(best_word, clue_num)] = (red_word, best_dist)\n bests[clue_num] = (best_red_word, best_per, best_per_dist)\n print(f\"length of possibilities: {len(possible)}\")\n return possible\n\n def add_children(self):\n cos_dist = scipy.spatial.distance.cosine\n cm = self.codemaster\n all_vectors = (cm.glove_vecs,)\n print(f\"at depth {self.depth}\")\n bests = self.get_best_clues()\n for clue, clue_info in bests.items():\n combined_clue, clue_num = clue\n best_red_word, combined_score = clue_info\n worst = -np.inf\n for word in best_red_word:\n dist = cos_dist(cm.concatenate(word, all_vectors), cm.concatenate(combined_clue, all_vectors))\n if dist > worst:\n worst = dist\n if worst < 0.7 and worst != -np.inf or clue_num == 1:\n print(f\"adding clue: {clue}\")\n self.add_child(clue, best_red_word)\n \n def check_board(self):\n cm = self.codemaster\n self.black_guessed = cm.black_word in self.words_guessed\n red_words = cm.red_words.difference(self.words_guessed)\n\n red_count = len(red_words)\n if self.black_guessed:\n self.val = np.inf\n self.terminal = True\n elif red_count == 0:\n self.val = self.depth\n self.terminal = True\n print(f\"Terminal Node: depth: {self.depth}\")\n else:\n self.val = 25\n \n def new_child(self, expected_words_chosen):\n new_words_guessed = copy.copy(self.words_guessed)\n for word in expected_words_chosen:\n new_words_guessed.add(word)\n return Node(self.codemaster, new_words_guessed, self, self.depth + 1, self.best)\n \n def get_val(self, depth=np.inf):\n # if self.words_guessed in self.codemaster.all_guesses:\n # print(\"Board State already explored\")\n # return self.val\n # self.codemaster.all_guesses.add(self.words_guessed)\n self.check_board()\n if self.not_possible():\n print(\"Skipped\")\n return self.val\n if self.terminal:\n if self.val < self.best:\n self.best = self.val\n return self.val\n if self.best_clue is not None:\n return self.val\n best_val = np.inf\n possible = self.get_best_clues()\n for clue, clue_info in sorted(possible.items(), key = lambda x: (x[0][1],-x[1][1]), reverse=True):\n combined_clue, clue_num = clue\n best_red_word, combined_score = clue_info\n if self.check_clue_feasible(clue_num, combined_score):\n print(f\"Exploring child, depth: {self.depth+1}, clue: {clue}, dist: {combined_score}\")\n child = self.new_child(best_red_word)\n child_val = child.get_val(depth)\n if child_val < best_val:\n best_val = child_val\n self.best_clue = clue\n self.best_child = child\n if child.best < self.best:\n print(f\"Found new best, prev: {self.best} new: {child.best}\")\n self.best = child.best\n self.val = best_val\n return self.val\n\n # def best_child(self):\n # best_clue = self.best_clue\n # for child_key in self.children.keys():\n # if child_key == best_clue:\n # best_child = self.children[child_key]\n # best_child.reset_depth()\n # return best_child\n\n def not_possible(self):\n red_words = self.codemaster.red_words.difference(self.words_guessed)\n best_possible = self.depth + ceil(len(red_words)/3)\n print(f\"BEST POSSIBLE: {best_possible}\")\n return self.best <= best_possible or self.depth >= self.best or (not self.terminal and self.depth == self.best - 1)\n\n def check_clue_feasible(self, clue_num, combined_score):\n return clue_num == 1 or combined_score < THRESHOLD\n # cos_dist = scipy.spatial.distance.cosine\n # cm = self.codemaster\n # all_vectors = (cm.glove_vecs,)\n # worst = -np.inf\n # for word in best_red_word:\n # dist = cos_dist(cm.concatenate(word, all_vectors), cm.concatenate(combined_clue, all_vectors))\n # if dist > worst:\n # worst = dist\n # return worst < 0.7 and worst != -np.inf or clue_num == 1\n\n\n \n" ]
[ [ "numpy.hstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ATTPC/VAE-event-classification
[ "aae331d44bffffec2ca8a6cdef71208899db0052" ]
[ "src/event_representations.py" ]
[ "import numpy as np\n\ndef make_histograms(x, bins=40, interval=[1e-1, 1]):\n intervals = np.linspace(interval[0], interval[1], bins)\n flat_x = x.reshape((x.shape[0], -1))\n hist_x = np.zeros((x.shape[0], bins))\n for i in range(1, bins):\n mask = flat_x <= intervals[i]\n mask = np.logical_and(mask, flat_x > intervals[i-1])\n hist_x[:, i] = mask.sum(1)\n\n return hist_x\n\ndef make_net_count(x, **kwargs):\n flat_x = x.reshape((x.shape[0], -1))\n sum_x = flat_x.sum(1)\n return sum_x\n" ]
[ [ "numpy.logical_and", "numpy.zeros", "numpy.linspace" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
handongke/tensorflow
[ "c6bb5cd0447a0af2764c195fb14d218df8ae6471", "c6bb5cd0447a0af2764c195fb14d218df8ae6471", "c6bb5cd0447a0af2764c195fb14d218df8ae6471", "6aa83398ab03bfae822f36772757097bcb98b6ed", "c6bb5cd0447a0af2764c195fb14d218df8ae6471", "6aa83398ab03bfae822f36772757097bcb98b6ed" ]
[ "tensorflow/python/ops/nn_ops.py", "tensorflow/python/keras/layers/recurrent.py", "tensorflow/contrib/tensorrt/test/quantization_mnist_test.py", "tensorflow/python/layers/convolutional.py", "tensorflow/python/ops/control_flow_util.py", "tensorflow/python/training/slot_creator.py" ]
[ "# Copyright 2015 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\"\"\"Wrappers for primitive Neural Net (NN) Operations.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numbers\n\nimport numpy as np\n\nfrom tensorflow.python.compat import compat\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors_impl\nfrom tensorflow.python.framework import graph_util\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import random_seed\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import check_ops\nfrom tensorflow.python.ops import gen_nn_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import random_ops\n# go/tf-wildcard-import\n# pylint: disable=wildcard-import\nfrom tensorflow.python.ops.gen_nn_ops import *\n# pylint: enable=wildcard-import\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util.deprecation import deprecated_args\nfrom tensorflow.python.util.deprecation import deprecated_argument_lookup\n\nfrom tensorflow.python.util.tf_export import tf_export\n\n# Aliases for some automatically-generated names.\nlocal_response_normalization = gen_nn_ops.lrn\n\n# pylint: disable=protected-access\n\n\ndef _non_atrous_convolution(\n input, # pylint: disable=redefined-builtin\n filter, # pylint: disable=redefined-builtin\n padding,\n data_format=None, # pylint: disable=redefined-builtin\n strides=None,\n name=None):\n \"\"\"Computes sums of N-D convolutions (actually cross correlation).\n\n It is required that 1 <= N <= 3.\n\n This is used to implement the more generic `convolution` function, which\n extends the interface of this function with a `dilation_rate` parameter.\n\n Args:\n\n input: Rank N+2 tensor of type T of shape\n `[batch_size] + input_spatial_shape + [in_channels]` if `data_format`\n does not start with `\"NC\"`, or\n `[batch_size, in_channels] + input_spatial_shape` if `data_format` starts\n with `\"NC\"`.\n filter: Rank N+2 tensor of type T of shape\n `filter_spatial_shape + [in_channels, out_channels]`. Rank of either\n `input` or `filter` must be known.\n padding: Padding method to use, must be either \"VALID\" or \"SAME\".\n data_format: A string or None. Specifies whether the channel dimension of\n the `input` and output is the last dimension (default, or if `data_format`\n does not start with \"NC\"), or the second dimension (if `data_format`\n starts with \"NC\"). For N=1, the valid values are \"NWC\" (default) and\n \"NCW\". For N=2, the valid values are \"NHWC\" (default) and \"NCHW\".\n For N=3, the valid values are \"NDHWC\" (default) and \"NCDHW\".\n strides: Sequence of N positive integers, defaults to `[1] * N`.\n name: Name prefix to use.\n\n Returns:\n Rank N+2 tensor of type T of shape\n `[batch_size] + output_spatial_shape + [out_channels]`, where\n if padding == \"SAME\":\n output_spatial_shape = input_spatial_shape\n if padding == \"VALID\":\n output_spatial_shape = input_spatial_shape - filter_spatial_shape + 1.\n\n Raises:\n ValueError: if ranks are incompatible.\n\n \"\"\"\n with ops.name_scope(name, \"non_atrous_convolution\", [input, filter]) as scope:\n input = ops.convert_to_tensor(input, name=\"input\") # pylint: disable=redefined-builtin\n input_shape = input.get_shape()\n filter = ops.convert_to_tensor(filter, name=\"filter\") # pylint: disable=redefined-builtin\n filter_shape = filter.get_shape()\n op = _NonAtrousConvolution(\n input_shape,\n filter_shape=filter_shape,\n padding=padding,\n data_format=data_format,\n strides=strides,\n name=scope)\n return op(input, filter)\n\n\nclass _NonAtrousConvolution(object):\n \"\"\"Helper class for _non_atrous_convolution.\n\n Note that this class assumes that shapes of input and filter passed to\n __call__ are compatible with input_shape and filter_shape passed to the\n constructor.\n\n Arguments:\n input_shape: static input shape, i.e. input.get_shape().\n filter_shape: static filter shape, i.e. filter.get_shape().\n padding: see _non_atrous_convolution.\n data_format: see _non_atrous_convolution.\n strides: see _non_atrous_convolution.\n name: see _non_atrous_convolution.\n \"\"\"\n\n def __init__(\n self,\n input_shape,\n filter_shape, # pylint: disable=redefined-builtin\n padding,\n data_format=None,\n strides=None,\n name=None):\n filter_shape = filter_shape.with_rank(input_shape.ndims)\n self.padding = padding\n self.name = name\n input_shape = input_shape.with_rank(filter_shape.ndims)\n if input_shape.ndims is None:\n raise ValueError(\"Rank of convolution must be known\")\n if input_shape.ndims < 3 or input_shape.ndims > 5:\n raise ValueError(\n \"`input` and `filter` must have rank at least 3 and at most 5\")\n conv_dims = input_shape.ndims - 2\n if strides is None:\n strides = [1] * conv_dims\n elif len(strides) != conv_dims:\n raise ValueError(\"len(strides)=%d, but should be %d\" % (len(strides),\n conv_dims))\n if conv_dims == 1:\n # conv1d uses the 2-d data format names\n if data_format is None:\n data_format = \"NWC\"\n elif data_format not in {\"NCW\", \"NWC\", \"NCHW\", \"NHWC\"}:\n raise ValueError(\"data_format must be \\\"NWC\\\" or \\\"NCW\\\".\")\n self.strides = strides[0]\n self.data_format = data_format\n self.conv_op = self._conv1d\n elif conv_dims == 2:\n if data_format is None or data_format == \"NHWC\":\n data_format = \"NHWC\"\n strides = [1] + list(strides) + [1]\n elif data_format == \"NCHW\":\n strides = [1, 1] + list(strides)\n else:\n raise ValueError(\"data_format must be \\\"NHWC\\\" or \\\"NCHW\\\".\")\n self.strides = strides\n self.data_format = data_format\n self.conv_op = conv2d\n elif conv_dims == 3:\n if data_format is None or data_format == \"NDHWC\":\n strides = [1] + list(strides) + [1]\n elif data_format == \"NCDHW\":\n strides = [1, 1] + list(strides)\n else:\n raise ValueError(\"data_format must be \\\"NDHWC\\\" or \\\"NCDHW\\\". Have: %s\"\n % data_format)\n self.strides = strides\n self.data_format = data_format\n self.conv_op = gen_nn_ops.conv3d\n\n # Note that we need this adapter since argument names for conv1d don't match\n # those for gen_nn_ops.conv2d and gen_nn_ops.conv3d.\n # pylint: disable=redefined-builtin\n def _conv1d(self, input, filter, strides, padding, data_format, name):\n return conv1d(\n value=input,\n filters=filter,\n stride=strides,\n padding=padding,\n data_format=data_format,\n name=name)\n\n # pylint: enable=redefined-builtin\n\n def __call__(self, inp, filter): # pylint: disable=redefined-builtin\n return self.conv_op(\n input=inp,\n filter=filter,\n strides=self.strides,\n padding=self.padding,\n data_format=self.data_format,\n name=self.name)\n\n\n@tf_export(\"nn.dilation2d\", v1=[])\ndef dilation2d_v2(\n input, # pylint: disable=redefined-builtin\n filters, # pylint: disable=redefined-builtin\n strides,\n padding,\n data_format,\n dilations,\n name=None):\n \"\"\"Computes the grayscale dilation of 4-D `input` and 3-D `filters` tensors.\n\n The `input` tensor has shape `[batch, in_height, in_width, depth]` and the\n `filters` tensor has shape `[filter_height, filter_width, depth]`, i.e., each\n input channel is processed independently of the others with its own\n structuring function. The `output` tensor has shape\n `[batch, out_height, out_width, depth]`. The spatial dimensions of the output\n tensor depend on the `padding` algorithm. We currently only support the\n default \"NHWC\" `data_format`.\n\n In detail, the grayscale morphological 2-D dilation is the max-sum correlation\n (for consistency with `conv2d`, we use unmirrored filters):\n\n output[b, y, x, c] =\n max_{dy, dx} input[b,\n strides[1] * y + rates[1] * dy,\n strides[2] * x + rates[2] * dx,\n c] +\n filters[dy, dx, c]\n\n Max-pooling is a special case when the filter has size equal to the pooling\n kernel size and contains all zeros.\n\n Note on duality: The dilation of `input` by the `filters` is equal to the\n negation of the erosion of `-input` by the reflected `filters`.\n\n Args:\n input: A `Tensor`. Must be one of the following types: `float32`, `float64`,\n `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`,\n `uint32`, `uint64`.\n 4-D with shape `[batch, in_height, in_width, depth]`.\n filters: A `Tensor`. Must have the same type as `input`.\n 3-D with shape `[filter_height, filter_width, depth]`.\n strides: A list of `ints` that has length `>= 4`.\n The stride of the sliding window for each dimension of the input\n tensor. Must be: `[1, stride_height, stride_width, 1]`.\n padding: A `string` from: `\"SAME\", \"VALID\"`.\n The type of padding algorithm to use.\n data_format: A `string`, only `\"NCHW\"` is currently supported.\n dilations: A list of `ints` that has length `>= 4`.\n The input stride for atrous morphological dilation. Must be:\n `[1, rate_height, rate_width, 1]`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `input`.\n \"\"\"\n if data_format != \"NCHW\":\n raise ValueError(\"Data formats other than NCHW are not yet supported\")\n\n return gen_nn_ops.dilation2d(input=input,\n filter=filters,\n strides=strides,\n rates=dilations,\n padding=padding,\n name=name)\n\n\n@tf_export(\"nn.with_space_to_batch\")\ndef with_space_to_batch(\n input, # pylint: disable=redefined-builtin\n dilation_rate,\n padding,\n op,\n filter_shape=None,\n spatial_dims=None,\n data_format=None):\n \"\"\"Performs `op` on the space-to-batch representation of `input`.\n\n This has the effect of transforming sliding window operations into the\n corresponding \"atrous\" operation in which the input is sampled at the\n specified `dilation_rate`.\n\n In the special case that `dilation_rate` is uniformly 1, this simply returns:\n\n op(input, num_spatial_dims, padding)\n\n Otherwise, it returns:\n\n batch_to_space_nd(\n op(space_to_batch_nd(input, adjusted_dilation_rate, adjusted_paddings),\n num_spatial_dims,\n \"VALID\")\n adjusted_dilation_rate,\n adjusted_crops),\n\n where:\n\n adjusted_dilation_rate is an int64 tensor of shape [max(spatial_dims)],\n adjusted_{paddings,crops} are int64 tensors of shape [max(spatial_dims), 2]\n\n defined as follows:\n\n We first define two int64 tensors `paddings` and `crops` of shape\n `[num_spatial_dims, 2]` based on the value of `padding` and the spatial\n dimensions of the `input`:\n\n If `padding = \"VALID\"`, then:\n\n paddings, crops = required_space_to_batch_paddings(\n input_shape[spatial_dims],\n dilation_rate)\n\n If `padding = \"SAME\"`, then:\n\n dilated_filter_shape =\n filter_shape + (filter_shape - 1) * (dilation_rate - 1)\n\n paddings, crops = required_space_to_batch_paddings(\n input_shape[spatial_dims],\n dilation_rate,\n [(dilated_filter_shape - 1) // 2,\n dilated_filter_shape - 1 - (dilated_filter_shape - 1) // 2])\n\n Because `space_to_batch_nd` and `batch_to_space_nd` assume that the spatial\n dimensions are contiguous starting at the second dimension, but the specified\n `spatial_dims` may not be, we must adjust `dilation_rate`, `paddings` and\n `crops` in order to be usable with these operations. For a given dimension,\n if the block size is 1, and both the starting and ending padding and crop\n amounts are 0, then space_to_batch_nd effectively leaves that dimension alone,\n which is what is needed for dimensions not part of `spatial_dims`.\n Furthermore, `space_to_batch_nd` and `batch_to_space_nd` handle this case\n efficiently for any number of leading and trailing dimensions.\n\n For 0 <= i < len(spatial_dims), we assign:\n\n adjusted_dilation_rate[spatial_dims[i] - 1] = dilation_rate[i]\n adjusted_paddings[spatial_dims[i] - 1, :] = paddings[i, :]\n adjusted_crops[spatial_dims[i] - 1, :] = crops[i, :]\n\n All unassigned values of `adjusted_dilation_rate` default to 1, while all\n unassigned values of `adjusted_paddings` and `adjusted_crops` default to 0.\n\n Note in the case that `dilation_rate` is not uniformly 1, specifying \"VALID\"\n padding is equivalent to specifying `padding = \"SAME\"` with a filter_shape of\n `[1]*N`.\n\n Advanced usage. Note the following optimization: A sequence of\n `with_space_to_batch` operations with identical (not uniformly 1)\n `dilation_rate` parameters and \"VALID\" padding\n\n net = with_space_to_batch(net, dilation_rate, \"VALID\", op_1)\n ...\n net = with_space_to_batch(net, dilation_rate, \"VALID\", op_k)\n\n can be combined into a single `with_space_to_batch` operation as follows:\n\n def combined_op(converted_input, num_spatial_dims, _):\n result = op_1(converted_input, num_spatial_dims, \"VALID\")\n ...\n result = op_k(result, num_spatial_dims, \"VALID\")\n\n net = with_space_to_batch(net, dilation_rate, \"VALID\", combined_op)\n\n This eliminates the overhead of `k-1` calls to `space_to_batch_nd` and\n `batch_to_space_nd`.\n\n Similarly, a sequence of `with_space_to_batch` operations with identical (not\n uniformly 1) `dilation_rate` parameters, \"SAME\" padding, and odd filter\n dimensions\n\n net = with_space_to_batch(net, dilation_rate, \"SAME\", op_1, filter_shape_1)\n ...\n net = with_space_to_batch(net, dilation_rate, \"SAME\", op_k, filter_shape_k)\n\n can be combined into a single `with_space_to_batch` operation as follows:\n\n def combined_op(converted_input, num_spatial_dims, _):\n result = op_1(converted_input, num_spatial_dims, \"SAME\")\n ...\n result = op_k(result, num_spatial_dims, \"SAME\")\n\n net = with_space_to_batch(net, dilation_rate, \"VALID\", combined_op)\n\n Args:\n input: Tensor of rank > max(spatial_dims).\n dilation_rate: int32 Tensor of *known* shape [num_spatial_dims].\n padding: str constant equal to \"VALID\" or \"SAME\"\n op: Function that maps (input, num_spatial_dims, padding) -> output\n filter_shape: If padding = \"SAME\", specifies the shape of the convolution\n kernel/pooling window as an integer Tensor of shape [>=num_spatial_dims].\n If padding = \"VALID\", filter_shape is ignored and need not be specified.\n spatial_dims: Monotonically increasing sequence of `num_spatial_dims`\n integers (which are >= 1) specifying the spatial dimensions of `input`\n and output. Defaults to: `range(1, num_spatial_dims+1)`.\n data_format: A string or None. Specifies whether the channel dimension of\n the `input` and output is the last dimension (default, or if `data_format`\n does not start with \"NC\"), or the second dimension (if `data_format`\n starts with \"NC\"). For N=1, the valid values are \"NWC\" (default) and\n \"NCW\". For N=2, the valid values are \"NHWC\" (default) and \"NCHW\".\n For N=3, the valid values are \"NDHWC\" (default) and \"NCDHW\".\n\n Returns:\n The output Tensor as described above, dimensions will vary based on the op\n provided.\n\n Raises:\n ValueError: if `padding` is invalid or the arguments are incompatible.\n ValueError: if `spatial_dims` are invalid.\n\n \"\"\"\n input = ops.convert_to_tensor(input, name=\"input\") # pylint: disable=redefined-builtin\n input_shape = input.get_shape()\n\n def build_op(num_spatial_dims, padding):\n return lambda inp, _: op(inp, num_spatial_dims, padding)\n\n new_op = _WithSpaceToBatch(\n input_shape,\n dilation_rate,\n padding,\n build_op,\n filter_shape=filter_shape,\n spatial_dims=spatial_dims,\n data_format=data_format)\n return new_op(input, None)\n\n\nclass _WithSpaceToBatch(object):\n \"\"\"Helper class for with_space_to_batch.\n\n Note that this class assumes that shapes of input and filter passed to\n __call__ are compatible with input_shape and filter_shape passed to the\n constructor.\n\n Arguments\n input_shape: static shape of input. i.e. input.get_shape().\n dilation_rate: see with_space_to_batch\n padding: see with_space_to_batch\n build_op: Function that maps (num_spatial_dims, paddings) -> (function that\n maps (input, filter) -> output).\n filter_shape: see with_space_to_batch\n spatial_dims: see with_space_to_batch\n data_format: see with_space_to_batch\n \"\"\"\n\n def __init__(self,\n input_shape,\n dilation_rate,\n padding,\n build_op,\n filter_shape=None,\n spatial_dims=None,\n data_format=None):\n \"\"\"Helper class for _with_space_to_batch.\"\"\"\n dilation_rate = ops.convert_to_tensor(\n dilation_rate, dtypes.int32, name=\"dilation_rate\")\n try:\n rate_shape = dilation_rate.get_shape().with_rank(1)\n except ValueError:\n raise ValueError(\"rate must be rank 1\")\n\n if not dilation_rate.get_shape().is_fully_defined():\n raise ValueError(\"rate must have known shape\")\n\n num_spatial_dims = rate_shape.dims[0].value\n\n if data_format is not None and data_format.startswith(\"NC\"):\n starting_spatial_dim = 2\n else:\n starting_spatial_dim = 1\n\n if spatial_dims is None:\n spatial_dims = range(starting_spatial_dim,\n num_spatial_dims + starting_spatial_dim)\n orig_spatial_dims = list(spatial_dims)\n spatial_dims = sorted(set(int(x) for x in orig_spatial_dims))\n if spatial_dims != orig_spatial_dims or any(x < 1 for x in spatial_dims):\n raise ValueError(\n \"spatial_dims must be a montonically increasing sequence of positive \"\n \"integers\") # pylint: disable=line-too-long\n\n if data_format is not None and data_format.startswith(\"NC\"):\n expected_input_rank = spatial_dims[-1]\n else:\n expected_input_rank = spatial_dims[-1] + 1\n\n try:\n input_shape.with_rank_at_least(expected_input_rank)\n except ValueError:\n raise ValueError(\n \"input tensor must have rank %d at least\" % (expected_input_rank))\n\n const_rate = tensor_util.constant_value(dilation_rate)\n rate_or_const_rate = dilation_rate\n if const_rate is not None:\n rate_or_const_rate = const_rate\n if np.any(const_rate < 1):\n raise ValueError(\"dilation_rate must be positive\")\n if np.all(const_rate == 1):\n self.call = build_op(num_spatial_dims, padding)\n return\n\n # We have two padding contributions. The first is used for converting \"SAME\"\n # to \"VALID\". The second is required so that the height and width of the\n # zero-padded value tensor are multiples of rate.\n\n # Padding required to reduce to \"VALID\" convolution\n if padding == \"SAME\":\n if filter_shape is None:\n raise ValueError(\"filter_shape must be specified for SAME padding\")\n filter_shape = ops.convert_to_tensor(filter_shape, name=\"filter_shape\")\n const_filter_shape = tensor_util.constant_value(filter_shape)\n if const_filter_shape is not None:\n filter_shape = const_filter_shape\n self.base_paddings = _with_space_to_batch_base_paddings(\n const_filter_shape, num_spatial_dims, rate_or_const_rate)\n else:\n self.num_spatial_dims = num_spatial_dims\n self.rate_or_const_rate = rate_or_const_rate\n self.base_paddings = None\n elif padding == \"VALID\":\n self.base_paddings = np.zeros([num_spatial_dims, 2], np.int32)\n else:\n raise ValueError(\"Invalid padding method %r\" % padding)\n\n self.input_shape = input_shape\n self.spatial_dims = spatial_dims\n self.dilation_rate = dilation_rate\n self.data_format = data_format\n self.op = build_op(num_spatial_dims, \"VALID\")\n self.call = self._with_space_to_batch_call\n\n def _with_space_to_batch_call(self, inp, filter): # pylint: disable=redefined-builtin\n \"\"\"Call functionality for with_space_to_batch.\"\"\"\n # Handle input whose shape is unknown during graph creation.\n input_spatial_shape = None\n input_shape = self.input_shape\n spatial_dims = self.spatial_dims\n if input_shape.ndims is not None:\n input_shape_list = input_shape.as_list()\n input_spatial_shape = [input_shape_list[i] for i in spatial_dims]\n if input_spatial_shape is None or None in input_spatial_shape:\n input_shape_tensor = array_ops.shape(inp)\n input_spatial_shape = array_ops.stack(\n [input_shape_tensor[i] for i in spatial_dims])\n\n base_paddings = self.base_paddings\n if base_paddings is None:\n # base_paddings could not be computed at build time since static filter\n # shape was not fully defined.\n filter_shape = array_ops.shape(filter)\n base_paddings = _with_space_to_batch_base_paddings(\n filter_shape, self.num_spatial_dims, self.rate_or_const_rate)\n paddings, crops = array_ops.required_space_to_batch_paddings(\n input_shape=input_spatial_shape,\n base_paddings=base_paddings,\n block_shape=self.dilation_rate)\n\n dilation_rate = _with_space_to_batch_adjust(self.dilation_rate, 1,\n spatial_dims)\n paddings = _with_space_to_batch_adjust(paddings, 0, spatial_dims)\n crops = _with_space_to_batch_adjust(crops, 0, spatial_dims)\n input_converted = array_ops.space_to_batch_nd(\n input=inp, block_shape=dilation_rate, paddings=paddings)\n\n result = self.op(input_converted, filter)\n\n result_converted = array_ops.batch_to_space_nd(\n input=result, block_shape=dilation_rate, crops=crops)\n\n # Recover channel information for output shape if channels are not last.\n if self.data_format is not None and self.data_format.startswith(\"NC\"):\n if not result_converted.shape.dims[1].value and filter is not None:\n output_shape = result_converted.shape.as_list()\n output_shape[1] = filter.shape[-1]\n result_converted.set_shape(output_shape)\n\n return result_converted\n\n def __call__(self, inp, filter): # pylint: disable=redefined-builtin\n return self.call(inp, filter)\n\n\ndef _with_space_to_batch_base_paddings(filter_shape, num_spatial_dims,\n rate_or_const_rate):\n \"\"\"Helper function to compute base_paddings.\"\"\"\n # Spatial dimensions of the filters and the upsampled filters in which we\n # introduce (rate - 1) zeros between consecutive filter values.\n filter_spatial_shape = filter_shape[:num_spatial_dims]\n dilated_filter_spatial_shape = (\n filter_spatial_shape + (filter_spatial_shape - 1) *\n (rate_or_const_rate - 1))\n pad_extra_shape = dilated_filter_spatial_shape - 1\n\n # When full_padding_shape is odd, we pad more at end, following the same\n # convention as conv2d.\n pad_extra_start = pad_extra_shape // 2\n pad_extra_end = pad_extra_shape - pad_extra_start\n base_paddings = array_ops.stack(\n [[pad_extra_start[i], pad_extra_end[i]] for i in range(num_spatial_dims)])\n return base_paddings\n\n\ndef _with_space_to_batch_adjust(orig, fill_value, spatial_dims):\n \"\"\"Returns an `adjusted` version of `orig` based on `spatial_dims`.\n\n Tensor of the same type as `orig` and with shape\n `[max(spatial_dims), ...]` where:\n\n adjusted[spatial_dims[i] - 1, ...] = orig[i, ...]\n\n for 0 <= i < len(spatial_dims), and\n\n adjusted[j, ...] = fill_value\n\n for j != spatial_dims[i] - 1 for some i.\n\n If `orig` is a constant value, then the result will be a constant value.\n\n Args:\n orig: Tensor of rank > max(spatial_dims).\n fill_value: Numpy scalar (of same data type as `orig) specifying the fill\n value for non-spatial dimensions.\n spatial_dims: See with_space_to_batch.\n\n Returns:\n `adjusted` tensor.\n \"\"\"\n fill_dims = orig.get_shape().as_list()[1:]\n dtype = orig.dtype.as_numpy_dtype\n parts = []\n const_orig = tensor_util.constant_value(orig)\n const_or_orig = const_orig if const_orig is not None else orig\n prev_spatial_dim = 0\n i = 0\n while i < len(spatial_dims):\n start_i = i\n start_spatial_dim = spatial_dims[i]\n if start_spatial_dim > 1:\n # Fill in any gap from the previous spatial dimension (or dimension 1 if\n # this is the first spatial dimension) with `fill_value`.\n parts.append(\n np.full(\n [start_spatial_dim - 1 - prev_spatial_dim] + fill_dims,\n fill_value,\n dtype=dtype))\n # Find the largest value of i such that:\n # [spatial_dims[start_i], ..., spatial_dims[i]]\n # == [start_spatial_dim, ..., start_spatial_dim + i - start_i],\n # i.e. the end of a contiguous group of spatial dimensions.\n while (i + 1 < len(spatial_dims) and\n spatial_dims[i + 1] == spatial_dims[i] + 1):\n i += 1\n parts.append(const_or_orig[start_i:i + 1])\n prev_spatial_dim = spatial_dims[i]\n i += 1\n if const_orig is not None:\n return np.concatenate(parts)\n else:\n return array_ops.concat(parts, 0)\n\n\ndef _get_strides_and_dilation_rate(num_spatial_dims, strides, dilation_rate):\n \"\"\"Helper function for verifying strides and dilation_rate arguments.\n\n This is used by `convolution` and `pool`.\n\n Args:\n num_spatial_dims: int\n strides: Optional. List of N ints >= 1. Defaults to [1]*N. If any value\n of strides is > 1, then all values of dilation_rate must be 1.\n dilation_rate: Optional. List of N ints >= 1. Defaults to [1]*N. If any\n value of dilation_rate is > 1, then all values of strides must be 1.\n\n Returns:\n Normalized (strides, dilation_rate) as int32 numpy arrays of shape\n [num_spatial_dims].\n\n Raises:\n ValueError: if the parameters are invalid.\n \"\"\"\n if dilation_rate is None:\n dilation_rate = [1] * num_spatial_dims\n elif len(dilation_rate) != num_spatial_dims:\n raise ValueError(\"len(dilation_rate)=%d but should be %d\" %\n (len(dilation_rate), num_spatial_dims))\n dilation_rate = np.array(dilation_rate, dtype=np.int32)\n if np.any(dilation_rate < 1):\n raise ValueError(\"all values of dilation_rate must be positive\")\n\n if strides is None:\n strides = [1] * num_spatial_dims\n elif len(strides) != num_spatial_dims:\n raise ValueError(\"len(strides)=%d but should be %d\" % (len(strides),\n num_spatial_dims))\n strides = np.array(strides, dtype=np.int32)\n if np.any(strides < 1):\n raise ValueError(\"all values of strides must be positive\")\n\n if np.any(strides > 1) and np.any(dilation_rate > 1):\n raise ValueError(\n \"strides > 1 not supported in conjunction with dilation_rate > 1\")\n return strides, dilation_rate\n\n\n@tf_export(v1=[\"nn.convolution\"])\ndef convolution(\n input, # pylint: disable=redefined-builtin\n filter, # pylint: disable=redefined-builtin\n padding,\n strides=None,\n dilation_rate=None,\n name=None,\n data_format=None):\n # pylint: disable=line-too-long\n \"\"\"Computes sums of N-D convolutions (actually cross-correlation).\n\n This also supports either output striding via the optional `strides` parameter\n or atrous convolution (also known as convolution with holes or dilated\n convolution, based on the French word \"trous\" meaning holes in English) via\n the optional `dilation_rate` parameter. Currently, however, output striding\n is not supported for atrous convolutions.\n\n Specifically, in the case that `data_format` does not start with \"NC\", given\n a rank (N+2) `input` Tensor of shape\n\n [num_batches,\n input_spatial_shape[0],\n ...,\n input_spatial_shape[N-1],\n num_input_channels],\n\n a rank (N+2) `filter` Tensor of shape\n\n [spatial_filter_shape[0],\n ...,\n spatial_filter_shape[N-1],\n num_input_channels,\n num_output_channels],\n\n an optional `dilation_rate` tensor of shape [N] (defaulting to [1]*N)\n specifying the filter upsampling/input downsampling rate, and an optional list\n of N `strides` (defaulting [1]*N), this computes for each N-D spatial output\n position (x[0], ..., x[N-1]):\n\n ```\n output[b, x[0], ..., x[N-1], k] =\n sum_{z[0], ..., z[N-1], q}\n filter[z[0], ..., z[N-1], q, k] *\n padded_input[b,\n x[0]*strides[0] + dilation_rate[0]*z[0],\n ...,\n x[N-1]*strides[N-1] + dilation_rate[N-1]*z[N-1],\n q]\n ```\n where b is the index into the batch, k is the output channel number, q is the\n input channel number, and z is the N-D spatial offset within the filter. Here,\n `padded_input` is obtained by zero padding the input using an effective\n spatial filter shape of `(spatial_filter_shape-1) * dilation_rate + 1` and\n output striding `strides` as described in the\n [comment here](https://tensorflow.org/api_guides/python/nn#Convolution).\n\n In the case that `data_format` does start with `\"NC\"`, the `input` and output\n (but not the `filter`) are simply transposed as follows:\n\n convolution(input, data_format, **kwargs) =\n tf.transpose(convolution(tf.transpose(input, [0] + range(2,N+2) + [1]),\n **kwargs),\n [0, N+1] + range(1, N+1))\n\n It is required that 1 <= N <= 3.\n\n Args:\n input: An (N+2)-D `Tensor` of type `T`, of shape\n `[batch_size] + input_spatial_shape + [in_channels]` if data_format does\n not start with \"NC\" (default), or\n `[batch_size, in_channels] + input_spatial_shape` if data_format starts\n with \"NC\".\n filter: An (N+2)-D `Tensor` with the same type as `input` and shape\n `spatial_filter_shape + [in_channels, out_channels]`.\n padding: A string, either `\"VALID\"` or `\"SAME\"`. The padding algorithm.\n strides: Optional. Sequence of N ints >= 1. Specifies the output stride.\n Defaults to [1]*N. If any value of strides is > 1, then all values of\n dilation_rate must be 1.\n dilation_rate: Optional. Sequence of N ints >= 1. Specifies the filter\n upsampling/input downsampling rate. In the literature, the same parameter\n is sometimes called `input stride` or `dilation`. The effective filter\n size used for the convolution will be `spatial_filter_shape +\n (spatial_filter_shape - 1) * (rate - 1)`, obtained by inserting\n (dilation_rate[i]-1) zeros between consecutive elements of the original\n filter in each spatial dimension i. If any value of dilation_rate is > 1,\n then all values of strides must be 1.\n name: Optional name for the returned tensor.\n data_format: A string or None. Specifies whether the channel dimension of\n the `input` and output is the last dimension (default, or if `data_format`\n does not start with \"NC\"), or the second dimension (if `data_format`\n starts with \"NC\"). For N=1, the valid values are \"NWC\" (default) and\n \"NCW\". For N=2, the valid values are \"NHWC\" (default) and \"NCHW\".\n For N=3, the valid values are \"NDHWC\" (default) and \"NCDHW\".\n\n Returns:\n A `Tensor` with the same type as `input` of shape\n\n `[batch_size] + output_spatial_shape + [out_channels]`\n\n if data_format is None or does not start with \"NC\", or\n\n `[batch_size, out_channels] + output_spatial_shape`\n\n if data_format starts with \"NC\",\n where `output_spatial_shape` depends on the value of `padding`.\n\n If padding == \"SAME\":\n output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides[i])\n\n If padding == \"VALID\":\n output_spatial_shape[i] =\n ceil((input_spatial_shape[i] -\n (spatial_filter_shape[i]-1) * dilation_rate[i])\n / strides[i]).\n\n Raises:\n ValueError: If input/output depth does not match `filter` shape, if padding\n is other than `\"VALID\"` or `\"SAME\"`, or if data_format is invalid.\n\n \"\"\"\n # pylint: enable=line-too-long\n with ops.name_scope(name, \"convolution\", [input, filter]) as name:\n input = ops.convert_to_tensor(input, name=\"input\") # pylint: disable=redefined-builtin\n input_shape = input.get_shape()\n filter = ops.convert_to_tensor(filter, name=\"filter\") # pylint: disable=redefined-builtin\n filter_shape = filter.get_shape()\n op = Convolution(\n input_shape,\n filter_shape,\n padding,\n strides=strides,\n dilation_rate=dilation_rate,\n name=name,\n data_format=data_format)\n return op(input, filter)\n\n\n@tf_export(\"nn.convolution\", v1=[])\ndef convolution_v2(\n input, # pylint: disable=redefined-builtin\n filters,\n strides=None,\n padding=\"VALID\",\n data_format=None,\n dilations=None,\n name=None):\n return convolution(\n input, # pylint: disable=redefined-builtin\n filters,\n padding=padding,\n strides=strides,\n dilation_rate=dilations,\n name=name,\n data_format=data_format)\n\nconvolution_v2.__doc__ = deprecation.rewrite_argument_docstring(\n deprecation.rewrite_argument_docstring(\n convolution.__doc__, \"dilation_rate\", \"dilations\"),\n \"filter\", \"filters\")\n\n\nclass Convolution(object):\n \"\"\"Helper class for convolution.\n\n Note that this class assumes that shapes of input and filter passed to\n __call__ are compatible with input_shape and filter_shape passed to the\n constructor.\n\n Arguments\n input_shape: static shape of input. i.e. input.get_shape().\n filter_shape: static shape of the filter. i.e. filter.get_shape().\n padding: see convolution.\n strides: see convolution.\n dilation_rate: see convolution.\n name: see convolution.\n data_format: see convolution.\n \"\"\"\n\n def __init__(self,\n input_shape,\n filter_shape,\n padding,\n strides=None,\n dilation_rate=None,\n name=None,\n data_format=None):\n \"\"\"Helper function for convolution.\"\"\"\n num_total_dims = filter_shape.ndims\n if num_total_dims is None:\n num_total_dims = input_shape.ndims\n if num_total_dims is None:\n raise ValueError(\"rank of input or filter must be known\")\n\n num_spatial_dims = num_total_dims - 2\n\n try:\n input_shape.with_rank(num_spatial_dims + 2)\n except ValueError:\n raise ValueError(\n \"input tensor must have rank %d\" % (num_spatial_dims + 2))\n\n try:\n filter_shape.with_rank(num_spatial_dims + 2)\n except ValueError:\n raise ValueError(\n \"filter tensor must have rank %d\" % (num_spatial_dims + 2))\n\n if data_format is None or not data_format.startswith(\"NC\"):\n input_channels_dim = tensor_shape.dimension_at_index(\n input_shape, num_spatial_dims + 1)\n spatial_dims = range(1, num_spatial_dims + 1)\n else:\n input_channels_dim = tensor_shape.dimension_at_index(input_shape, 1)\n spatial_dims = range(2, num_spatial_dims + 2)\n\n if not input_channels_dim.is_compatible_with(\n filter_shape[num_spatial_dims]):\n raise ValueError(\n \"number of input channels does not match corresponding dimension of \"\n \"filter, {} != {}\".format(input_channels_dim,\n filter_shape[num_spatial_dims]))\n\n strides, dilation_rate = _get_strides_and_dilation_rate(\n num_spatial_dims, strides, dilation_rate)\n\n self.input_shape = input_shape\n self.filter_shape = filter_shape\n self.data_format = data_format\n self.strides = strides\n self.name = name\n self.conv_op = _WithSpaceToBatch(\n input_shape,\n dilation_rate=dilation_rate,\n padding=padding,\n build_op=self._build_op,\n filter_shape=filter_shape,\n spatial_dims=spatial_dims,\n data_format=data_format)\n\n def _build_op(self, _, padding):\n return _NonAtrousConvolution(\n self.input_shape,\n filter_shape=self.filter_shape,\n padding=padding,\n data_format=self.data_format,\n strides=self.strides,\n name=self.name)\n\n def __call__(self, inp, filter): # pylint: disable=redefined-builtin\n return self.conv_op(inp, filter)\n\n\n@tf_export(v1=[\"nn.pool\"])\ndef pool(\n input, # pylint: disable=redefined-builtin\n window_shape,\n pooling_type,\n padding,\n dilation_rate=None,\n strides=None,\n name=None,\n data_format=None):\n # pylint: disable=line-too-long\n \"\"\"Performs an N-D pooling operation.\n\n In the case that `data_format` does not start with \"NC\", computes for\n 0 <= b < batch_size,\n 0 <= x[i] < output_spatial_shape[i],\n 0 <= c < num_channels:\n\n ```\n output[b, x[0], ..., x[N-1], c] =\n REDUCE_{z[0], ..., z[N-1]}\n input[b,\n x[0] * strides[0] - pad_before[0] + dilation_rate[0]*z[0],\n ...\n x[N-1]*strides[N-1] - pad_before[N-1] + dilation_rate[N-1]*z[N-1],\n c],\n ```\n\n where the reduction function REDUCE depends on the value of `pooling_type`,\n and pad_before is defined based on the value of `padding` as described in\n the \"returns\" section of `tf.nn.convolution` for details.\n The reduction never includes out-of-bounds positions.\n\n In the case that `data_format` starts with `\"NC\"`, the `input` and output are\n simply transposed as follows:\n\n ```\n pool(input, data_format, **kwargs) =\n tf.transpose(pool(tf.transpose(input, [0] + range(2,N+2) + [1]),\n **kwargs),\n [0, N+1] + range(1, N+1))\n ```\n\n Args:\n input: Tensor of rank N+2, of shape\n `[batch_size] + input_spatial_shape + [num_channels]` if data_format does\n not start with \"NC\" (default), or\n `[batch_size, num_channels] + input_spatial_shape` if data_format starts\n with \"NC\". Pooling happens over the spatial dimensions only.\n window_shape: Sequence of N ints >= 1.\n pooling_type: Specifies pooling operation, must be \"AVG\" or \"MAX\".\n padding: The padding algorithm, must be \"SAME\" or \"VALID\".\n See the \"returns\" section of `tf.nn.convolution` for details.\n dilation_rate: Optional. Dilation rate. List of N ints >= 1.\n Defaults to [1]*N. If any value of dilation_rate is > 1, then all values\n of strides must be 1.\n strides: Optional. Sequence of N ints >= 1. Defaults to [1]*N.\n If any value of strides is > 1, then all values of dilation_rate must be\n 1.\n name: Optional. Name of the op.\n data_format: A string or None. Specifies whether the channel dimension of\n the `input` and output is the last dimension (default, or if `data_format`\n does not start with \"NC\"), or the second dimension (if `data_format`\n starts with \"NC\"). For N=1, the valid values are \"NWC\" (default) and\n \"NCW\". For N=2, the valid values are \"NHWC\" (default) and \"NCHW\".\n For N=3, the valid values are \"NDHWC\" (default) and \"NCDHW\".\n\n Returns:\n Tensor of rank N+2, of shape\n [batch_size] + output_spatial_shape + [num_channels]\n\n if data_format is None or does not start with \"NC\", or\n\n [batch_size, num_channels] + output_spatial_shape\n\n if data_format starts with \"NC\",\n where `output_spatial_shape` depends on the value of padding:\n\n If padding = \"SAME\":\n output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides[i])\n\n If padding = \"VALID\":\n output_spatial_shape[i] =\n ceil((input_spatial_shape[i] - (window_shape[i] - 1) * dilation_rate[i])\n / strides[i]).\n\n Raises:\n ValueError: if arguments are invalid.\n\n \"\"\"\n # pylint: enable=line-too-long\n with ops.name_scope(name, \"%s_pool\" % (pooling_type.lower()),\n [input]) as scope:\n input = ops.convert_to_tensor(input, name=\"input\") # pylint: disable=redefined-builtin\n\n num_spatial_dims = len(window_shape)\n if num_spatial_dims < 1 or num_spatial_dims > 3:\n raise ValueError(\"It is required that 1 <= num_spatial_dims <= 3.\")\n\n input.get_shape().with_rank(num_spatial_dims + 2)\n\n strides, dilation_rate = _get_strides_and_dilation_rate(\n num_spatial_dims, strides, dilation_rate)\n\n if padding == \"SAME\" and np.any(dilation_rate > 1):\n raise ValueError(\n \"pooling with SAME padding is not implemented for dilation_rate > 1\")\n\n if np.any(strides > window_shape):\n raise ValueError(\n \"strides > window_shape not supported due to inconsistency between \"\n \"CPU and GPU implementations\")\n\n pooling_ops = {\n (\"MAX\", 1): max_pool,\n (\"MAX\", 2): max_pool,\n (\"MAX\", 3): max_pool3d, # pylint: disable=undefined-variable\n (\"AVG\", 1): avg_pool,\n (\"AVG\", 2): avg_pool,\n (\"AVG\", 3): avg_pool3d, # pylint: disable=undefined-variable\n }\n op_key = (pooling_type, num_spatial_dims)\n if op_key not in pooling_ops:\n raise ValueError(\"%d-D %s pooling is not supported.\" % (op_key[1],\n op_key[0]))\n\n if data_format is None or not data_format.startswith(\"NC\"):\n adjusted_window_shape = [1] + list(window_shape) + [1]\n adjusted_strides = [1] + list(strides) + [1]\n spatial_dims = range(1, num_spatial_dims + 1)\n else:\n adjusted_window_shape = [1, 1] + list(window_shape)\n adjusted_strides = [1, 1] + list(strides)\n spatial_dims = range(2, num_spatial_dims + 2)\n\n if num_spatial_dims == 1:\n if data_format is None or data_format == \"NWC\":\n data_format_kwargs = dict(data_format=\"NHWC\")\n elif data_format == \"NCW\":\n data_format_kwargs = dict(data_format=\"NCHW\")\n else:\n raise ValueError(\"data_format must be either \\\"NWC\\\" or \\\"NCW\\\".\")\n adjusted_window_shape = [1] + adjusted_window_shape\n adjusted_strides = [1] + adjusted_strides\n else:\n data_format_kwargs = dict(data_format=data_format)\n\n def op(converted_input, _, converted_padding): # pylint: disable=missing-docstring\n if num_spatial_dims == 1:\n converted_input = array_ops.expand_dims(converted_input,\n spatial_dims[0])\n result = pooling_ops[op_key](\n converted_input,\n adjusted_window_shape,\n adjusted_strides,\n converted_padding,\n name=scope,\n **data_format_kwargs)\n if num_spatial_dims == 1:\n result = array_ops.squeeze(result, [spatial_dims[0]])\n return result\n\n return with_space_to_batch(\n input=input,\n dilation_rate=dilation_rate,\n padding=padding,\n op=op,\n spatial_dims=spatial_dims,\n filter_shape=window_shape)\n\n\n@tf_export(\"nn.pool\", v1=[])\ndef pool_v2(\n input, # pylint: disable=redefined-builtin\n window_shape,\n pooling_type,\n strides=None,\n padding=\"VALID\",\n data_format=None,\n dilations=None,\n name=None):\n # pylint: disable=line-too-long\n \"\"\"Performs an N-D pooling operation.\n\n In the case that `data_format` does not start with \"NC\", computes for\n 0 <= b < batch_size,\n 0 <= x[i] < output_spatial_shape[i],\n 0 <= c < num_channels:\n\n ```\n output[b, x[0], ..., x[N-1], c] =\n REDUCE_{z[0], ..., z[N-1]}\n input[b,\n x[0] * strides[0] - pad_before[0] + dilation_rate[0]*z[0],\n ...\n x[N-1]*strides[N-1] - pad_before[N-1] + dilation_rate[N-1]*z[N-1],\n c],\n ```\n\n where the reduction function REDUCE depends on the value of `pooling_type`,\n and pad_before is defined based on the value of `padding` as described in\n the \"returns\" section of `tf.nn.convolution` for details.\n The reduction never includes out-of-bounds positions.\n\n In the case that `data_format` starts with `\"NC\"`, the `input` and output are\n simply transposed as follows:\n\n ```\n pool(input, data_format, **kwargs) =\n tf.transpose(pool(tf.transpose(input, [0] + range(2,N+2) + [1]),\n **kwargs),\n [0, N+1] + range(1, N+1))\n ```\n\n Args:\n input: Tensor of rank N+2, of shape `[batch_size] + input_spatial_shape +\n [num_channels]` if data_format does not start with \"NC\" (default), or\n `[batch_size, num_channels] + input_spatial_shape` if data_format starts\n with \"NC\". Pooling happens over the spatial dimensions only.\n window_shape: Sequence of N ints >= 1.\n pooling_type: Specifies pooling operation, must be \"AVG\" or \"MAX\".\n strides: Optional. Sequence of N ints >= 1. Defaults to [1]*N. If any value of\n strides is > 1, then all values of dilation_rate must be 1.\n padding: The padding algorithm, must be \"SAME\" or \"VALID\". Defaults to \"SAME\".\n See the \"returns\" section of `tf.nn.convolution` for details.\n data_format: A string or None. Specifies whether the channel dimension of\n the `input` and output is the last dimension (default, or if `data_format`\n does not start with \"NC\"), or the second dimension (if `data_format`\n starts with \"NC\"). For N=1, the valid values are \"NWC\" (default) and\n \"NCW\". For N=2, the valid values are \"NHWC\" (default) and \"NCHW\". For\n N=3, the valid values are \"NDHWC\" (default) and \"NCDHW\".\n dilations: Optional. Dilation rate. List of N ints >= 1. Defaults to\n [1]*N. If any value of dilation_rate is > 1, then all values of strides\n must be 1.\n name: Optional. Name of the op.\n\n Returns:\n Tensor of rank N+2, of shape\n [batch_size] + output_spatial_shape + [num_channels]\n\n if data_format is None or does not start with \"NC\", or\n\n [batch_size, num_channels] + output_spatial_shape\n\n if data_format starts with \"NC\",\n where `output_spatial_shape` depends on the value of padding:\n\n If padding = \"SAME\":\n output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides[i])\n\n If padding = \"VALID\":\n output_spatial_shape[i] =\n ceil((input_spatial_shape[i] - (window_shape[i] - 1) * dilation_rate[i])\n / strides[i]).\n\n Raises:\n ValueError: if arguments are invalid.\n\n \"\"\"\n return pool(\n input=input,\n window_shape=window_shape,\n pooling_type=pooling_type,\n padding=padding,\n dilation_rate=dilations,\n strides=strides,\n name=name,\n data_format=data_format)\n\n\n@tf_export(\"nn.atrous_conv2d\")\ndef atrous_conv2d(value, filters, rate, padding, name=None):\n \"\"\"Atrous convolution (a.k.a. convolution with holes or dilated convolution).\n\n This function is a simpler wrapper around the more general\n `tf.nn.convolution`, and exists only for backwards compatibility. You can\n use `tf.nn.convolution` to perform 1-D, 2-D, or 3-D atrous convolution.\n\n\n Computes a 2-D atrous convolution, also known as convolution with holes or\n dilated convolution, given 4-D `value` and `filters` tensors. If the `rate`\n parameter is equal to one, it performs regular 2-D convolution. If the `rate`\n parameter is greater than one, it performs convolution with holes, sampling\n the input values every `rate` pixels in the `height` and `width` dimensions.\n This is equivalent to convolving the input with a set of upsampled filters,\n produced by inserting `rate - 1` zeros between two consecutive values of the\n filters along the `height` and `width` dimensions, hence the name atrous\n convolution or convolution with holes (the French word trous means holes in\n English).\n\n More specifically:\n\n ```\n output[batch, height, width, out_channel] =\n sum_{dheight, dwidth, in_channel} (\n filters[dheight, dwidth, in_channel, out_channel] *\n value[batch, height + rate*dheight, width + rate*dwidth, in_channel]\n )\n ```\n\n Atrous convolution allows us to explicitly control how densely to compute\n feature responses in fully convolutional networks. Used in conjunction with\n bilinear interpolation, it offers an alternative to `conv2d_transpose` in\n dense prediction tasks such as semantic image segmentation, optical flow\n computation, or depth estimation. It also allows us to effectively enlarge\n the field of view of filters without increasing the number of parameters or\n the amount of computation.\n\n For a description of atrous convolution and how it can be used for dense\n feature extraction, please see: [Semantic Image Segmentation with Deep\n Convolutional Nets and Fully Connected CRFs](http://arxiv.org/abs/1412.7062).\n The same operation is investigated further in [Multi-Scale Context Aggregation\n by Dilated Convolutions](http://arxiv.org/abs/1511.07122). Previous works\n that effectively use atrous convolution in different ways are, among others,\n [OverFeat: Integrated Recognition, Localization and Detection using\n Convolutional Networks](http://arxiv.org/abs/1312.6229) and [Fast Image\n Scanning with Deep Max-Pooling Convolutional Neural\n Networks](http://arxiv.org/abs/1302.1700).\n Atrous convolution is also closely related to the so-called noble identities\n in multi-rate signal processing.\n\n There are many different ways to implement atrous convolution (see the refs\n above). The implementation here reduces\n\n ```python\n atrous_conv2d(value, filters, rate, padding=padding)\n ```\n\n to the following three operations:\n\n ```python\n paddings = ...\n net = space_to_batch(value, paddings, block_size=rate)\n net = conv2d(net, filters, strides=[1, 1, 1, 1], padding=\"VALID\")\n crops = ...\n net = batch_to_space(net, crops, block_size=rate)\n ```\n\n Advanced usage. Note the following optimization: A sequence of `atrous_conv2d`\n operations with identical `rate` parameters, 'SAME' `padding`, and filters\n with odd heights/ widths:\n\n ```python\n net = atrous_conv2d(net, filters1, rate, padding=\"SAME\")\n net = atrous_conv2d(net, filters2, rate, padding=\"SAME\")\n ...\n net = atrous_conv2d(net, filtersK, rate, padding=\"SAME\")\n ```\n\n can be equivalently performed cheaper in terms of computation and memory as:\n\n ```python\n pad = ... # padding so that the input dims are multiples of rate\n net = space_to_batch(net, paddings=pad, block_size=rate)\n net = conv2d(net, filters1, strides=[1, 1, 1, 1], padding=\"SAME\")\n net = conv2d(net, filters2, strides=[1, 1, 1, 1], padding=\"SAME\")\n ...\n net = conv2d(net, filtersK, strides=[1, 1, 1, 1], padding=\"SAME\")\n net = batch_to_space(net, crops=pad, block_size=rate)\n ```\n\n because a pair of consecutive `space_to_batch` and `batch_to_space` ops with\n the same `block_size` cancel out when their respective `paddings` and `crops`\n inputs are identical.\n\n Args:\n value: A 4-D `Tensor` of type `float`. It needs to be in the default \"NHWC\"\n format. Its shape is `[batch, in_height, in_width, in_channels]`.\n filters: A 4-D `Tensor` with the same type as `value` and shape\n `[filter_height, filter_width, in_channels, out_channels]`. `filters`'\n `in_channels` dimension must match that of `value`. Atrous convolution is\n equivalent to standard convolution with upsampled filters with effective\n height `filter_height + (filter_height - 1) * (rate - 1)` and effective\n width `filter_width + (filter_width - 1) * (rate - 1)`, produced by\n inserting `rate - 1` zeros along consecutive elements across the\n `filters`' spatial dimensions.\n rate: A positive int32. The stride with which we sample input values across\n the `height` and `width` dimensions. Equivalently, the rate by which we\n upsample the filter values by inserting zeros across the `height` and\n `width` dimensions. In the literature, the same parameter is sometimes\n called `input stride` or `dilation`.\n padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.\n name: Optional name for the returned tensor.\n\n Returns:\n A `Tensor` with the same type as `value`.\n Output shape with `'VALID'` padding is:\n\n [batch, height - 2 * (filter_width - 1),\n width - 2 * (filter_height - 1), out_channels].\n\n Output shape with `'SAME'` padding is:\n\n [batch, height, width, out_channels].\n\n Raises:\n ValueError: If input/output depth does not match `filters`' shape, or if\n padding is other than `'VALID'` or `'SAME'`.\n \"\"\"\n return convolution(\n input=value,\n filter=filters,\n padding=padding,\n dilation_rate=np.broadcast_to(rate, (2,)),\n name=name)\n\n\ndef _convert_padding(padding):\n \"\"\"Converts Python padding to C++ padding for ops which take EXPLICIT padding.\n\n Args:\n padding: the `padding` argument for a Python op which supports EXPLICIT\n padding.\n\n Returns:\n (padding, explicit_paddings) pair, which should be passed as attributes to a\n C++ op.\n\n Raises:\n ValueError: If padding is invalid.\n \"\"\"\n explicit_paddings = []\n if padding == \"EXPLICIT\":\n # Give a better error message if EXPLICIT is passed.\n raise ValueError('\"EXPLICIT\" is not a valid value for the padding '\n \"parameter. To use explicit padding, the padding \"\n \"parameter must be a list.\")\n if isinstance(padding, (list, tuple)):\n for i, dim_paddings in enumerate(padding):\n if not isinstance(dim_paddings, (list, tuple)):\n raise ValueError(\"When padding is a list, each element of padding must \"\n \"be a list/tuple of size 2. Element with index %d of \"\n \"padding is not a list/tuple\" % i)\n if len(dim_paddings) != 2:\n raise ValueError(\"When padding is a list, each element of padding must \"\n \"be a list/tuple of size 2. Element with index %d of \"\n \"padding has size %d\" % (i, len(dim_paddings)))\n explicit_paddings.extend(dim_paddings)\n if len(padding) != 4:\n raise ValueError(\"When padding is a list, it must be of size 4. Got \"\n \"padding of size: %d\" % len(padding))\n padding = \"EXPLICIT\"\n return padding, explicit_paddings\n\n\n@tf_export(\"nn.conv2d\", v1=[])\ndef conv2d_v2(input, # pylint: disable=redefined-builtin\n filters,\n strides,\n padding,\n data_format=\"NHWC\",\n dilations=None,\n name=None):\n # pylint: disable=line-too-long\n r\"\"\"Computes a 2-D convolution given 4-D `input` and `filters` tensors.\n\n Given an input tensor of shape `[batch, in_height, in_width, in_channels]`\n and a filter / kernel tensor of shape\n `[filter_height, filter_width, in_channels, out_channels]`, this op\n performs the following:\n\n 1. Flattens the filter to a 2-D matrix with shape\n `[filter_height * filter_width * in_channels, output_channels]`.\n 2. Extracts image patches from the input tensor to form a *virtual*\n tensor of shape `[batch, out_height, out_width,\n filter_height * filter_width * in_channels]`.\n 3. For each patch, right-multiplies the filter matrix and the image patch\n vector.\n\n In detail, with the default NHWC format,\n\n output[b, i, j, k] =\n sum_{di, dj, q} input[b, strides[1] * i + di, strides[2] * j + dj, q] *\n filter[di, dj, q, k]\n\n Must have `strides[0] = strides[3] = 1`. For the most common case of the same\n horizontal and vertices strides, `strides = [1, stride, stride, 1]`.\n\n Args:\n input: A `Tensor`. Must be one of the following types:\n `half`, `bfloat16`, `float32`, `float64`.\n A 4-D tensor. The dimension order is interpreted according to the value\n of `data_format`, see below for details.\n filters: A `Tensor`. Must have the same type as `input`.\n A 4-D tensor of shape\n `[filter_height, filter_width, in_channels, out_channels]`\n strides: A list of `ints`.\n 1-D tensor of length 4. The stride of the sliding window for each\n dimension of `input`. The dimension order is determined by the value of\n `data_format`, see below for details.\n padding: Either the `string `\"SAME\"` or `\"VALID\"` indicating the type of\n padding algorithm to use, or a list indicating the explicit paddings at\n the start and end of each dimension. When explicit padding is used and\n data_format is `\"NHWC\"`, this should be in the form `[[0, 0], [pad_top,\n pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used\n and data_format is `\"NCHW\"`, this should be in the form `[[0, 0], [0, 0],\n [pad_top, pad_bottom], [pad_left, pad_right]]`.\n data_format: An optional `string` from: `\"NHWC\", \"NCHW\"`.\n Defaults to `\"NHWC\"`.\n Specify the data format of the input and output data. With the\n default format \"NHWC\", the data is stored in the order of:\n [batch, height, width, channels].\n Alternatively, the format could be \"NCHW\", the data storage order of:\n [batch, channels, height, width].\n dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`.\n 1-D tensor of length 4. The dilation factor for each dimension of\n `input`. If set to k > 1, there will be k-1 skipped cells between each\n filter element on that dimension. The dimension order is determined by the\n value of `data_format`, see above for details. Dilations in the batch and\n depth dimensions must be 1.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `input`.\n \"\"\"\n # pylint: enable=line-too-long\n if dilations is None:\n dilations = [1, 1, 1, 1]\n return conv2d(input, # pylint: disable=redefined-builtin\n filters,\n strides,\n padding,\n use_cudnn_on_gpu=True,\n data_format=data_format,\n dilations=dilations,\n name=name)\n\n\n@tf_export(v1=[\"nn.conv2d\"])\ndef conv2d( # pylint: disable=redefined-builtin,dangerous-default-value\n input,\n filter,\n strides,\n padding,\n use_cudnn_on_gpu=True,\n data_format=\"NHWC\",\n dilations=[1, 1, 1, 1],\n name=None):\n r\"\"\"Computes a 2-D convolution given 4-D `input` and `filter` tensors.\n\n Given an input tensor of shape `[batch, in_height, in_width, in_channels]`\n and a filter / kernel tensor of shape\n `[filter_height, filter_width, in_channels, out_channels]`, this op\n performs the following:\n\n 1. Flattens the filter to a 2-D matrix with shape\n `[filter_height * filter_width * in_channels, output_channels]`.\n 2. Extracts image patches from the input tensor to form a *virtual*\n tensor of shape `[batch, out_height, out_width,\n filter_height * filter_width * in_channels]`.\n 3. For each patch, right-multiplies the filter matrix and the image patch\n vector.\n\n In detail, with the default NHWC format,\n\n output[b, i, j, k] =\n sum_{di, dj, q} input[b, strides[1] * i + di, strides[2] * j + dj, q]\n * filter[di, dj, q, k]\n\n Must have `strides[0] = strides[3] = 1`. For the most common case of the same\n horizontal and vertices strides, `strides = [1, stride, stride, 1]`.\n\n Args:\n input: A `Tensor`. Must be one of the following types:\n `half`, `bfloat16`, `float32`, `float64`.\n A 4-D tensor. The dimension order is interpreted according to the value\n of `data_format`, see below for details.\n filter: A `Tensor`. Must have the same type as `input`.\n A 4-D tensor of shape\n `[filter_height, filter_width, in_channels, out_channels]`\n strides: A list of `ints`.\n 1-D tensor of length 4. The stride of the sliding window for each\n dimension of `input`. The dimension order is determined by the value of\n `data_format`, see below for details.\n padding: Either the `string `\"SAME\"` or `\"VALID\"` indicating the type of\n padding algorithm to use, or a list indicating the explicit paddings at\n the start and end of each dimension. When explicit padding is used and\n data_format is `\"NHWC\"`, this should be in the form `[[0, 0], [pad_top,\n pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used\n and data_format is `\"NCHW\"`, this should be in the form `[[0, 0], [0, 0],\n [pad_top, pad_bottom], [pad_left, pad_right]]`.\n use_cudnn_on_gpu: An optional `bool`. Defaults to `True`.\n data_format: An optional `string` from: `\"NHWC\", \"NCHW\"`.\n Defaults to `\"NHWC\"`.\n Specify the data format of the input and output data. With the\n default format \"NHWC\", the data is stored in the order of:\n [batch, height, width, channels].\n Alternatively, the format could be \"NCHW\", the data storage order of:\n [batch, channels, height, width].\n dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`.\n 1-D tensor of length 4. The dilation factor for each dimension of\n `input`. If set to k > 1, there will be k-1 skipped cells between each\n filter element on that dimension. The dimension order is determined by the\n value of `data_format`, see above for details. Dilations in the batch and\n depth dimensions must be 1.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `input`.\n \"\"\"\n padding, explicit_paddings = _convert_padding(padding)\n return gen_nn_ops.conv2d(input, # pylint: disable=redefined-builtin\n filter,\n strides,\n padding,\n use_cudnn_on_gpu=use_cudnn_on_gpu,\n explicit_paddings=explicit_paddings,\n data_format=data_format,\n dilations=dilations,\n name=name)\n\n\n@tf_export(\"nn.conv2d_backprop_filter\", v1=[])\ndef conv2d_backprop_filter_v2(input, # pylint: disable=redefined-builtin\n filter_sizes,\n out_backprop,\n strides,\n padding,\n data_format=\"NHWC\",\n dilations=None,\n name=None):\n r\"\"\"Computes the gradients of convolution with respect to the filter.\n\n Args:\n input: A `Tensor`. Must be one of the following types:\n `half`, `bfloat16`, `float32`, `float64`.\n 4-D with shape `[batch, in_height, in_width, in_channels]`.\n filter_sizes: A `Tensor` of type `int32`.\n An integer vector representing the tensor shape of `filter`,\n where `filter` is a 4-D\n `[filter_height, filter_width, in_channels, out_channels]` tensor.\n out_backprop: A `Tensor`. Must have the same type as `input`.\n 4-D with shape `[batch, out_height, out_width, out_channels]`.\n Gradients w.r.t. the output of the convolution.\n strides: A list of `ints`.\n The stride of the sliding window for each dimension of the input\n of the convolution. Must be in the same order as the dimension specified\n with format.\n padding: Either the `string `\"SAME\"` or `\"VALID\"` indicating the type of\n padding algorithm to use, or a list indicating the explicit paddings at\n the start and end of each dimension. When explicit padding is used and\n data_format is `\"NHWC\"`, this should be in the form `[[0, 0], [pad_top,\n pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used\n and data_format is `\"NCHW\"`, this should be in the form `[[0, 0], [0, 0],\n [pad_top, pad_bottom], [pad_left, pad_right]]`.\n data_format: An optional `string` from: `\"NHWC\", \"NCHW\"`.\n Defaults to `\"NHWC\"`.\n Specify the data format of the input and output data. With the\n default format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\n Alternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width].\n dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`.\n 1-D tensor of length 4. The dilation factor for each dimension of\n `input`. If set to k > 1, there will be k-1 skipped cells between each\n filter element on that dimension. The dimension order is determined by\n the value of `data_format`, see above for details. Dilations in the batch\n and depth dimensions must be 1.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `input`.\n \"\"\"\n if dilations is None:\n dilations = [1, 1, 1, 1]\n return conv2d_backprop_filter(input, # pylint: disable=redefined-builtin\n filter_sizes,\n out_backprop,\n strides,\n padding,\n use_cudnn_on_gpu=True,\n data_format=data_format,\n dilations=dilations,\n name=name)\n\n\n@tf_export(v1=[\"nn.conv2d_backprop_filter\"])\ndef conv2d_backprop_filter( # pylint: disable=redefined-builtin,dangerous-default-value\n input,\n filter_sizes,\n out_backprop,\n strides,\n padding,\n use_cudnn_on_gpu=True,\n data_format=\"NHWC\",\n dilations=[1, 1, 1, 1],\n name=None):\n r\"\"\"Computes the gradients of convolution with respect to the filter.\n\n Args:\n input: A `Tensor`. Must be one of the following types:\n `half`, `bfloat16`, `float32`, `float64`.\n 4-D with shape `[batch, in_height, in_width, in_channels]`.\n filter_sizes: A `Tensor` of type `int32`.\n An integer vector representing the tensor shape of `filter`,\n where `filter` is a 4-D\n `[filter_height, filter_width, in_channels, out_channels]` tensor.\n out_backprop: A `Tensor`. Must have the same type as `input`.\n 4-D with shape `[batch, out_height, out_width, out_channels]`.\n Gradients w.r.t. the output of the convolution.\n strides: A list of `ints`.\n The stride of the sliding window for each dimension of the input\n of the convolution. Must be in the same order as the dimension specified\n with format.\n padding: Either the `string `\"SAME\"` or `\"VALID\"` indicating the type of\n padding algorithm to use, or a list indicating the explicit paddings at\n the start and end of each dimension. When explicit padding is used and\n data_format is `\"NHWC\"`, this should be in the form `[[0, 0], [pad_top,\n pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used\n and data_format is `\"NCHW\"`, this should be in the form `[[0, 0], [0, 0],\n [pad_top, pad_bottom], [pad_left, pad_right]]`.\n use_cudnn_on_gpu: An optional `bool`. Defaults to `True`.\n data_format: An optional `string` from: `\"NHWC\", \"NCHW\"`.\n Defaults to `\"NHWC\"`.\n Specify the data format of the input and output data. With the\n default format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\n Alternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width].\n dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`.\n 1-D tensor of length 4. The dilation factor for each dimension of\n `input`. If set to k > 1, there will be k-1 skipped cells between each\n filter element on that dimension. The dimension order is determined by\n the value of `data_format`, see above for details. Dilations in the batch\n and depth dimensions must be 1.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `input`.\n \"\"\"\n padding, explicit_paddings = _convert_padding(padding)\n return gen_nn_ops.conv2d_backprop_filter(\n input, filter_sizes, out_backprop, strides, padding, use_cudnn_on_gpu,\n explicit_paddings, data_format, dilations, name)\n\n\n@tf_export(\"nn.conv2d_backprop_input\", v1=[])\ndef conv2d_backprop_input_v2(input_sizes,\n filters,\n out_backprop,\n strides,\n padding,\n data_format=\"NHWC\",\n dilations=None,\n name=None):\n r\"\"\"Computes the gradients of convolution with respect to the input.\n\n Args:\n input_sizes: A `Tensor` of type `int32`.\n An integer vector representing the shape of `input`,\n where `input` is a 4-D `[batch, height, width, channels]` tensor.\n filters: A `Tensor`. Must be one of the following types:\n `half`, `bfloat16`, `float32`, `float64`.\n 4-D with shape\n `[filter_height, filter_width, in_channels, out_channels]`.\n out_backprop: A `Tensor`. Must have the same type as `filters`.\n 4-D with shape `[batch, out_height, out_width, out_channels]`.\n Gradients w.r.t. the output of the convolution.\n strides: A list of `ints`.\n The stride of the sliding window for each dimension of the input\n of the convolution. Must be in the same order as the dimension specified\n with format.\n padding: Either the `string `\"SAME\"` or `\"VALID\"` indicating the type of\n padding algorithm to use, or a list indicating the explicit paddings at\n the start and end of each dimension. When explicit padding is used and\n data_format is `\"NHWC\"`, this should be in the form `[[0, 0], [pad_top,\n pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used\n and data_format is `\"NCHW\"`, this should be in the form `[[0, 0], [0, 0],\n [pad_top, pad_bottom], [pad_left, pad_right]]`.\n data_format: An optional `string` from: `\"NHWC\", \"NCHW\"`.\n Defaults to `\"NHWC\"`.\n Specify the data format of the input and output data. With the\n default format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\n Alternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width].\n dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`.\n 1-D tensor of length 4. The dilation factor for each dimension of\n `input`. If set to k > 1, there will be k-1 skipped cells between each\n filter element on that dimension. The dimension order is determined by\n the value of `data_format`, see above for details. Dilations in the batch\n and depth dimensions must be 1.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `filters`.\n \"\"\"\n if dilations is None:\n dilations = [1, 1, 1, 1]\n return conv2d_backprop_input(input_sizes,\n filters,\n out_backprop,\n strides,\n padding,\n use_cudnn_on_gpu=True,\n data_format=data_format,\n dilations=dilations,\n name=name)\n\n\n@tf_export(v1=[\"nn.conv2d_backprop_input\"])\ndef conv2d_backprop_input( # pylint: disable=redefined-builtin,dangerous-default-value\n input_sizes,\n filter,\n out_backprop,\n strides,\n padding,\n use_cudnn_on_gpu=True,\n data_format=\"NHWC\",\n dilations=[1, 1, 1, 1],\n name=None):\n r\"\"\"Computes the gradients of convolution with respect to the input.\n\n Args:\n input_sizes: A `Tensor` of type `int32`.\n An integer vector representing the shape of `input`,\n where `input` is a 4-D `[batch, height, width, channels]` tensor.\n filter: A `Tensor`. Must be one of the following types:\n `half`, `bfloat16`, `float32`, `float64`.\n 4-D with shape\n `[filter_height, filter_width, in_channels, out_channels]`.\n out_backprop: A `Tensor`. Must have the same type as `filter`.\n 4-D with shape `[batch, out_height, out_width, out_channels]`.\n Gradients w.r.t. the output of the convolution.\n strides: A list of `ints`.\n The stride of the sliding window for each dimension of the input\n of the convolution. Must be in the same order as the dimension specified\n with format.\n padding: Either the `string `\"SAME\"` or `\"VALID\"` indicating the type of\n padding algorithm to use, or a list indicating the explicit paddings at\n the start and end of each dimension. When explicit padding is used and\n data_format is `\"NHWC\"`, this should be in the form `[[0, 0], [pad_top,\n pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used\n and data_format is `\"NCHW\"`, this should be in the form `[[0, 0], [0, 0],\n [pad_top, pad_bottom], [pad_left, pad_right]]`.\n use_cudnn_on_gpu: An optional `bool`. Defaults to `True`.\n data_format: An optional `string` from: `\"NHWC\", \"NCHW\"`.\n Defaults to `\"NHWC\"`.\n Specify the data format of the input and output data. With the\n default format \"NHWC\", the data is stored in the order of:\n [batch, in_height, in_width, in_channels].\n Alternatively, the format could be \"NCHW\", the data storage order of:\n [batch, in_channels, in_height, in_width].\n dilations: An optional list of `ints`. Defaults to `[1, 1, 1, 1]`.\n 1-D tensor of length 4. The dilation factor for each dimension of\n `input`. If set to k > 1, there will be k-1 skipped cells between each\n filter element on that dimension. The dimension order is determined by\n the value of `data_format`, see above for details. Dilations in the batch\n and depth dimensions must be 1.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `filter`.\n \"\"\"\n padding, explicit_paddings = _convert_padding(padding)\n return gen_nn_ops.conv2d_backprop_input(\n input_sizes, filter, out_backprop, strides, padding, use_cudnn_on_gpu,\n explicit_paddings, data_format, dilations, name)\n\n\n@tf_export(v1=[\"nn.conv2d_transpose\"])\ndef conv2d_transpose(\n value,\n filter, # pylint: disable=redefined-builtin\n output_shape,\n strides,\n padding=\"SAME\",\n data_format=\"NHWC\",\n name=None):\n \"\"\"The transpose of `conv2d`.\n\n This operation is sometimes called \"deconvolution\" after [Deconvolutional\n Networks](http://www.matthewzeiler.com/pubs/cvpr2010/cvpr2010.pdf), but is\n actually the transpose (gradient) of `conv2d` rather than an actual\n deconvolution.\n\n Args:\n value: A 4-D `Tensor` of type `float` and shape\n `[batch, height, width, in_channels]` for `NHWC` data format or\n `[batch, in_channels, height, width]` for `NCHW` data format.\n filter: A 4-D `Tensor` with the same type as `value` and shape\n `[height, width, output_channels, in_channels]`. `filter`'s\n `in_channels` dimension must match that of `value`.\n output_shape: A 1-D `Tensor` representing the output shape of the\n deconvolution op.\n strides: A list of ints. The stride of the sliding window for each\n dimension of the input tensor.\n padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.\n See the \"returns\" section of `tf.nn.convolution` for details.\n data_format: A string. 'NHWC' and 'NCHW' are supported.\n name: Optional name for the returned tensor.\n\n Returns:\n A `Tensor` with the same type as `value`.\n\n Raises:\n ValueError: If input/output depth does not match `filter`'s shape, or if\n padding is other than `'VALID'` or `'SAME'`.\n \"\"\"\n with ops.name_scope(name, \"conv2d_transpose\",\n [value, filter, output_shape]) as name:\n if data_format not in (\"NCHW\", \"NHWC\"):\n raise ValueError(\"data_format has to be either NCHW or NHWC.\")\n value = ops.convert_to_tensor(value, name=\"value\")\n filter = ops.convert_to_tensor(filter, name=\"filter\") # pylint: disable=redefined-builtin\n axis = 3 if data_format == \"NHWC\" else 1\n if not value.get_shape().dims[axis].is_compatible_with(\n filter.get_shape()[3]):\n raise ValueError(\"input channels does not match filter's input channels, \"\n \"{} != {}\".format(value.get_shape()[axis],\n filter.get_shape()[3]))\n\n output_shape_ = ops.convert_to_tensor(output_shape, name=\"output_shape\")\n if not output_shape_.get_shape().is_compatible_with(tensor_shape.vector(4)):\n raise ValueError(\"output_shape must have shape (4,), got {}\".format(\n output_shape_.get_shape()))\n\n if isinstance(output_shape, (list, np.ndarray)):\n # output_shape's shape should be == [4] if reached this point.\n if not filter.get_shape().dims[2].is_compatible_with(\n output_shape[axis]):\n raise ValueError(\n \"output_shape does not match filter's output channels, \"\n \"{} != {}\".format(output_shape[axis],\n filter.get_shape()[2]))\n\n if padding != \"VALID\" and padding != \"SAME\":\n raise ValueError(\"padding must be either VALID or SAME:\"\n \" {}\".format(padding))\n\n return gen_nn_ops.conv2d_backprop_input(\n input_sizes=output_shape_,\n filter=filter,\n out_backprop=value,\n strides=strides,\n padding=padding,\n data_format=data_format,\n name=name)\n\n\n# pylint: disable=redefined-builtin\n@tf_export(\"nn.conv2d_transpose\", v1=[])\ndef conv2d_transpose_v2(\n input,\n filters, # pylint: disable=redefined-builtin\n output_shape,\n strides,\n padding=\"SAME\",\n data_format=\"NHWC\",\n name=None):\n return conv2d_transpose(\n input,\n filters,\n output_shape,\n strides,\n padding=padding,\n data_format=data_format,\n name=name)\n# pylint: enable=redefined-builtin\nconv2d_transpose_v2.__doc__ = deprecation.rewrite_argument_docstring(\n deprecation.rewrite_argument_docstring(\n conv2d_transpose.__doc__, \"filter\", \"filters\"),\n \"value\", \"input\")\n\n\n@tf_export(\"nn.atrous_conv2d_transpose\")\ndef atrous_conv2d_transpose(value,\n filters,\n output_shape,\n rate,\n padding,\n name=None):\n \"\"\"The transpose of `atrous_conv2d`.\n\n This operation is sometimes called \"deconvolution\" after [Deconvolutional\n Networks](http://www.matthewzeiler.com/pubs/cvpr2010/cvpr2010.pdf), but is\n actually the transpose (gradient) of `atrous_conv2d` rather than an actual\n deconvolution.\n\n Args:\n value: A 4-D `Tensor` of type `float`. It needs to be in the default `NHWC`\n format. Its shape is `[batch, in_height, in_width, in_channels]`.\n filters: A 4-D `Tensor` with the same type as `value` and shape\n `[filter_height, filter_width, out_channels, in_channels]`. `filters`'\n `in_channels` dimension must match that of `value`. Atrous convolution is\n equivalent to standard convolution with upsampled filters with effective\n height `filter_height + (filter_height - 1) * (rate - 1)` and effective\n width `filter_width + (filter_width - 1) * (rate - 1)`, produced by\n inserting `rate - 1` zeros along consecutive elements across the\n `filters`' spatial dimensions.\n output_shape: A 1-D `Tensor` of shape representing the output shape of the\n deconvolution op.\n rate: A positive int32. The stride with which we sample input values across\n the `height` and `width` dimensions. Equivalently, the rate by which we\n upsample the filter values by inserting zeros across the `height` and\n `width` dimensions. In the literature, the same parameter is sometimes\n called `input stride` or `dilation`.\n padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.\n name: Optional name for the returned tensor.\n\n Returns:\n A `Tensor` with the same type as `value`.\n\n Raises:\n ValueError: If input/output depth does not match `filters`' shape, or if\n padding is other than `'VALID'` or `'SAME'`, or if the `rate` is less\n than one, or if the output_shape is not a tensor with 4 elements.\n \"\"\"\n with ops.name_scope(name, \"atrous_conv2d_transpose\",\n [value, filters, output_shape]) as name:\n value = ops.convert_to_tensor(value, name=\"value\")\n filters = ops.convert_to_tensor(filters, name=\"filters\")\n if not value.get_shape().dims[3].is_compatible_with(filters.get_shape()[3]):\n raise ValueError(\n \"value's input channels does not match filters' input channels, \"\n \"{} != {}\".format(value.get_shape()[3],\n filters.get_shape()[3]))\n if rate < 1:\n raise ValueError(\"rate {} cannot be less than one\".format(rate))\n\n if rate == 1:\n return conv2d_transpose(\n value,\n filters,\n output_shape,\n strides=[1, 1, 1, 1],\n padding=padding,\n data_format=\"NHWC\")\n\n output_shape_ = ops.convert_to_tensor(output_shape, name=\"output_shape\")\n if not output_shape_.get_shape().is_compatible_with(tensor_shape.vector(4)):\n raise ValueError(\"output_shape must have shape (4,), got {}\".format(\n output_shape_.get_shape()))\n\n if isinstance(output_shape, (list, np.ndarray)):\n # output_shape's shape should be == [4] if reached this point.\n if not filters.get_shape().dims[2].is_compatible_with(output_shape[3]):\n raise ValueError(\n \"output_shape does not match filter's output channels, \"\n \"{} != {}\".format(output_shape[3],\n filters.get_shape()[2]))\n\n # We have two padding contributions. The first is used for converting \"SAME\"\n # to \"VALID\". The second is required so that the height and width of the\n # zero-padded value tensor are multiples of rate.\n\n # Padding required to reduce to \"VALID\" convolution\n if padding == \"SAME\":\n # Handle filters whose shape is unknown during graph creation.\n if filters.get_shape().is_fully_defined():\n filter_shape = filters.get_shape().as_list()\n else:\n filter_shape = array_ops.shape(filters)\n filter_height, filter_width = filter_shape[0], filter_shape[1]\n\n # Spatial dimensions of the filters and the upsampled filters in which we\n # introduce (rate - 1) zeros between consecutive filter values.\n filter_height_up = filter_height + (filter_height - 1) * (rate - 1)\n filter_width_up = filter_width + (filter_width - 1) * (rate - 1)\n\n pad_height = filter_height_up - 1\n pad_width = filter_width_up - 1\n\n # When pad_height (pad_width) is odd, we pad more to bottom (right),\n # following the same convention as conv2d().\n pad_top = pad_height // 2\n pad_bottom = pad_height - pad_top\n pad_left = pad_width // 2\n pad_right = pad_width - pad_left\n elif padding == \"VALID\":\n pad_top = 0\n pad_bottom = 0\n pad_left = 0\n pad_right = 0\n else:\n raise ValueError(\"padding must be either VALID or SAME:\"\n \" {}\".format(padding))\n\n in_height = output_shape[1] + pad_top + pad_bottom\n in_width = output_shape[2] + pad_left + pad_right\n\n # More padding so that rate divides the height and width of the input.\n pad_bottom_extra = (rate - in_height % rate) % rate\n pad_right_extra = (rate - in_width % rate) % rate\n\n # The paddings argument to space_to_batch is just the extra padding\n # component.\n space_to_batch_pad = [[0, pad_bottom_extra], [0, pad_right_extra]]\n\n value = array_ops.space_to_batch(\n input=value, paddings=space_to_batch_pad, block_size=rate)\n\n input_sizes = [\n rate * rate * output_shape[0], (in_height + pad_bottom_extra) // rate,\n (in_width + pad_right_extra) // rate, output_shape[3]\n ]\n\n value = gen_nn_ops.conv2d_backprop_input(\n input_sizes=input_sizes,\n filter=filters,\n out_backprop=value,\n strides=[1, 1, 1, 1],\n padding=\"VALID\",\n data_format=\"NHWC\")\n\n # The crops argument to batch_to_space includes both padding components.\n batch_to_space_crop = [[pad_top, pad_bottom + pad_bottom_extra],\n [pad_left, pad_right + pad_right_extra]]\n\n return array_ops.batch_to_space(\n input=value, crops=batch_to_space_crop, block_size=rate)\n\n\n@tf_export(\"nn.conv3d\", v1=[])\ndef conv3d_v2(input, # pylint: disable=redefined-builtin,missing-docstring\n filters,\n strides,\n padding,\n data_format=\"NDHWC\",\n dilations=None,\n name=None):\n if dilations is None:\n dilations = [1, 1, 1, 1, 1]\n return gen_nn_ops.conv3d(input, # pylint: disable=redefined-builtin\n filters,\n strides,\n padding,\n data_format=data_format,\n dilations=dilations,\n name=name)\ntf_export(v1=[\"nn.conv3d\"])(gen_nn_ops.conv3d)\nconv3d_v2.__doc__ = deprecation.rewrite_argument_docstring(\n gen_nn_ops.conv3d.__doc__, \"filter\", \"filters\")\n\n\n@tf_export(v1=[\"nn.conv3d_transpose\"])\ndef conv3d_transpose(\n value,\n filter, # pylint: disable=redefined-builtin\n output_shape,\n strides,\n padding=\"SAME\",\n data_format=\"NDHWC\",\n name=None):\n \"\"\"The transpose of `conv3d`.\n\n This operation is sometimes called \"deconvolution\" after [Deconvolutional\n Networks](http://www.matthewzeiler.com/pubs/cvpr2010/cvpr2010.pdf), but is\n actually the transpose (gradient) of `conv3d` rather than an actual\n deconvolution.\n\n Args:\n value: A 5-D `Tensor` of type `float` and shape\n `[batch, depth, height, width, in_channels]`.\n filter: A 5-D `Tensor` with the same type as `value` and shape\n `[depth, height, width, output_channels, in_channels]`. `filter`'s\n `in_channels` dimension must match that of `value`.\n output_shape: A 1-D `Tensor` representing the output shape of the\n deconvolution op.\n strides: A list of ints. The stride of the sliding window for each\n dimension of the input tensor.\n padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.\n See the \"returns\" section of `tf.nn.convolution` for details.\n data_format: A string, either `'NDHWC'` or `'NCDHW`' specifying the layout\n of the input and output tensors. Defaults to `'NDHWC'`.\n name: Optional name for the returned tensor.\n\n Returns:\n A `Tensor` with the same type as `value`.\n\n Raises:\n ValueError: If input/output depth does not match `filter`'s shape, or if\n padding is other than `'VALID'` or `'SAME'`.\n \"\"\"\n with ops.name_scope(name, \"conv3d_transpose\",\n [value, filter, output_shape]) as name:\n value = ops.convert_to_tensor(value, name=\"value\")\n filter = ops.convert_to_tensor(filter, name=\"filter\") # pylint: disable=redefined-builtin\n axis = 1 if data_format == \"NCDHW\" else 4\n if not value.get_shape().dims[axis].is_compatible_with(\n filter.get_shape()[4]):\n raise ValueError(\"input channels does not match filter's input channels, \"\n \"{} != {}\".format(value.get_shape()[axis],\n filter.get_shape()[4]))\n\n output_shape_ = ops.convert_to_tensor(output_shape, name=\"output_shape\")\n if not output_shape_.get_shape().is_compatible_with(tensor_shape.vector(5)):\n raise ValueError(\"output_shape must have shape (5,), got {}\".format(\n output_shape_.get_shape()))\n\n if isinstance(output_shape, (list, np.ndarray)):\n # output_shape's shape should be == [5] if reached this point.\n if not filter.get_shape().dims[3].is_compatible_with(\n output_shape[axis]):\n raise ValueError(\n \"output_shape does not match filter's output channels, \"\n \"{} != {}\".format(output_shape[axis],\n filter.get_shape()[3]))\n\n if padding != \"VALID\" and padding != \"SAME\":\n raise ValueError(\"padding must be either VALID or SAME:\"\n \" {}\".format(padding))\n\n return gen_nn_ops.conv3d_backprop_input_v2(\n input_sizes=output_shape_,\n filter=filter,\n out_backprop=value,\n strides=strides,\n padding=padding,\n data_format=data_format,\n name=name)\n\n\n# pylint: disable=redefined-builtin\n@tf_export(\"nn.conv3d_transpose\", v1=[])\ndef conv3d_transpose_v2(\n input,\n filters,\n output_shape,\n strides,\n padding=\"SAME\",\n data_format=\"NDHWC\",\n name=None):\n return conv3d_transpose(\n input,\n filters,\n output_shape,\n strides,\n padding=padding,\n data_format=data_format,\n name=name)\n# pylint: enable=redefined-builtin\nconv3d_transpose_v2.__doc__ = deprecation.rewrite_argument_docstring(\n deprecation.rewrite_argument_docstring(\n conv3d_transpose.__doc__, \"filter\", \"filters\"),\n \"value\", \"input\")\n\n\n@tf_export(\"nn.bias_add\")\ndef bias_add(value, bias, data_format=None, name=None):\n \"\"\"Adds `bias` to `value`.\n\n This is (mostly) a special case of `tf.add` where `bias` is restricted to 1-D.\n Broadcasting is supported, so `value` may have any number of dimensions.\n Unlike `tf.add`, the type of `bias` is allowed to differ from `value` in the\n case where both types are quantized.\n\n Args:\n value: A `Tensor` with type `float`, `double`, `int64`, `int32`, `uint8`,\n `int16`, `int8`, `complex64`, or `complex128`.\n bias: A 1-D `Tensor` with size matching the last dimension of `value`.\n Must be the same type as `value` unless `value` is a quantized type,\n in which case a different quantized type may be used.\n data_format: A string. 'NHWC' and 'NCHW' are supported.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` with the same type as `value`.\n \"\"\"\n with ops.name_scope(name, \"BiasAdd\", [value, bias]) as name:\n if not context.executing_eagerly():\n value = ops.convert_to_tensor(value, name=\"input\")\n bias = ops.convert_to_tensor(bias, dtype=value.dtype, name=\"bias\")\n return gen_nn_ops.bias_add(value, bias, data_format=data_format, name=name)\n\n\ndef bias_add_v1(value, bias, name=None):\n \"\"\"Adds `bias` to `value`.\n\n This is a deprecated version of bias_add and will soon to be removed.\n\n This is (mostly) a special case of `tf.add` where `bias` is restricted to 1-D.\n Broadcasting is supported, so `value` may have any number of dimensions.\n Unlike `tf.add`, the type of `bias` is allowed to differ from `value` in the\n case where both types are quantized.\n\n Args:\n value: A `Tensor` with type `float`, `double`, `int64`, `int32`, `uint8`,\n `int16`, `int8`, `complex64`, or `complex128`.\n bias: A 1-D `Tensor` with size matching the last dimension of `value`.\n Must be the same type as `value` unless `value` is a quantized type,\n in which case a different quantized type may be used.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` with the same type as `value`.\n \"\"\"\n with ops.name_scope(name, \"BiasAddV1\", [value, bias]) as name:\n value = ops.convert_to_tensor(value, name=\"input\")\n bias = ops.convert_to_tensor(bias, dtype=value.dtype, name=\"bias\")\n return gen_nn_ops.bias_add_v1(value, bias, name=name)\n\n\n@tf_export(v1=[\"nn.crelu\"])\ndef crelu(features, name=None, axis=-1):\n \"\"\"Computes Concatenated ReLU.\n\n Concatenates a ReLU which selects only the positive part of the activation\n with a ReLU which selects only the *negative* part of the activation.\n Note that as a result this non-linearity doubles the depth of the activations.\n Source: [Understanding and Improving Convolutional Neural Networks via\n Concatenated Rectified Linear Units. W. Shang, et\n al.](https://arxiv.org/abs/1603.05201)\n\n Args:\n features: A `Tensor` with type `float`, `double`, `int32`, `int64`, `uint8`,\n `int16`, or `int8`.\n name: A name for the operation (optional).\n axis: The axis that the output values are concatenated along. Default is -1.\n\n Returns:\n A `Tensor` with the same type as `features`.\n \"\"\"\n with ops.name_scope(name, \"CRelu\", [features]) as name:\n features = ops.convert_to_tensor(features, name=\"features\")\n c = array_ops.concat([features, -features], axis, name=name)\n return gen_nn_ops.relu(c)\n\n\n@tf_export(\"nn.crelu\", v1=[])\ndef crelu_v2(features, axis=-1, name=None):\n return crelu(features, name=name, axis=axis)\ncrelu_v2.__doc__ = crelu.__doc__\n\n\n@tf_export(\"nn.relu6\")\ndef relu6(features, name=None):\n \"\"\"Computes Rectified Linear 6: `min(max(features, 0), 6)`.\n\n Source: [Convolutional Deep Belief Networks on CIFAR-10. A.\n Krizhevsky](http://www.cs.utoronto.ca/~kriz/conv-cifar10-aug2010.pdf)\n\n Args:\n features: A `Tensor` with type `float`, `double`, `int32`, `int64`, `uint8`,\n `int16`, or `int8`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` with the same type as `features`.\n \"\"\"\n with ops.name_scope(name, \"Relu6\", [features]) as name:\n features = ops.convert_to_tensor(features, name=\"features\")\n return gen_nn_ops.relu6(features, name=name)\n\n\n@tf_export(\"nn.leaky_relu\")\ndef leaky_relu(features, alpha=0.2, name=None):\n \"\"\"Compute the Leaky ReLU activation function.\n\n \"Rectifier Nonlinearities Improve Neural Network Acoustic Models\"\n AL Maas, AY Hannun, AY Ng - Proc. ICML, 2013\n https://ai.stanford.edu/~amaas/papers/relu_hybrid_icml2013_final.pdf\n\n Args:\n features: A `Tensor` representing preactivation values. Must be one of\n the following types: `float16`, `float32`, `float64`, `int32`, `int64`.\n alpha: Slope of the activation function at x < 0.\n name: A name for the operation (optional).\n\n Returns:\n The activation value.\n \"\"\"\n with ops.name_scope(name, \"LeakyRelu\", [features, alpha]) as name:\n features = ops.convert_to_tensor(features, name=\"features\")\n if features.dtype.is_integer:\n features = math_ops.to_float(features)\n if compat.forward_compatible(2018, 11, 1):\n if isinstance(alpha, np.ndarray):\n alpha = np.asscalar(alpha)\n return gen_nn_ops.leaky_relu(features, alpha=alpha, name=name)\n alpha = ops.convert_to_tensor(alpha, dtype=features.dtype, name=\"alpha\")\n return math_ops.maximum(alpha * features, features, name=name)\n\n\ndef _flatten_outer_dims(logits):\n \"\"\"Flattens logits' outer dimensions and keep its last dimension.\"\"\"\n rank = array_ops.rank(logits)\n last_dim_size = array_ops.slice(\n array_ops.shape(logits), [math_ops.subtract(rank, 1)], [1])\n output = array_ops.reshape(logits, array_ops.concat([[-1], last_dim_size], 0))\n\n # Set output shape if known.\n if not context.executing_eagerly():\n shape = logits.get_shape()\n if shape is not None and shape.dims is not None:\n shape = shape.as_list()\n product = 1\n product_valid = True\n for d in shape[:-1]:\n if d is None:\n product_valid = False\n break\n else:\n product *= d\n if product_valid:\n output_shape = [product, shape[-1]]\n output.set_shape(output_shape)\n\n return output\n\n\ndef _softmax(logits, compute_op, dim=-1, name=None):\n \"\"\"Helper function for softmax and log_softmax.\n\n It reshapes and transposes the input logits into a 2-D Tensor and then invokes\n the tf.nn._softmax or tf.nn._log_softmax function. The output would be\n transposed and reshaped back.\n\n Args:\n logits: A non-empty `Tensor`. Must be one of the following types: `half`,\n `float32`, `float64`.\n compute_op: Either gen_nn_ops.softmax or gen_nn_ops.log_softmax\n dim: The dimension softmax would be performed on. The default is -1 which\n indicates the last dimension.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `logits`. Same shape as `logits`.\n Raises:\n InvalidArgumentError: if `logits` is empty or `dim` is beyond the last\n dimension of `logits`.\n \"\"\"\n\n def _swap_axis(logits, dim_index, last_index, name=None):\n \"\"\"Swaps logits's dim_index and last_index.\"\"\"\n return array_ops.transpose(\n logits,\n array_ops.concat([\n math_ops.range(dim_index), [last_index],\n math_ops.range(dim_index + 1, last_index), [dim_index]\n ], 0),\n name=name)\n\n logits = ops.convert_to_tensor(logits)\n\n # We need its original shape for shape inference.\n shape = logits.get_shape()\n is_last_dim = (dim is -1) or (dim == shape.ndims - 1)\n\n if is_last_dim:\n return compute_op(logits, name=name)\n\n dim_val = dim\n if isinstance(dim, ops.Tensor):\n dim_val = tensor_util.constant_value(dim)\n if dim_val is not None and (dim_val < -shape.ndims or dim_val >= shape.ndims):\n raise errors_impl.InvalidArgumentError(\n None, None,\n \"Dimension (%d) must be in the range [%d, %d) where %d is the number of\"\n \" dimensions in the input.\" % (dim_val, -shape.ndims, shape.ndims,\n shape.ndims))\n\n # If dim is not the last dimension, we have to do a transpose so that we can\n # still perform softmax on its last dimension.\n\n # In case dim is negative (and is not last dimension -1), add shape.ndims\n ndims = array_ops.rank(logits)\n if not isinstance(dim, ops.Tensor):\n if dim < 0:\n dim += ndims\n else:\n dim = array_ops.where(math_ops.less(dim, 0), dim + ndims, dim)\n\n # Swap logits' dimension of dim and its last dimension.\n input_rank = array_ops.rank(logits)\n dim_axis = dim % shape.ndims\n logits = _swap_axis(logits, dim_axis, math_ops.subtract(input_rank, 1))\n\n # Do the actual softmax on its last dimension.\n output = compute_op(logits)\n\n output = _swap_axis(\n output, dim_axis, math_ops.subtract(input_rank, 1), name=name)\n\n # Make shape inference work since transpose may erase its static shape.\n output.set_shape(shape)\n\n return output\n\n\n@tf_export(v1=[\"nn.softmax\", \"math.softmax\"])\[email protected]_args(None, \"dim is deprecated, use axis instead\", \"dim\")\ndef softmax(logits, axis=None, name=None, dim=None):\n \"\"\"Computes softmax activations.\n\n This function performs the equivalent of\n\n softmax = tf.exp(logits) / tf.reduce_sum(tf.exp(logits), axis)\n\n Args:\n logits: A non-empty `Tensor`. Must be one of the following types: `half`,\n `float32`, `float64`.\n axis: The dimension softmax would be performed on. The default is -1 which\n indicates the last dimension.\n name: A name for the operation (optional).\n dim: Deprecated alias for `axis`.\n\n Returns:\n A `Tensor`. Has the same type and shape as `logits`.\n\n Raises:\n InvalidArgumentError: if `logits` is empty or `axis` is beyond the last\n dimension of `logits`.\n \"\"\"\n axis = deprecation.deprecated_argument_lookup(\"axis\", axis, \"dim\", dim)\n if axis is None:\n axis = -1\n return _softmax(logits, gen_nn_ops.softmax, axis, name)\n\n\n@tf_export(\"nn.softmax\", \"math.softmax\", v1=[])\ndef softmax_v2(logits, axis=None, name=None):\n \"\"\"Computes softmax activations.\n\n This function performs the equivalent of\n\n softmax = tf.exp(logits) / tf.reduce_sum(tf.exp(logits), axis)\n\n Args:\n logits: A non-empty `Tensor`. Must be one of the following types: `half`,\n `float32`, `float64`.\n axis: The dimension softmax would be performed on. The default is -1 which\n indicates the last dimension.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type and shape as `logits`.\n\n Raises:\n InvalidArgumentError: if `logits` is empty or `axis` is beyond the last\n dimension of `logits`.\n \"\"\"\n if axis is None:\n axis = -1\n return _softmax(logits, gen_nn_ops.softmax, axis, name)\n\n\n@tf_export(v1=[\"nn.log_softmax\", \"math.log_softmax\"])\[email protected]_args(None, \"dim is deprecated, use axis instead\", \"dim\")\ndef log_softmax(logits, axis=None, name=None, dim=None):\n \"\"\"Computes log softmax activations.\n\n For each batch `i` and class `j` we have\n\n logsoftmax = logits - log(reduce_sum(exp(logits), axis))\n\n Args:\n logits: A non-empty `Tensor`. Must be one of the following types: `half`,\n `float32`, `float64`.\n axis: The dimension softmax would be performed on. The default is -1 which\n indicates the last dimension.\n name: A name for the operation (optional).\n dim: Deprecated alias for `axis`.\n\n Returns:\n A `Tensor`. Has the same type as `logits`. Same shape as `logits`.\n\n Raises:\n InvalidArgumentError: if `logits` is empty or `axis` is beyond the last\n dimension of `logits`.\n \"\"\"\n axis = deprecation.deprecated_argument_lookup(\"axis\", axis, \"dim\", dim)\n if axis is None:\n axis = -1\n return _softmax(logits, gen_nn_ops.log_softmax, axis, name)\n\n\n@tf_export(\"nn.log_softmax\", \"math.log_softmax\", v1=[])\ndef log_softmax_v2(logits, axis=None, name=None):\n \"\"\"Computes log softmax activations.\n\n For each batch `i` and class `j` we have\n\n logsoftmax = logits - log(reduce_sum(exp(logits), axis))\n\n Args:\n logits: A non-empty `Tensor`. Must be one of the following types: `half`,\n `float32`, `float64`.\n axis: The dimension softmax would be performed on. The default is -1 which\n indicates the last dimension.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `logits`. Same shape as `logits`.\n\n Raises:\n InvalidArgumentError: if `logits` is empty or `axis` is beyond the last\n dimension of `logits`.\n \"\"\"\n if axis is None:\n axis = -1\n return _softmax(logits, gen_nn_ops.log_softmax, axis, name)\n\n\ndef _ensure_xent_args(name, sentinel, labels, logits):\n # Make sure that all arguments were passed as named arguments.\n if sentinel is not None:\n raise ValueError(\"Only call `%s` with \"\n \"named arguments (labels=..., logits=..., ...)\" % name)\n if labels is None or logits is None:\n raise ValueError(\"Both labels and logits must be provided.\")\n\n\n@tf_export(\"nn.softmax_cross_entropy_with_logits\", v1=[])\ndef softmax_cross_entropy_with_logits_v2(labels, logits, axis=-1, name=None):\n \"\"\"Computes softmax cross entropy between `logits` and `labels`.\n\n Measures the probability error in discrete classification tasks in which the\n classes are mutually exclusive (each entry is in exactly one class). For\n example, each CIFAR-10 image is labeled with one and only one label: an image\n can be a dog or a truck, but not both.\n\n **NOTE:** While the classes are mutually exclusive, their probabilities\n need not be. All that is required is that each row of `labels` is\n a valid probability distribution. If they are not, the computation of the\n gradient will be incorrect.\n\n If using exclusive `labels` (wherein one and only\n one class is true at a time), see `sparse_softmax_cross_entropy_with_logits`.\n\n **WARNING:** This op expects unscaled logits, since it performs a `softmax`\n on `logits` internally for efficiency. Do not call this op with the\n output of `softmax`, as it will produce incorrect results.\n\n A common use case is to have logits and labels of shape\n `[batch_size, num_classes]`, but higher dimensions are supported, with\n the `axis` argument specifying the class dimension.\n\n `logits` and `labels` must have the same dtype (either `float16`, `float32`,\n or `float64`).\n\n Backpropagation will happen into both `logits` and `labels`. To disallow\n backpropagation into `labels`, pass label tensors through `tf.stop_gradient`\n before feeding it to this function.\n\n **Note that to avoid confusion, it is required to pass only named arguments to\n this function.**\n\n Args:\n labels: Each vector along the class dimension should hold a valid\n probability distribution e.g. for the case in which labels are of shape\n `[batch_size, num_classes]`, each row of `labels[i]` must be a valid\n probability distribution.\n logits: Unscaled log probabilities.\n axis: The class dimension. Defaulted to -1 which is the last dimension.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` that contains the softmax cross entropy loss. Its type is the\n same as `logits` and its shape is the same as `labels` except that it does\n not have the last dimension of `labels`.\n \"\"\"\n return softmax_cross_entropy_with_logits_v2_helper(\n labels=labels, logits=logits, axis=axis, name=name)\n\n\n@tf_export(v1=[\"nn.softmax_cross_entropy_with_logits_v2\"])\n@deprecated_args(None, \"dim is deprecated, use axis instead\", \"dim\")\ndef softmax_cross_entropy_with_logits_v2_helper(\n labels, logits, axis=None, name=None, dim=None):\n \"\"\"Computes softmax cross entropy between `logits` and `labels`.\n\n Measures the probability error in discrete classification tasks in which the\n classes are mutually exclusive (each entry is in exactly one class). For\n example, each CIFAR-10 image is labeled with one and only one label: an image\n can be a dog or a truck, but not both.\n\n **NOTE:** While the classes are mutually exclusive, their probabilities\n need not be. All that is required is that each row of `labels` is\n a valid probability distribution. If they are not, the computation of the\n gradient will be incorrect.\n\n If using exclusive `labels` (wherein one and only\n one class is true at a time), see `sparse_softmax_cross_entropy_with_logits`.\n\n **WARNING:** This op expects unscaled logits, since it performs a `softmax`\n on `logits` internally for efficiency. Do not call this op with the\n output of `softmax`, as it will produce incorrect results.\n\n A common use case is to have logits and labels of shape\n `[batch_size, num_classes]`, but higher dimensions are supported, with\n the `axis` argument specifying the class dimension.\n\n `logits` and `labels` must have the same dtype (either `float16`, `float32`,\n or `float64`).\n\n Backpropagation will happen into both `logits` and `labels`. To disallow\n backpropagation into `labels`, pass label tensors through `tf.stop_gradient`\n before feeding it to this function.\n\n **Note that to avoid confusion, it is required to pass only named arguments to\n this function.**\n\n Args:\n labels: Each vector along the class dimension should hold a valid\n probability distribution e.g. for the case in which labels are of shape\n `[batch_size, num_classes]`, each row of `labels[i]` must be a valid\n probability distribution.\n logits: Unscaled log probabilities.\n axis: The class dimension. Defaulted to -1 which is the last dimension.\n name: A name for the operation (optional).\n dim: Deprecated alias for axis.\n\n Returns:\n A `Tensor` that contains the softmax cross entropy loss. Its type is the\n same as `logits` and its shape is the same as `labels` except that it does\n not have the last dimension of `labels`.\n \"\"\"\n # TODO(pcmurray) Raise an error when the labels do not sum to 1. Note: This\n # could break users who call this with bad labels, but disregard the bad\n # results.\n axis = deprecated_argument_lookup(\"axis\", axis, \"dim\", dim)\n del dim\n if axis is None:\n axis = -1\n\n with ops.name_scope(name, \"softmax_cross_entropy_with_logits\",\n [logits, labels]) as name:\n logits = ops.convert_to_tensor(logits, name=\"logits\")\n labels = ops.convert_to_tensor(labels, name=\"labels\")\n convert_to_float32 = (\n logits.dtype == dtypes.float16 or logits.dtype == dtypes.bfloat16)\n precise_logits = math_ops.cast(\n logits, dtypes.float32) if convert_to_float32 else logits\n # labels and logits must be of the same type\n labels = math_ops.cast(labels, precise_logits.dtype)\n input_rank = array_ops.rank(precise_logits)\n # For shape inference.\n shape = logits.get_shape()\n\n # Move the dim to the end if dim is not the last dimension.\n if axis != -1:\n\n def _move_dim_to_end(tensor, dim_index, rank):\n return array_ops.transpose(\n tensor,\n array_ops.concat([\n math_ops.range(dim_index),\n math_ops.range(dim_index + 1, rank), [dim_index]\n ], 0))\n\n precise_logits = _move_dim_to_end(precise_logits, axis, input_rank)\n labels = _move_dim_to_end(labels, axis, input_rank)\n\n input_shape = array_ops.shape(precise_logits)\n\n # Make precise_logits and labels into matrices.\n precise_logits = _flatten_outer_dims(precise_logits)\n labels = _flatten_outer_dims(labels)\n\n # Do the actual op computation.\n # The second output tensor contains the gradients. We use it in\n # _CrossEntropyGrad() in nn_grad but not here.\n cost, unused_backprop = gen_nn_ops.softmax_cross_entropy_with_logits(\n precise_logits, labels, name=name)\n\n # The output cost shape should be the input minus axis.\n output_shape = array_ops.slice(input_shape, [0],\n [math_ops.subtract(input_rank, 1)])\n cost = array_ops.reshape(cost, output_shape)\n\n # Make shape inference work since reshape and transpose may erase its static\n # shape.\n if not context.executing_eagerly(\n ) and shape is not None and shape.dims is not None:\n shape = shape.as_list()\n del shape[axis]\n cost.set_shape(shape)\n\n if convert_to_float32:\n return math_ops.cast(cost, logits.dtype)\n else:\n return cost\n\n\n_XENT_DEPRECATION = \"\"\"\nFuture major versions of TensorFlow will allow gradients to flow\ninto the labels input on backprop by default.\n\nSee `tf.nn.softmax_cross_entropy_with_logits_v2`.\n\"\"\"\n\n\n@tf_export(v1=[\"nn.softmax_cross_entropy_with_logits\"])\[email protected](date=None, instructions=_XENT_DEPRECATION)\ndef softmax_cross_entropy_with_logits(\n _sentinel=None, # pylint: disable=invalid-name\n labels=None,\n logits=None,\n dim=-1,\n name=None):\n \"\"\"Computes softmax cross entropy between `logits` and `labels`.\n\n Measures the probability error in discrete classification tasks in which the\n classes are mutually exclusive (each entry is in exactly one class). For\n example, each CIFAR-10 image is labeled with one and only one label: an image\n can be a dog or a truck, but not both.\n\n **NOTE:** While the classes are mutually exclusive, their probabilities\n need not be. All that is required is that each row of `labels` is\n a valid probability distribution. If they are not, the computation of the\n gradient will be incorrect.\n\n If using exclusive `labels` (wherein one and only\n one class is true at a time), see `sparse_softmax_cross_entropy_with_logits`.\n\n **WARNING:** This op expects unscaled logits, since it performs a `softmax`\n on `logits` internally for efficiency. Do not call this op with the\n output of `softmax`, as it will produce incorrect results.\n\n A common use case is to have logits and labels of shape\n `[batch_size, num_classes]`, but higher dimensions are supported, with\n the `dim` argument specifying the class dimension.\n\n Backpropagation will happen only into `logits`. To calculate a cross entropy\n loss that allows backpropagation into both `logits` and `labels`, see\n `tf.nn.softmax_cross_entropy_with_logits_v2`.\n\n **Note that to avoid confusion, it is required to pass only named arguments to\n this function.**\n\n Args:\n _sentinel: Used to prevent positional parameters. Internal, do not use.\n labels: Each vector along the class dimension should hold a valid\n probability distribution e.g. for the case in which labels are of shape\n `[batch_size, num_classes]`, each row of `labels[i]` must be a valid\n probability distribution.\n logits: Unscaled log probabilities.\n dim: The class dimension. Defaulted to -1 which is the last dimension.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` that contains the softmax cross entropy loss. Its type is the\n same as `logits` and its shape is the same as `labels` except that it does\n not have the last dimension of `labels`.\n \"\"\"\n _ensure_xent_args(\"softmax_cross_entropy_with_logits\", _sentinel, labels,\n logits)\n\n with ops.name_scope(name, \"softmax_cross_entropy_with_logits_sg\",\n [logits, labels]) as name:\n labels = array_ops.stop_gradient(labels, name=\"labels_stop_gradient\")\n\n return softmax_cross_entropy_with_logits_v2(\n labels=labels, logits=logits, axis=dim, name=name)\n\n\n@tf_export(\"nn.sparse_softmax_cross_entropy_with_logits\")\ndef sparse_softmax_cross_entropy_with_logits(\n _sentinel=None, # pylint: disable=invalid-name\n labels=None,\n logits=None,\n name=None):\n \"\"\"Computes sparse softmax cross entropy between `logits` and `labels`.\n\n Measures the probability error in discrete classification tasks in which the\n classes are mutually exclusive (each entry is in exactly one class). For\n example, each CIFAR-10 image is labeled with one and only one label: an image\n can be a dog or a truck, but not both.\n\n **NOTE:** For this operation, the probability of a given label is considered\n exclusive. That is, soft classes are not allowed, and the `labels` vector\n must provide a single specific index for the true class for each row of\n `logits` (each minibatch entry). For soft softmax classification with\n a probability distribution for each entry, see\n `softmax_cross_entropy_with_logits_v2`.\n\n **WARNING:** This op expects unscaled logits, since it performs a `softmax`\n on `logits` internally for efficiency. Do not call this op with the\n output of `softmax`, as it will produce incorrect results.\n\n A common use case is to have logits of shape\n `[batch_size, num_classes]` and have labels of shape\n `[batch_size]`, but higher dimensions are supported, in which\n case the `dim`-th dimension is assumed to be of size `num_classes`.\n `logits` must have the dtype of `float16`, `float32`, or `float64`, and\n `labels` must have the dtype of `int32` or `int64`.\n\n **Note that to avoid confusion, it is required to pass only named arguments to\n this function.**\n\n Args:\n _sentinel: Used to prevent positional parameters. Internal, do not use.\n labels: `Tensor` of shape `[d_0, d_1, ..., d_{r-1}]` (where `r` is rank of\n `labels` and result) and dtype `int32` or `int64`. Each entry in `labels`\n must be an index in `[0, num_classes)`. Other values will raise an\n exception when this op is run on CPU, and return `NaN` for corresponding\n loss and gradient rows on GPU.\n logits: Unscaled log probabilities of shape\n `[d_0, d_1, ..., d_{r-1}, num_classes]` and dtype `float16`, `float32`, or\n `float64`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of the same shape as `labels` and of the same type as `logits`\n with the softmax cross entropy loss.\n\n Raises:\n ValueError: If logits are scalars (need to have rank >= 1) or if the rank\n of the labels is not equal to the rank of the logits minus one.\n \"\"\"\n _ensure_xent_args(\"sparse_softmax_cross_entropy_with_logits\", _sentinel,\n labels, logits)\n\n # TODO(pcmurray) Raise an error when the label is not an index in\n # [0, num_classes). Note: This could break users who call this with bad\n # labels, but disregard the bad results.\n\n # Reshape logits and labels to rank 2.\n with ops.name_scope(name, \"SparseSoftmaxCrossEntropyWithLogits\",\n [labels, logits]):\n labels = ops.convert_to_tensor(labels)\n logits = ops.convert_to_tensor(logits)\n precise_logits = math_ops.cast(logits, dtypes.float32) if (dtypes.as_dtype(\n logits.dtype) == dtypes.float16) else logits\n\n # Store label shape for result later.\n labels_static_shape = labels.get_shape()\n labels_shape = array_ops.shape(labels)\n static_shapes_fully_defined = (\n labels_static_shape.is_fully_defined() and\n logits.get_shape()[:-1].is_fully_defined())\n if logits.get_shape().ndims is not None and logits.get_shape().ndims == 0:\n raise ValueError(\n \"Logits cannot be scalars - received shape %s.\" % logits.get_shape())\n if logits.get_shape().ndims is not None and (\n labels_static_shape.ndims is not None and\n labels_static_shape.ndims != logits.get_shape().ndims - 1):\n raise ValueError(\"Rank mismatch: Rank of labels (received %s) should \"\n \"equal rank of logits minus 1 (received %s).\" %\n (labels_static_shape.ndims, logits.get_shape().ndims))\n if (static_shapes_fully_defined and\n labels_static_shape != logits.get_shape()[:-1]):\n raise ValueError(\"Shape mismatch: The shape of labels (received %s) \"\n \"should equal the shape of logits except for the last \"\n \"dimension (received %s).\" % (labels_static_shape,\n logits.get_shape()))\n # Check if no reshapes are required.\n if logits.get_shape().ndims == 2:\n cost, _ = gen_nn_ops.sparse_softmax_cross_entropy_with_logits(\n precise_logits, labels, name=name)\n if logits.dtype == dtypes.float16:\n return math_ops.cast(cost, dtypes.float16)\n else:\n return cost\n\n # Perform a check of the dynamic shapes if the static shapes are not fully\n # defined.\n shape_checks = []\n if not static_shapes_fully_defined:\n shape_checks.append(\n check_ops.assert_equal(\n array_ops.shape(labels),\n array_ops.shape(logits)[:-1]))\n with ops.control_dependencies(shape_checks):\n # Reshape logits to 2 dim, labels to 1 dim.\n num_classes = array_ops.shape(logits)[array_ops.rank(logits) - 1]\n precise_logits = array_ops.reshape(precise_logits, [-1, num_classes])\n labels = array_ops.reshape(labels, [-1])\n # The second output tensor contains the gradients. We use it in\n # _CrossEntropyGrad() in nn_grad but not here.\n cost, _ = gen_nn_ops.sparse_softmax_cross_entropy_with_logits(\n precise_logits, labels, name=name)\n cost = array_ops.reshape(cost, labels_shape)\n cost.set_shape(labels_static_shape)\n if logits.dtype == dtypes.float16:\n return math_ops.cast(cost, dtypes.float16)\n else:\n return cost\n\n\n@tf_export(\"nn.avg_pool\")\ndef avg_pool(value, ksize, strides, padding, data_format=\"NHWC\", name=None):\n \"\"\"Performs the average pooling on the input.\n\n Each entry in `output` is the mean of the corresponding size `ksize`\n window in `value`.\n\n Args:\n value: A 4-D `Tensor` of shape `[batch, height, width, channels]` and type\n `float32`, `float64`, `qint8`, `quint8`, or `qint32`.\n ksize: A list or tuple of 4 ints. The size of the window for each dimension\n of the input tensor.\n strides: A list or tuple of 4 ints. The stride of the sliding window for\n each dimension of the input tensor.\n padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.\n See the \"returns\" section of `tf.nn.convolution` for details.\n data_format: A string. 'NHWC' and 'NCHW' are supported.\n name: Optional name for the operation.\n\n Returns:\n A `Tensor` with the same type as `value`. The average pooled output tensor.\n \"\"\"\n with ops.name_scope(name, \"AvgPool\", [value]) as name:\n value = ops.convert_to_tensor(value, name=\"input\")\n return gen_nn_ops.avg_pool(\n value,\n ksize=ksize,\n strides=strides,\n padding=padding,\n data_format=data_format,\n name=name)\n\n\n@tf_export(\"nn.max_pool\")\ndef max_pool(value, ksize, strides, padding, data_format=\"NHWC\", name=None):\n \"\"\"Performs the max pooling on the input.\n\n Args:\n value: A 4-D `Tensor` of the format specified by `data_format`.\n ksize: A list or tuple of 4 ints. The size of the window for each dimension\n of the input tensor.\n strides: A list or tuple of 4 ints. The stride of the sliding window for\n each dimension of the input tensor.\n padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.\n See the \"returns\" section of `tf.nn.convolution` for details.\n data_format: A string. 'NHWC', 'NCHW' and 'NCHW_VECT_C' are supported.\n name: Optional name for the operation.\n\n Returns:\n A `Tensor` of format specified by `data_format`.\n The max pooled output tensor.\n \"\"\"\n with ops.name_scope(name, \"MaxPool\", [value]) as name:\n value = ops.convert_to_tensor(value, name=\"input\")\n return gen_nn_ops.max_pool(\n value,\n ksize=ksize,\n strides=strides,\n padding=padding,\n data_format=data_format,\n name=name)\n\n\n# pylint: disable=redefined-builtin\n@tf_export(\"nn.max_pool_with_argmax\", v1=[])\ndef max_pool_with_argmax_v2(input,\n ksize,\n strides,\n padding,\n data_format=\"NHWC\",\n output_dtype=dtypes.int64,\n name=None):\n \"\"\"Performs max pooling on the input and outputs both max values and indices.\n\n The indices in `argmax` are flattened, so that a maximum value at position\n `[b, y, x, c]` becomes flattened index\n `((b * height + y) * width + x) * channels + c`.\n\n The indices returned are always in `[0, height) x [0, width)` before\n flattening, even if padding is involved and the mathematically correct answer\n is outside (either negative or too large). This is a bug, but fixing it is\n difficult to do in a safe backwards compatible way, especially due to\n flattening.\n\n Args:\n input: A `Tensor`. Must be one of the following types: `float32`, `float64`,\n `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`,\n `uint32`, `uint64`.\n 4-D with shape `[batch, height, width, channels]`. Input to pool over.\n ksize: A list of `ints` that has length `>= 4`.\n The size of the window for each dimension of the input tensor.\n strides: A list of `ints` that has length `>= 4`.\n The stride of the sliding window for each dimension of the\n input tensor.\n padding: A `string` from: `\"SAME\", \"VALID\"`.\n The type of padding algorithm to use.\n data_format: An optional `string`, must be set to `\"NHWC\"`. Defaults to\n `\"NHWC\"`.\n Specify the data format of the input and output data.\n output_dtype: An optional `tf.DType` from: `tf.int32, tf.int64`.\n Defaults to `tf.int64`.\n The dtype of the returned argmax tensor.\n name: A name for the operation (optional).\n\n Returns:\n A tuple of `Tensor` objects (output, argmax).\n\n output: A `Tensor`. Has the same type as `input`.\n argmax: A `Tensor` of type `output_dtype`.\n \"\"\"\n\n if data_format != \"NHWC\":\n raise ValueError(\"Data formats other than 'NHWC' are not yet supported\")\n\n return gen_nn_ops.max_pool_with_argmax(input=input,\n ksize=ksize,\n strides=strides,\n padding=padding,\n Targmax=output_dtype,\n name=name)\n\n# pylint: enable=redefined-builtin\n\n\[email protected](\"Conv2D\", \"flops\")\ndef _calc_conv_flops(graph, node):\n \"\"\"Calculates the compute resources needed for Conv2D.\"\"\"\n input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0])\n input_shape.assert_is_fully_defined()\n filter_shape = graph_util.tensor_shape_from_node_def_name(\n graph, node.input[1])\n filter_shape.assert_is_fully_defined()\n output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name)\n output_shape.assert_is_fully_defined()\n filter_height = int(filter_shape[0])\n filter_width = int(filter_shape[1])\n filter_in_depth = int(filter_shape[2])\n output_count = np.prod(output_shape.as_list(), dtype=np.int64)\n return ops.OpStats(\n \"flops\",\n (output_count * filter_in_depth * filter_height * filter_width * 2))\n\n\[email protected](\"DepthwiseConv2dNative\", \"flops\")\ndef _calc_depthwise_conv_flops(graph, node):\n \"\"\"Calculates the compute resources needed for DepthwiseConv2dNative.\"\"\"\n input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0])\n input_shape.assert_is_fully_defined()\n filter_shape = graph_util.tensor_shape_from_node_def_name(\n graph, node.input[1])\n filter_shape.assert_is_fully_defined()\n output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name)\n output_shape.assert_is_fully_defined()\n filter_height = int(filter_shape[0])\n filter_width = int(filter_shape[1])\n output_count = np.prod(output_shape.as_list(), dtype=np.int64)\n return ops.OpStats(\"flops\", (output_count * filter_height * filter_width * 2))\n\n\[email protected](\"BiasAdd\", \"flops\")\ndef _calc_bias_add_flops(graph, node):\n \"\"\"Calculates the computing needed for BiasAdd.\"\"\"\n input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0])\n input_shape.assert_is_fully_defined()\n input_count = np.prod(input_shape.as_list())\n return ops.OpStats(\"flops\", input_count)\n\n\n@tf_export(v1=[\"nn.xw_plus_b\"])\ndef xw_plus_b(x, weights, biases, name=None): # pylint: disable=invalid-name\n \"\"\"Computes matmul(x, weights) + biases.\n\n Args:\n x: a 2D tensor. Dimensions typically: batch, in_units\n weights: a 2D tensor. Dimensions typically: in_units, out_units\n biases: a 1D tensor. Dimensions: out_units\n name: A name for the operation (optional). If not specified\n \"xw_plus_b\" is used.\n\n Returns:\n A 2-D Tensor computing matmul(x, weights) + biases.\n Dimensions typically: batch, out_units.\n \"\"\"\n with ops.name_scope(name, \"xw_plus_b\", [x, weights, biases]) as name:\n x = ops.convert_to_tensor(x, name=\"x\")\n weights = ops.convert_to_tensor(weights, name=\"weights\")\n biases = ops.convert_to_tensor(biases, name=\"biases\")\n mm = math_ops.matmul(x, weights)\n return bias_add(mm, biases, name=name)\n\n\ndef xw_plus_b_v1(x, weights, biases, name=None): # pylint: disable=invalid-name\n \"\"\"Computes matmul(x, weights) + biases.\n\n This is a deprecated version of that will soon be removed.\n\n Args:\n x: a 2D tensor. Dimensions typically: batch, in_units\n weights: a 2D tensor. Dimensions typically: in_units, out_units\n biases: a 1D tensor. Dimensions: out_units\n name: A name for the operation (optional). If not specified\n \"xw_plus_b_v1\" is used.\n\n Returns:\n A 2-D Tensor computing matmul(x, weights) + biases.\n Dimensions typically: batch, out_units.\n \"\"\"\n with ops.name_scope(name, \"xw_plus_b_v1\", [x, weights, biases]) as name:\n x = ops.convert_to_tensor(x, name=\"x\")\n weights = ops.convert_to_tensor(weights, name=\"weights\")\n biases = ops.convert_to_tensor(biases, name=\"biases\")\n mm = math_ops.matmul(x, weights)\n return bias_add_v1(mm, biases, name=name)\n\n\ndef _get_noise_shape(x, noise_shape):\n # If noise_shape is none return immediately.\n if noise_shape is None:\n return array_ops.shape(x)\n\n try:\n # Best effort to figure out the intended shape.\n # If not possible, let the op to handle it.\n # In eager mode exception will show up.\n noise_shape_ = tensor_shape.as_shape(noise_shape)\n except (TypeError, ValueError):\n return noise_shape\n\n if x.shape.dims is not None and len(x.shape.dims) == len(noise_shape_.dims):\n new_dims = []\n for i, dim in enumerate(x.shape.dims):\n if noise_shape_.dims[i].value is None and dim.value is not None:\n new_dims.append(dim.value)\n else:\n new_dims.append(noise_shape_.dims[i].value)\n return tensor_shape.TensorShape(new_dims)\n\n return noise_shape\n\n\n@tf_export(v1=[\"nn.dropout\"])\[email protected]_args(None, \"Please use `rate` instead of `keep_prob`. \"\n \"Rate should be set to `rate = 1 - keep_prob`.\",\n \"keep_prob\")\ndef dropout(x, keep_prob=None, noise_shape=None, seed=None, name=None,\n rate=None): # pylint: disable=invalid-name\n \"\"\"Computes dropout.\n\n For each element of `x`, with probability `rate`, outputs `0`, and otherwise\n scales up the input by `1 / (1-rate)`. The scaling is such that the expected\n sum is unchanged.\n\n By default, each element is kept or dropped independently. If `noise_shape`\n is specified, it must be\n [broadcastable](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)\n to the shape of `x`, and only dimensions with `noise_shape[i] == shape(x)[i]`\n will make independent decisions. For example, if `shape(x) = [k, l, m, n]`\n and `noise_shape = [k, 1, 1, n]`, each batch and channel component will be\n kept independently and each row and column will be kept or not kept together.\n\n Args:\n x: A floating point tensor.\n keep_prob: (deprecated) A deprecated alias for `(1-rate)`.\n noise_shape: A 1-D `Tensor` of type `int32`, representing the\n shape for randomly generated keep/drop flags.\n seed: A Python integer. Used to create random seeds. See\n `tf.set_random_seed` for behavior.\n name: A name for this operation (optional).\n rate: A scalar `Tensor` with the same type as `x`. The probability that each\n element of `x` is discarded.\n\n Returns:\n A Tensor of the same shape of `x`.\n\n Raises:\n ValueError: If `rate` is not in `[0, 1)` or if `x` is not a floating\n point tensor.\n \"\"\"\n try:\n keep = 1. - keep_prob if keep_prob is not None else None\n except TypeError:\n raise ValueError(\"keep_prob must be a floating point number or Tensor \"\n \"(got %r)\" % keep_prob)\n\n rate = deprecation.deprecated_argument_lookup(\n \"rate\", rate,\n \"keep_prob\", keep)\n\n if rate is None:\n raise ValueError(\"You must provide a rate to dropout.\")\n\n return dropout_v2(x, rate, noise_shape=noise_shape, seed=seed, name=name)\n\n\n@tf_export(\"nn.dropout\", v1=[])\ndef dropout_v2(x, rate, noise_shape=None, seed=None, name=None): # pylint: disable=invalid-name\n \"\"\"Computes dropout.\n\n With probability `rate`, drops elements of `x`. Input that are kept are\n scaled up by `1 / (1 - rate)`, otherwise outputs `0`. The scaling is so that\n the expected sum is unchanged.\n\n By default, each element is kept or dropped independently. If `noise_shape`\n is specified, it must be\n [broadcastable](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)\n to the shape of `x`, and only dimensions with `noise_shape[i] == shape(x)[i]`\n will make independent decisions. For example, if `shape(x) = [k, l, m, n]`\n and `noise_shape = [k, 1, 1, n]`, each batch and channel component will be\n kept independently and each row and column will be kept or not kept together.\n\n Args:\n x: A floating point tensor.\n rate: A scalar `Tensor` with the same type as x. The probability\n that each element is dropped. For example, setting rate=0.1 would drop\n 10% of input elements.\n noise_shape: A 1-D `Tensor` of type `int32`, representing the\n shape for randomly generated keep/drop flags.\n seed: A Python integer. Used to create random seeds. See\n `tf.set_random_seed`\n for behavior.\n name: A name for this operation (optional).\n\n Returns:\n A Tensor of the same shape of `x`.\n\n Raises:\n ValueError: If `keep_prob` is not in `(0, 1]` or if `x` is not a floating\n point tensor.\n \"\"\"\n with ops.name_scope(name, \"dropout\", [x]) as name:\n x = ops.convert_to_tensor(x, name=\"x\")\n if not x.dtype.is_floating:\n raise ValueError(\"x has to be a floating point tensor since it's going to\"\n \" be scaled. Got a %s tensor instead.\" % x.dtype)\n if isinstance(rate, numbers.Real) and not (rate >= 0 and rate < 1):\n raise ValueError(\"rate must be a scalar tensor or a float in the \"\n \"range [0, 1), got %g\" % rate)\n\n # Early return if nothing needs to be dropped.\n if isinstance(rate, numbers.Real) and rate == 0:\n return x\n if context.executing_eagerly():\n if isinstance(rate, ops.EagerTensor):\n if rate.numpy() == 0:\n return x\n else:\n rate = ops.convert_to_tensor(\n rate, dtype=x.dtype, name=\"rate\")\n rate.get_shape().assert_is_compatible_with(tensor_shape.scalar())\n\n # Do nothing if we know rate == 0\n if tensor_util.constant_value(rate) == 0:\n return x\n\n noise_shape = _get_noise_shape(x, noise_shape)\n\n keep_prob = 1 - rate\n # uniform [keep_prob, 1.0 + keep_prob)\n random_tensor = keep_prob\n random_tensor += random_ops.random_uniform(\n noise_shape, seed=seed, dtype=x.dtype)\n # 0. if [keep_prob, 1.0) and 1. if [1.0, 1.0 + keep_prob)\n binary_tensor = math_ops.floor(random_tensor)\n ret = math_ops.divide(x, keep_prob) * binary_tensor\n if not context.executing_eagerly():\n ret.set_shape(x.get_shape())\n return ret\n\n\n@tf_export(\"math.top_k\", \"nn.top_k\")\ndef top_k(input, k=1, sorted=True, name=None): # pylint: disable=redefined-builtin\n \"\"\"Finds values and indices of the `k` largest entries for the last dimension.\n\n If the input is a vector (rank=1), finds the `k` largest entries in the vector\n and outputs their values and indices as vectors. Thus `values[j]` is the\n `j`-th largest entry in `input`, and its index is `indices[j]`.\n\n For matrices (resp. higher rank input), computes the top `k` entries in each\n row (resp. vector along the last dimension). Thus,\n\n values.shape = indices.shape = input.shape[:-1] + [k]\n\n If two elements are equal, the lower-index element appears first.\n\n Args:\n input: 1-D or higher `Tensor` with last dimension at least `k`.\n k: 0-D `int32` `Tensor`. Number of top elements to look for along the last\n dimension (along each row for matrices).\n sorted: If true the resulting `k` elements will be sorted by the values in\n descending order.\n name: Optional name for the operation.\n\n Returns:\n values: The `k` largest elements along each last dimensional slice.\n indices: The indices of `values` within the last dimension of `input`.\n \"\"\"\n return gen_nn_ops.top_kv2(input, k=k, sorted=sorted, name=name)\n\n\ndef nth_element(input, n, reverse=False, name=None): # pylint: disable=redefined-builtin\n r\"\"\"Finds values of the `n`-th order statistic for the last dmension.\n\n If the input is a vector (rank-1), finds the entries which is the nth-smallest\n value in the vector and outputs their values as scalar tensor.\n\n For matrices (resp. higher rank input), computes the entries which is the\n nth-smallest value in each row (resp. vector along the last dimension). Thus,\n\n values.shape = input.shape[:-1]\n\n Args:\n input: 1-D or higher `Tensor` with last dimension at least `n+1`.\n n: A `Tensor` of type `int32`.\n 0-D. Position of sorted vector to select along the last dimension (along\n each row for matrices). Valid range of n is `[0, input.shape[:-1])`\n reverse: An optional `bool`. Defaults to `False`.\n When set to True, find the nth-largest value in the vector and vice\n versa.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `input`.\n The `n`-th order statistic along each last dimensional slice.\n \"\"\"\n return gen_nn_ops.nth_element(input, n, reverse=reverse, name=name)\n\n\n@tf_export(v1=[\"nn.fractional_max_pool\"])\[email protected](date=None, instructions=\"`seed2` and `deterministic` \"\n \"args are deprecated. Use fractional_max_pool_v2.\")\ndef fractional_max_pool(value,\n pooling_ratio,\n pseudo_random=False,\n overlapping=False,\n deterministic=False,\n seed=0,\n seed2=0,\n name=None): # pylint: disable=redefined-builtin\n r\"\"\"Performs fractional max pooling on the input.\n\n This is a deprecated version of `fractional_max_pool`.\n\n Fractional max pooling is slightly different than regular max pooling. In\n regular max pooling, you downsize an input set by taking the maximum value of\n smaller N x N subsections of the set (often 2x2), and try to reduce the set by\n a factor of N, where N is an integer. Fractional max pooling, as you might\n expect from the word \"fractional\", means that the overall reduction ratio N\n does not have to be an integer.\n\n The sizes of the pooling regions are generated randomly but are fairly\n uniform. For example, let's look at the height dimension, and the constraints\n on the list of rows that will be pool boundaries.\n\n First we define the following:\n\n 1. input_row_length : the number of rows from the input set\n 2. output_row_length : which will be smaller than the input\n 3. alpha = input_row_length / output_row_length : our reduction ratio\n 4. K = floor(alpha)\n 5. row_pooling_sequence : this is the result list of pool boundary rows\n\n Then, row_pooling_sequence should satisfy:\n\n 1. a[0] = 0 : the first value of the sequence is 0\n 2. a[end] = input_row_length : the last value of the sequence is the size\n 3. K <= (a[i+1] - a[i]) <= K+1 : all intervals are K or K+1 size\n 4. length(row_pooling_sequence) = output_row_length+1\n\n For more details on fractional max pooling, see this paper: [Benjamin Graham,\n Fractional Max-Pooling](http://arxiv.org/abs/1412.6071)\n\n Args:\n value: A `Tensor`. 4-D with shape `[batch, height, width, channels]`.\n pooling_ratio: A list of `floats` that has length >= 4. Pooling ratio for\n each dimension of `value`, currently only supports row and col dimension\n and should be >= 1.0. For example, a valid pooling ratio looks like [1.0,\n 1.44, 1.73, 1.0]. The first and last elements must be 1.0 because we don't\n allow pooling on batch and channels dimensions. 1.44 and 1.73 are pooling\n ratio on height and width dimensions respectively.\n pseudo_random: An optional `bool`. Defaults to `False`. When set to `True`,\n generates the pooling sequence in a pseudorandom fashion, otherwise, in a\n random fashion. Check paper [Benjamin Graham, Fractional\n Max-Pooling](http://arxiv.org/abs/1412.6071) for difference between\n pseudorandom and random.\n overlapping: An optional `bool`. Defaults to `False`. When set to `True`,\n it means when pooling, the values at the boundary of adjacent pooling\n cells are used by both cells. For example:\n `index 0 1 2 3 4`\n `value 20 5 16 3 7`\n If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used\n twice. The result would be [20, 16] for fractional max pooling.\n deterministic: An optional `bool`. Deprecated; use `fractional_max_pool_v2`\n instead.\n seed: An optional `int`. Defaults to `0`. If set to be non-zero, the\n random number generator is seeded by the given seed. Otherwise it is\n seeded by a random seed.\n seed2: An optional `int`. Deprecated; use `fractional_max_pool_v2` instead.\n name: A name for the operation (optional).\n\n Returns:\n A tuple of `Tensor` objects (`output`, `row_pooling_sequence`,\n `col_pooling_sequence`).\n output: Output `Tensor` after fractional max pooling. Has the same type as\n `value`.\n row_pooling_sequence: A `Tensor` of type `int64`.\n col_pooling_sequence: A `Tensor` of type `int64`.\n \"\"\"\n return gen_nn_ops.fractional_max_pool(value, pooling_ratio, pseudo_random,\n overlapping, deterministic, seed, seed2,\n name)\n\n\n@tf_export(\"nn.fractional_max_pool\", v1=[])\ndef fractional_max_pool_v2(value,\n pooling_ratio,\n pseudo_random=False,\n overlapping=False,\n seed=0,\n name=None): # pylint: disable=redefined-builtin\n r\"\"\"Performs fractional max pooling on the input.\n\n Fractional max pooling is slightly different than regular max pooling. In\n regular max pooling, you downsize an input set by taking the maximum value of\n smaller N x N subsections of the set (often 2x2), and try to reduce the set by\n a factor of N, where N is an integer. Fractional max pooling, as you might\n expect from the word \"fractional\", means that the overall reduction ratio N\n does not have to be an integer.\n\n The sizes of the pooling regions are generated randomly but are fairly\n uniform. For example, let's look at the height dimension, and the constraints\n on the list of rows that will be pool boundaries.\n\n First we define the following:\n\n 1. input_row_length : the number of rows from the input set\n 2. output_row_length : which will be smaller than the input\n 3. alpha = input_row_length / output_row_length : our reduction ratio\n 4. K = floor(alpha)\n 5. row_pooling_sequence : this is the result list of pool boundary rows\n\n Then, row_pooling_sequence should satisfy:\n\n 1. a[0] = 0 : the first value of the sequence is 0\n 2. a[end] = input_row_length : the last value of the sequence is the size\n 3. K <= (a[i+1] - a[i]) <= K+1 : all intervals are K or K+1 size\n 4. length(row_pooling_sequence) = output_row_length+1\n\n For more details on fractional max pooling, see this paper: [Benjamin Graham,\n Fractional Max-Pooling](http://arxiv.org/abs/1412.6071)\n\n Args:\n value: A `Tensor`. 4-D with shape `[batch, height, width, channels]`.\n pooling_ratio: A list of `floats` that has length >= 4. Pooling ratio for\n each dimension of `value`, currently only supports row and col dimension\n and should be >= 1.0. For example, a valid pooling ratio looks like [1.0,\n 1.44, 1.73, 1.0]. The first and last elements must be 1.0 because we don't\n allow pooling on batch and channels dimensions. 1.44 and 1.73 are pooling\n ratio on height and width dimensions respectively.\n pseudo_random: An optional `bool`. Defaults to `False`. When set to `True`,\n generates the pooling sequence in a pseudorandom fashion, otherwise, in a\n random fashion. Check paper [Benjamin Graham, Fractional\n Max-Pooling](http://arxiv.org/abs/1412.6071) for difference between\n pseudorandom and random.\n overlapping: An optional `bool`. Defaults to `False`. When set to `True`,\n it means when pooling, the values at the boundary of adjacent pooling\n cells are used by both cells. For example:\n `index 0 1 2 3 4`\n `value 20 5 16 3 7`\n If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used\n twice. The result would be [20, 16] for fractional max pooling.\n seed: An optional `int`. Defaults to `0`. If set to be non-zero, the\n random number generator is seeded by the given seed. Otherwise it is\n seeded by a random seed.\n name: A name for the operation (optional).\n\n Returns:\n A tuple of `Tensor` objects (`output`, `row_pooling_sequence`,\n `col_pooling_sequence`).\n output: Output `Tensor` after fractional max pooling. Has the same type as\n `value`.\n row_pooling_sequence: A `Tensor` of type `int64`.\n col_pooling_sequence: A `Tensor` of type `int64`.\n \"\"\"\n if seed == 0:\n return gen_nn_ops.fractional_max_pool(value, pooling_ratio, pseudo_random,\n overlapping, deterministic=False,\n seed=0, seed2=0, name=name)\n else:\n seed1, seed2 = random_seed.get_seed(seed)\n return gen_nn_ops.fractional_max_pool(value, pooling_ratio, pseudo_random,\n overlapping, deterministic=True,\n seed=seed1, seed2=seed2, name=name)\n\n\n@tf_export(v1=[\"nn.fractional_avg_pool\"])\[email protected](date=None, instructions=\"`seed2` and `deterministic` \"\n \"args are deprecated. Use fractional_avg_pool_v2.\")\ndef fractional_avg_pool(value,\n pooling_ratio,\n pseudo_random=False,\n overlapping=False,\n deterministic=False,\n seed=0,\n seed2=0,\n name=None): # pylint: disable=redefined-builtin\n r\"\"\"Performs fractional average pooling on the input.\n\n This is a deprecated version of `fractional_avg_pool`.\n\n Fractional average pooling is similar to Fractional max pooling in the pooling\n region generation step. The only difference is that after pooling regions are\n generated, a mean operation is performed instead of a max operation in each\n pooling region.\n\n Args:\n value: A `Tensor`. 4-D with shape `[batch, height, width, channels]`.\n pooling_ratio: A list of `floats` that has length >= 4. Pooling ratio for\n each dimension of `value`, currently only supports row and col dimension\n and should be >= 1.0. For example, a valid pooling ratio looks like [1.0,\n 1.44, 1.73, 1.0]. The first and last elements must be 1.0 because we don't\n allow pooling on batch and channels dimensions. 1.44 and 1.73 are pooling\n ratio on height and width dimensions respectively.\n pseudo_random: An optional `bool`. Defaults to `False`. When set to `True`,\n generates the pooling sequence in a pseudorandom fashion, otherwise, in a\n random fashion. Check paper [Benjamin Graham, Fractional\n Max-Pooling](http://arxiv.org/abs/1412.6071) for difference between\n pseudorandom and random.\n overlapping: An optional `bool`. Defaults to `False`. When set to `True`,\n it means when pooling, the values at the boundary of adjacent pooling\n cells are used by both cells. For example:\n `index 0 1 2 3 4`\n `value 20 5 16 3 7`\n If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used\n twice. The result would be [20, 16] for fractional avg pooling.\n deterministic: An optional `bool`. Deprecated; use `fractional_avg_pool_v2`\n instead.\n seed: An optional `int`. Defaults to `0`. If set to be non-zero, the\n random number generator is seeded by the given seed. Otherwise it is\n seeded by a random seed.\n seed2: An optional `int`. Deprecated; use `fractional_avg_pool_v2` instead.\n name: A name for the operation (optional).\n\n Returns:\n A tuple of `Tensor` objects (`output`, `row_pooling_sequence`,\n `col_pooling_sequence`).\n output: Output `Tensor` after fractional avg pooling. Has the same type as\n `value`.\n row_pooling_sequence: A `Tensor` of type `int64`.\n col_pooling_sequence: A `Tensor` of type `int64`.\n \"\"\"\n return gen_nn_ops.fractional_avg_pool(value, pooling_ratio, pseudo_random,\n overlapping, deterministic, seed, seed2,\n name=name)\n\n\n@tf_export(\"nn.fractional_avg_pool\", v1=[])\ndef fractional_avg_pool_v2(value,\n pooling_ratio,\n pseudo_random=False,\n overlapping=False,\n seed=0,\n name=None): # pylint: disable=redefined-builtin\n r\"\"\"Performs fractional average pooling on the input.\n\n Fractional average pooling is similar to Fractional max pooling in the pooling\n region generation step. The only difference is that after pooling regions are\n generated, a mean operation is performed instead of a max operation in each\n pooling region.\n\n Args:\n value: A `Tensor`. 4-D with shape `[batch, height, width, channels]`.\n pooling_ratio: A list of `floats` that has length >= 4. Pooling ratio for\n each dimension of `value`, currently only supports row and col dimension\n and should be >= 1.0. For example, a valid pooling ratio looks like [1.0,\n 1.44, 1.73, 1.0]. The first and last elements must be 1.0 because we don't\n allow pooling on batch and channels dimensions. 1.44 and 1.73 are pooling\n ratio on height and width dimensions respectively.\n pseudo_random: An optional `bool`. Defaults to `False`. When set to `True`,\n generates the pooling sequence in a pseudorandom fashion, otherwise, in a\n random fashion. Check paper [Benjamin Graham, Fractional\n Max-Pooling](http://arxiv.org/abs/1412.6071) for difference between\n pseudorandom and random.\n overlapping: An optional `bool`. Defaults to `False`. When set to `True`,\n it means when pooling, the values at the boundary of adjacent pooling\n cells are used by both cells. For example:\n `index 0 1 2 3 4`\n `value 20 5 16 3 7`\n If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used\n twice. The result would be [20, 16] for fractional avg pooling.\n seed: An optional `int`. Defaults to `0`. If set to be non-zero, the\n random number generator is seeded by the given seed. Otherwise it is\n seeded by a random seed.\n name: A name for the operation (optional).\n\n Returns:\n A tuple of `Tensor` objects (`output`, `row_pooling_sequence`,\n `col_pooling_sequence`).\n output: Output `Tensor` after fractional avg pooling. Has the same type as\n `value`.\n row_pooling_sequence: A `Tensor` of type `int64`.\n col_pooling_sequence: A `Tensor` of type `int64`.\n \"\"\"\n if seed == 0:\n return gen_nn_ops.fractional_avg_pool(value, pooling_ratio, pseudo_random,\n overlapping, deterministic=False,\n seed=0, seed2=0, name=name)\n else:\n seed1, seed2 = random_seed.get_seed(seed)\n return gen_nn_ops.fractional_avg_pool(value, pooling_ratio, pseudo_random,\n overlapping, deterministic=True,\n seed=seed1, seed2=seed2, name=name)\n\n\n@tf_export(v1=[\"nn.conv1d\"])\[email protected]_arg_values(\n None,\n \"`NCHW` for data_format is deprecated, use `NCW` instead\",\n warn_once=True,\n data_format=\"NCHW\")\[email protected]_arg_values(\n None,\n \"`NHWC` for data_format is deprecated, use `NWC` instead\",\n warn_once=True,\n data_format=\"NHWC\")\ndef conv1d(value,\n filters,\n stride,\n padding,\n use_cudnn_on_gpu=None,\n data_format=None,\n name=None):\n r\"\"\"Computes a 1-D convolution given 3-D input and filter tensors.\n\n Given an input tensor of shape\n [batch, in_width, in_channels]\n if data_format is \"NWC\", or\n [batch, in_channels, in_width]\n if data_format is \"NCW\",\n and a filter / kernel tensor of shape\n [filter_width, in_channels, out_channels], this op reshapes\n the arguments to pass them to conv2d to perform the equivalent\n convolution operation.\n\n Internally, this op reshapes the input tensors and invokes `tf.nn.conv2d`.\n For example, if `data_format` does not start with \"NC\", a tensor of shape\n [batch, in_width, in_channels]\n is reshaped to\n [batch, 1, in_width, in_channels],\n and the filter is reshaped to\n [1, filter_width, in_channels, out_channels].\n The result is then reshaped back to\n [batch, out_width, out_channels]\n \\(where out_width is a function of the stride and padding as in conv2d\\) and\n returned to the caller.\n\n Args:\n value: A 3D `Tensor`. Must be of type `float16`, `float32`, or `float64`.\n filters: A 3D `Tensor`. Must have the same type as `value`.\n stride: An `integer`. The number of entries by which\n the filter is moved right at each step.\n padding: 'SAME' or 'VALID'\n use_cudnn_on_gpu: An optional `bool`. Defaults to `True`.\n data_format: An optional `string` from `\"NWC\", \"NCW\"`. Defaults\n to `\"NWC\"`, the data is stored in the order of\n [batch, in_width, in_channels]. The `\"NCW\"` format stores\n data as [batch, in_channels, in_width].\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as input.\n\n Raises:\n ValueError: if `data_format` is invalid.\n \"\"\"\n with ops.name_scope(name, \"conv1d\", [value, filters]) as name:\n # Reshape the input tensor to [batch, 1, in_width, in_channels]\n if data_format is None or data_format == \"NHWC\" or data_format == \"NWC\":\n data_format = \"NHWC\"\n spatial_start_dim = 1\n strides = [1, 1, stride, 1]\n elif data_format == \"NCHW\" or data_format == \"NCW\":\n data_format = \"NCHW\"\n spatial_start_dim = 2\n strides = [1, 1, 1, stride]\n else:\n raise ValueError(\"data_format must be \\\"NWC\\\" or \\\"NCW\\\".\")\n value = array_ops.expand_dims(value, spatial_start_dim)\n filters = array_ops.expand_dims(filters, 0)\n result = gen_nn_ops.conv2d(\n value,\n filters,\n strides,\n padding,\n use_cudnn_on_gpu=use_cudnn_on_gpu,\n data_format=data_format)\n return array_ops.squeeze(result, [spatial_start_dim])\n\n\n@tf_export(\"nn.conv1d\", v1=[])\ndef conv1d_v2(input, # pylint: disable=redefined-builtin\n filters,\n stride,\n padding,\n data_format=None,\n name=None):\n r\"\"\"Computes a 1-D convolution given 3-D input and filter tensors.\n\n Given an input tensor of shape\n [batch, in_width, in_channels]\n if data_format is \"NWC\", or\n [batch, in_channels, in_width]\n if data_format is \"NCW\",\n and a filter / kernel tensor of shape\n [filter_width, in_channels, out_channels], this op reshapes\n the arguments to pass them to conv2d to perform the equivalent\n convolution operation.\n\n Internally, this op reshapes the input tensors and invokes `tf.nn.conv2d`.\n For example, if `data_format` does not start with \"NC\", a tensor of shape\n [batch, in_width, in_channels]\n is reshaped to\n [batch, 1, in_width, in_channels],\n and the filter is reshaped to\n [1, filter_width, in_channels, out_channels].\n The result is then reshaped back to\n [batch, out_width, out_channels]\n \\(where out_width is a function of the stride and padding as in conv2d\\) and\n returned to the caller.\n\n Args:\n input: A 3D `Tensor`. Must be of type `float16`, `float32`, or `float64`.\n filters: A 3D `Tensor`. Must have the same type as `input`.\n stride: An `integer`. The number of entries by which\n the filter is moved right at each step.\n padding: 'SAME' or 'VALID'\n data_format: An optional `string` from `\"NWC\", \"NCW\"`. Defaults\n to `\"NWC\"`, the data is stored in the order of\n [batch, in_width, in_channels]. The `\"NCW\"` format stores\n data as [batch, in_channels, in_width].\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as input.\n\n Raises:\n ValueError: if `data_format` is invalid.\n \"\"\"\n return conv1d(input, # pylint: disable=redefined-builtin\n filters,\n stride,\n padding,\n use_cudnn_on_gpu=True,\n data_format=data_format,\n name=name)\n\n\ndef conv1d_transpose(\n value,\n filter, # pylint: disable=redefined-builtin\n output_shape,\n stride,\n padding=\"SAME\",\n data_format=\"NWC\",\n name=None):\n \"\"\"The transpose of `conv1d`.\n\n This operation is sometimes called \"deconvolution\" after [Deconvolutional\n Networks](http://www.matthewzeiler.com/pubs/cvpr2010/cvpr2010.pdf), but is\n actually the transpose (gradient) of `conv1d` rather than an actual\n deconvolution.\n\n Args:\n value: A 3-D `Tensor` of type `float` and shape\n `[batch, in_width, in_channels]` for `NWC` data format or\n `[batch, in_channels, in_width]` for `NCW` data format.\n filter: A 3-D `Tensor` with the same type as `value` and shape\n `[filter_width, output_channels, in_channels]`. `filter`'s\n `in_channels` dimension must match that of `value`.\n output_shape: A 1-D `Tensor` representing the output shape of the\n deconvolution op.\n stride: An `integer`. The number of entries by which\n the filter is moved right at each step.\n padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.\n See the \"returns\" section of `tf.nn.convolution` for details.\n data_format: A string. 'NHWC' and 'NCHW' are supported.\n name: Optional name for the returned tensor.\n\n Returns:\n A `Tensor` with the same type as `value`.\n\n Raises:\n ValueError: If input/output depth does not match `filter`'s shape, or if\n padding is other than `'VALID'` or `'SAME'`.\n \"\"\"\n with ops.name_scope(name, \"conv1d_transpose\",\n [value, filter, output_shape]) as name:\n output_shape_ = ops.convert_to_tensor(output_shape, name=\"output_shape\")\n if not output_shape_.get_shape().is_compatible_with(tensor_shape.vector(3)):\n raise ValueError(\"output_shape must have shape (3,), got {}\".format(\n output_shape_.get_shape()))\n\n # The format could be either NWC or NCW, map to NHWC or NCHW\n if data_format is None or data_format == \"NWC\":\n data_format_2d = \"NHWC\"\n axis = 2\n elif data_format == \"NCW\":\n data_format_2d = \"NCHW\"\n axis = 1\n else:\n raise ValueError(\"data_format must be \\\"NWC\\\" or \\\"NCW\\\".\")\n\n if not value.get_shape().dims[axis].is_compatible_with(\n filter.get_shape()[2]):\n raise ValueError(\"input channels does not match filter's input channels, \"\n \"{} != {}\".format(value.get_shape()[axis],\n filter.get_shape()[2]))\n\n if isinstance(output_shape, (list, np.ndarray)):\n # output_shape's shape should be == [3] if reached this point.\n if not filter.get_shape().dims[1].is_compatible_with(\n output_shape[axis]):\n raise ValueError(\n \"output_shape does not match filter's output channels, \"\n \"{} != {}\".format(output_shape[axis],\n filter.get_shape()[1]))\n\n if padding != \"VALID\" and padding != \"SAME\":\n raise ValueError(\"padding must be either VALID or SAME:\"\n \" {}\".format(padding))\n\n # Reshape the input tensor to [batch, 1, in_width, in_channels]\n if data_format_2d == \"NHWC\":\n output_shape_ = array_ops.concat(\n [output_shape_[:1], [1], output_shape_[1:]], axis=0)\n spatial_start_dim = 1\n strides = [1, 1, stride, 1]\n else:\n output_shape_ = array_ops.concat(\n [output_shape_[:2], [1], output_shape_[2:]], axis=0)\n spatial_start_dim = 2\n strides = [1, 1, 1, stride]\n value = array_ops.expand_dims(value, spatial_start_dim)\n filter = array_ops.expand_dims(filter, 0) # pylint: disable=redefined-builtin\n\n result = gen_nn_ops.conv2d_backprop_input(\n input_sizes=output_shape_,\n filter=filter,\n out_backprop=value,\n strides=strides,\n padding=padding,\n data_format=data_format_2d,\n name=name)\n return array_ops.squeeze(result, [spatial_start_dim])\n\n\[email protected](\"Dilation2D\", \"flops\")\ndef _calc_dilation2d_flops(graph, node):\n \"\"\"Calculates the compute resources needed for Dilation2D.\"\"\"\n input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0])\n input_shape.assert_is_fully_defined()\n filter_shape = graph_util.tensor_shape_from_node_def_name(\n graph, node.input[1])\n filter_shape.assert_is_fully_defined()\n output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name)\n output_shape.assert_is_fully_defined()\n filter_height = int(filter_shape[0])\n filter_width = int(filter_shape[1])\n output_count = np.prod(output_shape.as_list(), dtype=np.int64)\n return ops.OpStats(\"flops\", (output_count * filter_height * filter_width * 2))\n\n\n@tf_export(v1=[\"nn.erosion2d\"])\ndef erosion2d(value, kernel, strides, rates, padding, name=None):\n \"\"\"Computes the grayscale erosion of 4-D `value` and 3-D `kernel` tensors.\n\n The `value` tensor has shape `[batch, in_height, in_width, depth]` and the\n `kernel` tensor has shape `[kernel_height, kernel_width, depth]`, i.e.,\n each input channel is processed independently of the others with its own\n structuring function. The `output` tensor has shape\n `[batch, out_height, out_width, depth]`. The spatial dimensions of the\n output tensor depend on the `padding` algorithm. We currently only support the\n default \"NHWC\" `data_format`.\n\n In detail, the grayscale morphological 2-D erosion is given by:\n\n output[b, y, x, c] =\n min_{dy, dx} value[b,\n strides[1] * y - rates[1] * dy,\n strides[2] * x - rates[2] * dx,\n c] -\n kernel[dy, dx, c]\n\n Duality: The erosion of `value` by the `kernel` is equal to the negation of\n the dilation of `-value` by the reflected `kernel`.\n\n Args:\n value: A `Tensor`. 4-D with shape `[batch, in_height, in_width, depth]`.\n kernel: A `Tensor`. Must have the same type as `value`.\n 3-D with shape `[kernel_height, kernel_width, depth]`.\n strides: A list of `ints` that has length `>= 4`.\n 1-D of length 4. The stride of the sliding window for each dimension of\n the input tensor. Must be: `[1, stride_height, stride_width, 1]`.\n rates: A list of `ints` that has length `>= 4`.\n 1-D of length 4. The input stride for atrous morphological dilation.\n Must be: `[1, rate_height, rate_width, 1]`.\n padding: A `string` from: `\"SAME\", \"VALID\"`.\n The type of padding algorithm to use.\n name: A name for the operation (optional). If not specified \"erosion2d\"\n is used.\n\n Returns:\n A `Tensor`. Has the same type as `value`.\n 4-D with shape `[batch, out_height, out_width, depth]`.\n\n Raises:\n ValueError: If the `value` depth does not match `kernel`' shape, or if\n padding is other than `'VALID'` or `'SAME'`.\n \"\"\"\n with ops.name_scope(name, \"erosion2d\", [value, kernel]) as name:\n # Reduce erosion to dilation by duality.\n return math_ops.negative(\n gen_nn_ops.dilation2d(\n input=math_ops.negative(value),\n filter=array_ops.reverse_v2(kernel, [0, 1]),\n strides=strides,\n rates=rates,\n padding=padding,\n name=name))\n\n\n@tf_export(\"nn.erosion2d\", v1=[])\ndef erosion2d_v2(value,\n filters,\n strides,\n padding,\n data_format,\n dilations,\n name=None):\n \"\"\"Computes the grayscale erosion of 4-D `value` and 3-D `filters` tensors.\n\n The `value` tensor has shape `[batch, in_height, in_width, depth]` and the\n `filters` tensor has shape `[filters_height, filters_width, depth]`, i.e.,\n each input channel is processed independently of the others with its own\n structuring function. The `output` tensor has shape\n `[batch, out_height, out_width, depth]`. The spatial dimensions of the\n output tensor depend on the `padding` algorithm. We currently only support the\n default \"NHWC\" `data_format`.\n\n In detail, the grayscale morphological 2-D erosion is given by:\n\n output[b, y, x, c] =\n min_{dy, dx} value[b,\n strides[1] * y - dilations[1] * dy,\n strides[2] * x - dilations[2] * dx,\n c] -\n filters[dy, dx, c]\n\n Duality: The erosion of `value` by the `filters` is equal to the negation of\n the dilation of `-value` by the reflected `filters`.\n\n Args:\n value: A `Tensor`. 4-D with shape `[batch, in_height, in_width, depth]`.\n filters: A `Tensor`. Must have the same type as `value`.\n 3-D with shape `[filters_height, filters_width, depth]`.\n strides: A list of `ints` that has length `>= 4`.\n 1-D of length 4. The stride of the sliding window for each dimension of\n the input tensor. Must be: `[1, stride_height, stride_width, 1]`.\n padding: A `string` from: `\"SAME\", \"VALID\"`.\n The type of padding algorithm to use.\n data_format: A `string`, only `\"NHWC\"` is currently supported.\n dilations: A list of `ints` that has length `>= 4`.\n 1-D of length 4. The input stride for atrous morphological dilation.\n Must be: `[1, rate_height, rate_width, 1]`.\n name: A name for the operation (optional). If not specified \"erosion2d\"\n is used.\n\n Returns:\n A `Tensor`. Has the same type as `value`.\n 4-D with shape `[batch, out_height, out_width, depth]`.\n\n Raises:\n ValueError: If the `value` depth does not match `filters`' shape, or if\n padding is other than `'VALID'` or `'SAME'`.\n \"\"\"\n if data_format != \"NHWC\":\n raise ValueError(\"Data formats other than NHWC are not yet supported\")\n\n with ops.name_scope(name, \"erosion2d\", [value, filters]) as name:\n # Reduce erosion to dilation by duality.\n return math_ops.negative(\n gen_nn_ops.dilation2d(\n input=math_ops.negative(value),\n filter=array_ops.reverse_v2(filters, [0, 1]),\n strides=strides,\n rates=dilations,\n padding=padding,\n name=name))\n\n\n@tf_export(v1=[\"math.in_top_k\", \"nn.in_top_k\"])\ndef in_top_k(predictions, targets, k, name=None):\n r\"\"\"Says whether the targets are in the top `K` predictions.\n\n This outputs a `batch_size` bool array, an entry `out[i]` is `true` if the\n prediction for the target class is among the top `k` predictions among\n all predictions for example `i`. Note that the behavior of `InTopK` differs\n from the `TopK` op in its handling of ties; if multiple classes have the\n same prediction value and straddle the top-`k` boundary, all of those\n classes are considered to be in the top `k`.\n\n More formally, let\n\n \\\\(predictions_i\\\\) be the predictions for all classes for example `i`,\n \\\\(targets_i\\\\) be the target class for example `i`,\n \\\\(out_i\\\\) be the output for example `i`,\n\n $$out_i = predictions_{i, targets_i} \\in TopKIncludingTies(predictions_i)$$\n\n Args:\n predictions: A `Tensor` of type `float32`.\n A `batch_size` x `classes` tensor.\n targets: A `Tensor`. Must be one of the following types: `int32`, `int64`.\n A `batch_size` vector of class ids.\n k: An `int`. Number of top elements to look at for computing precision.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `bool`. Computed Precision at `k` as a `bool Tensor`.\n \"\"\"\n with ops.name_scope(name, \"in_top_k\"):\n return gen_nn_ops.in_top_kv2(predictions, targets, k, name=name)\n\n\n@tf_export(\"math.in_top_k\", \"nn.in_top_k\", v1=[])\ndef in_top_k_v2(targets, predictions, k, name=None):\n return in_top_k(predictions, targets, k, name)\n\n\nin_top_k_v2.__doc__ = in_top_k.__doc__\n\n\ntf_export(v1=[\"nn.quantized_avg_pool\"])(gen_nn_ops.quantized_avg_pool)\ntf_export(v1=[\"nn.quantized_conv2d\"])(gen_nn_ops.quantized_conv2d)\ntf_export(v1=[\"nn.quantized_relu_x\"])(gen_nn_ops.quantized_relu_x)\ntf_export(v1=[\"nn.quantized_max_pool\"])(gen_nn_ops.quantized_max_pool)\n", "# Copyright 2015 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# pylint: disable=protected-access\n\"\"\"Recurrent layers and their base classes.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport uuid\n\nimport numpy as np\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import function\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.keras import activations\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras import constraints\nfrom tensorflow.python.keras import initializers\nfrom tensorflow.python.keras import regularizers\nfrom tensorflow.python.keras.engine.base_layer import Layer\nfrom tensorflow.python.keras.engine.input_spec import InputSpec\nfrom tensorflow.python.keras.utils import generic_utils\nfrom tensorflow.python.keras.utils import tf_utils\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gen_cudnn_rnn_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.training.checkpointable import base as checkpointable\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util.tf_export import keras_export\n\n\n# The following string constants are used by Defun approach for unified backend\n# of LSTM and GRU.\n_DEFUN_API_NAME_ATTRIBUTE = 'experimental_api_implements'\n_DEFUN_DEVICE_ATTRIBUTE = 'experimental_api_preferred_device'\n_CPU_DEVICE_NAME = 'CPU'\n_GPU_DEVICE_NAME = 'GPU'\n\n\n@keras_export('keras.layers.StackedRNNCells')\nclass StackedRNNCells(Layer):\n \"\"\"Wrapper allowing a stack of RNN cells to behave as a single cell.\n\n Used to implement efficient stacked RNNs.\n\n Arguments:\n cells: List of RNN cell instances.\n\n Examples:\n\n ```python\n cells = [\n keras.layers.LSTMCell(output_dim),\n keras.layers.LSTMCell(output_dim),\n keras.layers.LSTMCell(output_dim),\n ]\n\n inputs = keras.Input((timesteps, input_dim))\n x = keras.layers.RNN(cells)(inputs)\n ```\n \"\"\"\n\n @checkpointable.no_automatic_dependency_tracking\n def __init__(self, cells, **kwargs):\n for cell in cells:\n if not hasattr(cell, 'call'):\n raise ValueError('All cells must have a `call` method. '\n 'received cells:', cells)\n if not hasattr(cell, 'state_size'):\n raise ValueError('All cells must have a '\n '`state_size` attribute. '\n 'received cells:', cells)\n self.cells = cells\n # reverse_state_order determines whether the state size will be in a reverse\n # order of the cells' state. User might want to set this to True to keep the\n # existing behavior. This is only useful when use RNN(return_state=True)\n # since the state will be returned as the same order of state_size.\n self.reverse_state_order = kwargs.pop('reverse_state_order', False)\n if self.reverse_state_order:\n logging.warning('reverse_state_order=True in StackedRNNCells will soon '\n 'be deprecated. Please update the code to work with the '\n 'natural order of states if you reply on the RNN states, '\n 'eg RNN(return_state=True).')\n super(StackedRNNCells, self).__init__(**kwargs)\n\n @property\n def state_size(self):\n return tuple(c.state_size for c in\n (self.cells[::-1] if self.reverse_state_order else self.cells))\n\n @property\n def output_size(self):\n if getattr(self.cells[-1], 'output_size', None) is not None:\n return self.cells[-1].output_size\n elif _is_multiple_state(self.cells[-1].state_size):\n return self.cells[-1].state_size[0]\n else:\n return self.cells[-1].state_size\n\n def get_initial_state(self, inputs=None, batch_size=None, dtype=None):\n initial_states = []\n for cell in self.cells[::-1] if self.reverse_state_order else self.cells:\n get_initial_state_fn = getattr(cell, 'get_initial_state', None)\n if get_initial_state_fn:\n initial_states.append(get_initial_state_fn(\n inputs=inputs, batch_size=batch_size, dtype=dtype))\n else:\n initial_states.append(_generate_zero_filled_state_for_cell(\n cell, inputs, batch_size, dtype))\n\n return tuple(initial_states)\n\n def call(self, inputs, states, constants=None, **kwargs):\n # Recover per-cell states.\n state_size = (self.state_size[::-1]\n if self.reverse_state_order else self.state_size)\n nested_states = nest.pack_sequence_as(state_size, nest.flatten(states))\n\n # Call the cells in order and store the returned states.\n new_nested_states = []\n for cell, states in zip(self.cells, nested_states):\n states = states if nest.is_sequence(states) else [states]\n if generic_utils.has_arg(cell.call, 'constants'):\n inputs, states = cell.call(inputs, states, constants=constants,\n **kwargs)\n else:\n inputs, states = cell.call(inputs, states, **kwargs)\n new_nested_states.append(states)\n\n return inputs, nest.pack_sequence_as(state_size,\n nest.flatten(new_nested_states))\n\n @tf_utils.shape_type_conversion\n def build(self, input_shape):\n if isinstance(input_shape, list):\n constants_shape = input_shape[1:]\n input_shape = input_shape[0]\n for cell in self.cells:\n if isinstance(cell, Layer):\n if generic_utils.has_arg(cell.call, 'constants'):\n cell.build([input_shape] + constants_shape)\n else:\n cell.build(input_shape)\n if getattr(cell, 'output_size', None) is not None:\n output_dim = cell.output_size\n elif _is_multiple_state(cell.state_size):\n output_dim = cell.state_size[0]\n else:\n output_dim = cell.state_size\n input_shape = tuple([input_shape[0]] +\n tensor_shape.as_shape(output_dim).as_list())\n self.built = True\n\n def get_config(self):\n cells = []\n for cell in self.cells:\n cells.append({\n 'class_name': cell.__class__.__name__,\n 'config': cell.get_config()\n })\n config = {'cells': cells}\n base_config = super(StackedRNNCells, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n @classmethod\n def from_config(cls, config, custom_objects=None):\n from tensorflow.python.keras.layers import deserialize as deserialize_layer # pylint: disable=g-import-not-at-top\n cells = []\n for cell_config in config.pop('cells'):\n cells.append(\n deserialize_layer(cell_config, custom_objects=custom_objects))\n return cls(cells, **config)\n\n @property\n def trainable_weights(self):\n if not self.trainable:\n return []\n weights = []\n for cell in self.cells:\n if isinstance(cell, Layer):\n weights += cell.trainable_weights\n return weights\n\n @property\n def non_trainable_weights(self):\n weights = []\n for cell in self.cells:\n if isinstance(cell, Layer):\n weights += cell.non_trainable_weights\n if not self.trainable:\n trainable_weights = []\n for cell in self.cells:\n if isinstance(cell, Layer):\n trainable_weights += cell.trainable_weights\n return trainable_weights + weights\n return weights\n\n def get_weights(self):\n \"\"\"Retrieves the weights of the model.\n\n Returns:\n A flat list of Numpy arrays.\n \"\"\"\n weights = []\n for cell in self.cells:\n if isinstance(cell, Layer):\n weights += cell.weights\n return K.batch_get_value(weights)\n\n def set_weights(self, weights):\n \"\"\"Sets the weights of the model.\n\n Arguments:\n weights: A list of Numpy arrays with shapes and types matching\n the output of `model.get_weights()`.\n \"\"\"\n tuples = []\n for cell in self.cells:\n if isinstance(cell, Layer):\n num_param = len(cell.weights)\n weights = weights[:num_param]\n for sw, w in zip(cell.weights, weights):\n tuples.append((sw, w))\n weights = weights[num_param:]\n K.batch_set_value(tuples)\n\n @property\n def losses(self):\n losses = []\n for cell in self.cells:\n if isinstance(cell, Layer):\n losses += cell.losses\n return losses + self._losses\n\n @property\n def updates(self):\n updates = []\n for cell in self.cells:\n if isinstance(cell, Layer):\n updates += cell.updates\n return updates + self._updates\n\n\n@keras_export('keras.layers.RNN')\nclass RNN(Layer):\n \"\"\"Base class for recurrent layers.\n\n Arguments:\n cell: A RNN cell instance or a list of RNN cell instances.\n A RNN cell is a class that has:\n - a `call(input_at_t, states_at_t)` method, returning\n `(output_at_t, states_at_t_plus_1)`. The call method of the\n cell can also take the optional argument `constants`, see\n section \"Note on passing external constants\" below.\n - a `state_size` attribute. This can be a single integer\n (single state) in which case it is the size of the recurrent\n state. This can also be a list/tuple of integers (one size per\n state).\n The `state_size` can also be TensorShape or tuple/list of\n TensorShape, to represent high dimension state.\n - a `output_size` attribute. This can be a single integer or a\n TensorShape, which represent the shape of the output. For backward\n compatible reason, if this attribute is not available for the\n cell, the value will be inferred by the first element of the\n `state_size`.\n - a `get_initial_state(inputs=None, batch_size=None, dtype=None)`\n method that creates a tensor meant to be fed to `call()` as the\n initial state, if user didn't specify any initial state via other\n means. The returned initial state should be in shape of\n [batch, cell.state_size]. Cell might choose to create zero filled\n tensor, or with other values based on the cell implementations.\n `inputs` is the input tensor to the RNN layer, which should\n contain the batch size as its shape[0], and also dtype. Note that\n the shape[0] might be None during the graph construction. Either\n the `inputs` or the pair of `batch` and `dtype `are provided.\n `batch` is a scalar tensor that represent the batch size\n of the input. `dtype` is `tf.dtype` that represent the dtype of\n the input.\n For backward compatible reason, if this method is not implemented\n by the cell, RNN layer will create a zero filled tensors with the\n size of [batch, cell.state_size].\n In the case that `cell` is a list of RNN cell instances, the cells\n will be stacked on after the other in the RNN, implementing an\n efficient stacked RNN.\n return_sequences: Boolean. Whether to return the last output\n in the output sequence, or the full sequence.\n return_state: Boolean. Whether to return the last state\n in addition to the output.\n go_backwards: Boolean (default False).\n If True, process the input sequence backwards and return the\n reversed sequence.\n stateful: Boolean (default False). If True, the last state\n for each sample at index i in a batch will be used as initial\n state for the sample of index i in the following batch.\n unroll: Boolean (default False).\n If True, the network will be unrolled,\n else a symbolic loop will be used.\n Unrolling can speed-up a RNN,\n although it tends to be more memory-intensive.\n Unrolling is only suitable for short sequences.\n input_dim: dimensionality of the input (integer or tuple of integers).\n This argument (or alternatively, the keyword argument `input_shape`)\n is required when using this layer as the first layer in a model.\n input_length: Length of input sequences, to be specified\n when it is constant.\n This argument is required if you are going to connect\n `Flatten` then `Dense` layers upstream\n (without it, the shape of the dense outputs cannot be computed).\n Note that if the recurrent layer is not the first layer\n in your model, you would need to specify the input length\n at the level of the first layer\n (e.g. via the `input_shape` argument)\n time_major: The shape format of the `inputs` and `outputs` tensors.\n If True, the inputs and outputs will be in shape\n `(timesteps, batch, ...)`, whereas in the False case, it will be\n `(batch, timesteps, ...)`. Using `time_major = True` is a bit more\n efficient because it avoids transposes at the beginning and end of the\n RNN calculation. However, most TensorFlow data is batch-major, so by\n default this function accepts input and emits output in batch-major\n form.\n\n Input shape:\n N-D tensor with shape `(batch_size, timesteps, ...)` or\n `(timesteps, batch_size, ...)` when time_major is True.\n\n Output shape:\n - if `return_state`: a list of tensors. The first tensor is\n the output. The remaining tensors are the last states,\n each with shape `(batch_size, state_size)`, where `state_size` could\n be a high dimension tensor shape.\n - if `return_sequences`: N-D tensor with shape\n `(batch_size, timesteps, output_size)`, where `output_size` could\n be a high dimension tensor shape, or\n `(timesteps, batch_size, output_size)` when `time_major` is True.\n - else, N-D tensor with shape `(batch_size, output_size)`, where\n `output_size` could be a high dimension tensor shape.\n\n # Masking\n This layer supports masking for input data with a variable number\n of timesteps. To introduce masks to your data,\n use an [Embedding](embeddings.md) layer with the `mask_zero` parameter\n set to `True`.\n\n # Note on using statefulness in RNNs\n You can set RNN layers to be 'stateful', which means that the states\n computed for the samples in one batch will be reused as initial states\n for the samples in the next batch. This assumes a one-to-one mapping\n between samples in different successive batches.\n\n To enable statefulness:\n - specify `stateful=True` in the layer constructor.\n - specify a fixed batch size for your model, by passing\n if sequential model:\n `batch_input_shape=(...)` to the first layer in your model.\n else for functional model with 1 or more Input layers:\n `batch_shape=(...)` to all the first layers in your model.\n This is the expected shape of your inputs\n *including the batch size*.\n It should be a tuple of integers, e.g. `(32, 10, 100)`.\n - specify `shuffle=False` when calling fit().\n\n To reset the states of your model, call `.reset_states()` on either\n a specific layer, or on your entire model.\n\n # Note on specifying the initial state of RNNs\n You can specify the initial state of RNN layers symbolically by\n calling them with the keyword argument `initial_state`. The value of\n `initial_state` should be a tensor or list of tensors representing\n the initial state of the RNN layer.\n\n You can specify the initial state of RNN layers numerically by\n calling `reset_states` with the keyword argument `states`. The value of\n `states` should be a numpy array or list of numpy arrays representing\n the initial state of the RNN layer.\n\n # Note on passing external constants to RNNs\n You can pass \"external\" constants to the cell using the `constants`\n keyword argument of `RNN.__call__` (as well as `RNN.call`) method. This\n requires that the `cell.call` method accepts the same keyword argument\n `constants`. Such constants can be used to condition the cell\n transformation on additional static inputs (not changing over time),\n a.k.a. an attention mechanism.\n\n Examples:\n\n ```python\n # First, let's define a RNN Cell, as a layer subclass.\n\n class MinimalRNNCell(keras.layers.Layer):\n\n def __init__(self, units, **kwargs):\n self.units = units\n self.state_size = units\n super(MinimalRNNCell, self).__init__(**kwargs)\n\n def build(self, input_shape):\n self.kernel = self.add_weight(shape=(input_shape[-1], self.units),\n initializer='uniform',\n name='kernel')\n self.recurrent_kernel = self.add_weight(\n shape=(self.units, self.units),\n initializer='uniform',\n name='recurrent_kernel')\n self.built = True\n\n def call(self, inputs, states):\n prev_output = states[0]\n h = K.dot(inputs, self.kernel)\n output = h + K.dot(prev_output, self.recurrent_kernel)\n return output, [output]\n\n # Let's use this cell in a RNN layer:\n\n cell = MinimalRNNCell(32)\n x = keras.Input((None, 5))\n layer = RNN(cell)\n y = layer(x)\n\n # Here's how to use the cell to build a stacked RNN:\n\n cells = [MinimalRNNCell(32), MinimalRNNCell(64)]\n x = keras.Input((None, 5))\n layer = RNN(cells)\n y = layer(x)\n ```\n \"\"\"\n\n @checkpointable.no_automatic_dependency_tracking\n def __init__(self,\n cell,\n return_sequences=False,\n return_state=False,\n go_backwards=False,\n stateful=False,\n unroll=False,\n time_major=False,\n **kwargs):\n if isinstance(cell, (list, tuple)):\n cell = StackedRNNCells(cell)\n if not hasattr(cell, 'call'):\n raise ValueError('`cell` should have a `call` method. '\n 'The RNN was passed:', cell)\n if not hasattr(cell, 'state_size'):\n raise ValueError('The RNN cell should have '\n 'an attribute `state_size` '\n '(tuple of integers, '\n 'one integer per RNN state).')\n # If True, the output for masked timestep will be zeros, whereas in the\n # False case, output from previous timestep is returned for masked timestep.\n self.zero_output_for_mask = kwargs.pop('zero_output_for_mask', False)\n super(RNN, self).__init__(**kwargs)\n self.cell = cell\n if isinstance(cell, checkpointable.CheckpointableBase):\n self._track_checkpointable(self.cell, name='cell')\n self.return_sequences = return_sequences\n self.return_state = return_state\n self.go_backwards = go_backwards\n self.stateful = stateful\n self.unroll = unroll\n self.time_major = time_major\n\n self.supports_masking = True\n # The input shape is unknown yet, it could have nested tensor inputs, and\n # the input spec will be the list of specs for flattened inputs.\n self.input_spec = None\n self.state_spec = None\n self._states = None\n self.constants_spec = None\n self._num_constants = None\n self._num_inputs = None\n\n @property\n def states(self):\n if self._states is None:\n state = nest.map_structure(lambda _: None, self.cell.state_size)\n return state if nest.is_sequence(self.cell.state_size) else [state]\n return self._states\n\n @states.setter\n def states(self, states):\n self._states = states\n\n def compute_output_shape(self, input_shape):\n if isinstance(input_shape, list):\n input_shape = input_shape[0]\n # Check whether the input shape contains any nested shapes. It could be\n # (tensor_shape(1, 2), tensor_shape(3, 4)) or (1, 2, 3) which is from numpy\n # inputs.\n try:\n input_shape = tensor_shape.as_shape(input_shape)\n except (ValueError, TypeError):\n # A nested tensor input\n input_shape = nest.flatten(input_shape)[0]\n\n batch = input_shape[0]\n time_step = input_shape[1]\n if self.time_major:\n batch, time_step = time_step, batch\n\n if _is_multiple_state(self.cell.state_size):\n state_size = self.cell.state_size\n else:\n state_size = [self.cell.state_size]\n\n def _get_output_shape(flat_output_size):\n output_dim = tensor_shape.as_shape(flat_output_size).as_list()\n if self.return_sequences:\n if self.time_major:\n output_shape = tensor_shape.as_shape([time_step, batch] + output_dim)\n else:\n output_shape = tensor_shape.as_shape([batch, time_step] + output_dim)\n else:\n output_shape = tensor_shape.as_shape([batch] + output_dim)\n return output_shape\n\n if getattr(self.cell, 'output_size', None) is not None:\n # cell.output_size could be nested structure.\n output_shape = nest.flatten(nest.map_structure(\n _get_output_shape, self.cell.output_size))\n output_shape = output_shape[0] if len(output_shape) == 1 else output_shape\n else:\n # Note that state_size[0] could be a tensor_shape or int.\n output_shape = _get_output_shape(state_size[0])\n\n if self.return_state:\n def _get_state_shape(flat_state):\n state_shape = [batch] + tensor_shape.as_shape(flat_state).as_list()\n return tensor_shape.as_shape(state_shape)\n state_shape = nest.map_structure(_get_state_shape, state_size)\n return generic_utils.to_list(output_shape) + nest.flatten(state_shape)\n else:\n return output_shape\n\n def compute_mask(self, inputs, mask):\n # Time step masks must be the same for each input.\n # This is because the mask for an RNN is of size [batch, time_steps, 1],\n # and specifies which time steps should be skipped, and a time step\n # must be skipped for all inputs.\n # TODO(scottzhu): Should we accept multiple different masks?\n mask = nest.flatten(mask)[0]\n output_mask = mask if self.return_sequences else None\n if self.return_state:\n state_mask = [None for _ in self.states]\n return [output_mask] + state_mask\n else:\n return output_mask\n\n def build(self, input_shape):\n # Note input_shape will be list of shapes of initial states and\n # constants if these are passed in __call__.\n if self._num_constants is not None:\n constants_shape = input_shape[-self._num_constants:] # pylint: disable=invalid-unary-operand-type\n constants_shape = nest.map_structure(\n lambda s: tuple(tensor_shape.TensorShape(s).as_list()),\n constants_shape)\n else:\n constants_shape = None\n\n if isinstance(input_shape, list):\n input_shape = input_shape[0]\n # The input_shape here could be a nest structure.\n\n # do the tensor_shape to shapes here. The input could be single tensor, or a\n # nested structure of tensors.\n def get_input_spec(shape):\n if isinstance(shape, tensor_shape.TensorShape):\n input_spec_shape = shape.as_list()\n else:\n input_spec_shape = list(shape)\n batch_index, time_step_index = (1, 0) if self.time_major else (0, 1)\n if not self.stateful:\n input_spec_shape[batch_index] = None\n input_spec_shape[time_step_index] = None\n return InputSpec(shape=tuple(input_spec_shape))\n\n def get_step_input_shape(shape):\n if isinstance(shape, tensor_shape.TensorShape):\n shape = tuple(shape.as_list())\n # remove the timestep from the input_shape\n return shape[1:] if self.time_major else (shape[0],) + shape[2:]\n\n # Check whether the input shape contains any nested shapes. It could be\n # (tensor_shape(1, 2), tensor_shape(3, 4)) or (1, 2, 3) which is from numpy\n # inputs.\n try:\n input_shape = tensor_shape.as_shape(input_shape)\n except (ValueError, TypeError):\n # A nested tensor input\n pass\n\n if not nest.is_sequence(input_shape):\n # This indicates the there is only one input.\n if self.input_spec is not None:\n self.input_spec[0] = get_input_spec(input_shape)\n else:\n self.input_spec = [get_input_spec(input_shape)]\n step_input_shape = get_step_input_shape(input_shape)\n else:\n flat_input_shapes = nest.flatten(input_shape)\n flat_input_shapes = nest.map_structure(get_input_spec, flat_input_shapes)\n assert len(flat_input_shapes) == self._num_inputs\n if self.input_spec is not None:\n self.input_spec[:self._num_inputs] = flat_input_shapes\n else:\n self.input_spec = flat_input_shapes\n step_input_shape = nest.map_structure(get_step_input_shape, input_shape)\n\n # allow cell (if layer) to build before we set or validate state_spec\n if isinstance(self.cell, Layer):\n if constants_shape is not None:\n self.cell.build([step_input_shape] + constants_shape)\n else:\n self.cell.build(step_input_shape)\n\n # set or validate state_spec\n if _is_multiple_state(self.cell.state_size):\n state_size = list(self.cell.state_size)\n else:\n state_size = [self.cell.state_size]\n\n if self.state_spec is not None:\n # initial_state was passed in call, check compatibility\n self._validate_state_spec(state_size, self.state_spec)\n else:\n self.state_spec = [\n InputSpec(shape=[None] + tensor_shape.as_shape(dim).as_list())\n for dim in state_size\n ]\n if self.stateful:\n self.reset_states()\n self.built = True\n\n @staticmethod\n def _validate_state_spec(cell_state_sizes, init_state_specs):\n \"\"\"Validate the state spec between the initial_state and the state_size.\n\n Args:\n cell_state_sizes: list, the `state_size` attribute from the cell.\n init_state_specs: list, the `state_spec` from the initial_state that is\n passed in call()\n\n Raises:\n ValueError: When initial state spec is not compatible with the state size.\n \"\"\"\n validation_error = ValueError(\n 'An `initial_state` was passed that is not compatible with '\n '`cell.state_size`. Received `state_spec`={}; '\n 'however `cell.state_size` is '\n '{}'.format(init_state_specs, cell_state_sizes))\n if len(cell_state_sizes) == len(init_state_specs):\n for i in range(len(cell_state_sizes)):\n if not tensor_shape.TensorShape(\n # Ignore the first axis for init_state which is for batch\n init_state_specs[i].shape[1:]).is_compatible_with(\n tensor_shape.TensorShape(cell_state_sizes[i])):\n raise validation_error\n else:\n raise validation_error\n\n def get_initial_state(self, inputs):\n get_initial_state_fn = getattr(self.cell, 'get_initial_state', None)\n\n if nest.is_sequence(inputs):\n # The input are nested sequences. Use the first element in the seq to get\n # batch size and dtype.\n inputs = nest.flatten(inputs)[0]\n\n input_shape = array_ops.shape(inputs)\n batch_size = input_shape[1] if self.time_major else input_shape[0]\n dtype = inputs.dtype\n if get_initial_state_fn:\n init_state = get_initial_state_fn(\n inputs=None, batch_size=batch_size, dtype=dtype)\n else:\n init_state = _generate_zero_filled_state(batch_size, self.cell.state_size,\n dtype)\n # Keras RNN expect the states in a list, even if it's a single state tensor.\n if not nest.is_sequence(init_state):\n init_state = [init_state]\n # Force the state to be a list in case it is a namedtuple eg LSTMStateTuple.\n return list(init_state)\n\n def __call__(self, inputs, initial_state=None, constants=None, **kwargs):\n inputs, initial_state, constants = _standardize_args(inputs,\n initial_state,\n constants,\n self._num_constants,\n self._num_inputs)\n # in case the real inputs is a nested structure, set the size of flatten\n # input so that we can distinguish between real inputs, initial_state and\n # constants.\n self._num_inputs = len(nest.flatten(inputs))\n\n if initial_state is None and constants is None:\n return super(RNN, self).__call__(inputs, **kwargs)\n\n # If any of `initial_state` or `constants` are specified and are Keras\n # tensors, then add them to the inputs and temporarily modify the\n # input_spec to include them.\n\n additional_inputs = []\n additional_specs = []\n if initial_state is not None:\n additional_inputs += initial_state\n self.state_spec = [\n InputSpec(shape=K.int_shape(state)) for state in initial_state\n ]\n additional_specs += self.state_spec\n if constants is not None:\n additional_inputs += constants\n self.constants_spec = [\n InputSpec(shape=K.int_shape(constant)) for constant in constants\n ]\n self._num_constants = len(constants)\n additional_specs += self.constants_spec\n # at this point additional_inputs cannot be empty\n is_keras_tensor = K.is_keras_tensor(additional_inputs[0])\n for tensor in additional_inputs:\n if K.is_keras_tensor(tensor) != is_keras_tensor:\n raise ValueError('The initial state or constants of an RNN'\n ' layer cannot be specified with a mix of'\n ' Keras tensors and non-Keras tensors'\n ' (a \"Keras tensor\" is a tensor that was'\n ' returned by a Keras layer, or by `Input`)')\n\n if is_keras_tensor:\n # Compute the full input spec, including state and constants\n full_input = [inputs] + additional_inputs\n # The original input_spec is None since there could be a nested tensor\n # input. Update the input_spec to match the inputs.\n full_input_spec = [None for _ in range(len(nest.flatten(inputs)))\n ] + additional_specs\n # Perform the call with temporarily replaced input_spec\n original_input_spec = self.input_spec\n self.input_spec = full_input_spec\n output = super(RNN, self).__call__(full_input, **kwargs)\n self.input_spec = original_input_spec\n return output\n else:\n if initial_state is not None:\n kwargs['initial_state'] = initial_state\n if constants is not None:\n kwargs['constants'] = constants\n return super(RNN, self).__call__(inputs, **kwargs)\n\n def call(self,\n inputs,\n mask=None,\n training=None,\n initial_state=None,\n constants=None):\n inputs, initial_state, constants = self._process_inputs(\n inputs, initial_state, constants)\n\n if mask is not None:\n # Time step masks must be the same for each input.\n # TODO(scottzhu): Should we accept multiple different masks?\n mask = nest.flatten(mask)[0]\n\n if nest.is_sequence(inputs):\n # In the case of nested input, use the first element for shape check.\n input_shape = K.int_shape(nest.flatten(inputs)[0])\n else:\n input_shape = K.int_shape(inputs)\n timesteps = input_shape[0] if self.time_major else input_shape[1]\n if self.unroll and timesteps in [None, 1]:\n raise ValueError('Cannot unroll a RNN if the '\n 'time dimension is undefined or equal to 1. \\n'\n '- If using a Sequential model, '\n 'specify the time dimension by passing '\n 'an `input_shape` or `batch_input_shape` '\n 'argument to your first layer. If your '\n 'first layer is an Embedding, you can '\n 'also use the `input_length` argument.\\n'\n '- If using the functional API, specify '\n 'the time dimension by passing a `shape` '\n 'or `batch_shape` argument to your Input layer.')\n\n kwargs = {}\n if generic_utils.has_arg(self.cell.call, 'training'):\n kwargs['training'] = training\n\n # TF RNN cells expect single tensor as state instead of list wrapped tensor.\n is_tf_rnn_cell = getattr(self.cell, '_is_tf_rnn_cell', None) is not None\n if constants:\n if not generic_utils.has_arg(self.cell.call, 'constants'):\n raise ValueError('RNN cell does not support constants')\n\n def step(inputs, states):\n constants = states[-self._num_constants:] # pylint: disable=invalid-unary-operand-type\n states = states[:-self._num_constants] # pylint: disable=invalid-unary-operand-type\n\n states = states[0] if len(states) == 1 and is_tf_rnn_cell else states\n output, new_states = self.cell.call(\n inputs, states, constants=constants, **kwargs)\n if not nest.is_sequence(new_states):\n new_states = [new_states]\n return output, new_states\n else:\n\n def step(inputs, states):\n states = states[0] if len(states) == 1 and is_tf_rnn_cell else states\n output, new_states = self.cell.call(inputs, states, **kwargs)\n if not nest.is_sequence(new_states):\n new_states = [new_states]\n return output, new_states\n\n last_output, outputs, states = K.rnn(\n step,\n inputs,\n initial_state,\n constants=constants,\n go_backwards=self.go_backwards,\n mask=mask,\n unroll=self.unroll,\n input_length=timesteps,\n time_major=self.time_major,\n zero_output_for_mask=self.zero_output_for_mask)\n if self.stateful:\n updates = []\n for i in range(len(states)):\n updates.append(state_ops.assign(self.states[i], states[i]))\n self.add_update(updates, inputs)\n\n if self.return_sequences:\n output = outputs\n else:\n output = last_output\n\n if self.return_state:\n if not isinstance(states, (list, tuple)):\n states = [states]\n else:\n states = list(states)\n return generic_utils.to_list(output) + states\n else:\n return output\n\n def _process_inputs(self, inputs, initial_state, constants):\n # input shape: `(samples, time (padded with zeros), input_dim)`\n # note that the .build() method of subclasses MUST define\n # self.input_spec and self.state_spec with complete input shapes.\n if isinstance(inputs, list):\n # get initial_state from full input spec\n # as they could be copied to multiple GPU.\n if self._num_constants is None:\n initial_state = inputs[1:]\n else:\n initial_state = inputs[1:-self._num_constants]\n constants = inputs[-self._num_constants:]\n if len(initial_state) == 0:\n initial_state = None\n inputs = inputs[0]\n if initial_state is not None:\n pass\n elif self.stateful:\n initial_state = self.states\n else:\n initial_state = self.get_initial_state(inputs)\n\n if len(initial_state) != len(self.states):\n raise ValueError('Layer has ' + str(len(self.states)) +\n ' states but was passed ' + str(len(initial_state)) +\n ' initial states.')\n return inputs, initial_state, constants\n\n def reset_states(self, states=None):\n if not self.stateful:\n raise AttributeError('Layer must be stateful.')\n if self.time_major:\n batch_size = self.input_spec[0].shape[1]\n else:\n batch_size = self.input_spec[0].shape[0]\n if not batch_size:\n raise ValueError('If a RNN is stateful, it needs to know '\n 'its batch size. Specify the batch size '\n 'of your input tensors: \\n'\n '- If using a Sequential model, '\n 'specify the batch size by passing '\n 'a `batch_input_shape` '\n 'argument to your first layer.\\n'\n '- If using the functional API, specify '\n 'the batch size by passing a '\n '`batch_shape` argument to your Input layer.')\n # initialize state if None\n if self.states[0] is None:\n if _is_multiple_state(self.cell.state_size):\n self.states = [\n K.zeros([batch_size] + tensor_shape.as_shape(dim).as_list())\n for dim in self.cell.state_size\n ]\n else:\n self.states = [\n K.zeros([batch_size] +\n tensor_shape.as_shape(self.cell.state_size).as_list())\n ]\n elif states is None:\n if _is_multiple_state(self.cell.state_size):\n for state, dim in zip(self.states, self.cell.state_size):\n K.set_value(state,\n np.zeros([batch_size] +\n tensor_shape.as_shape(dim).as_list()))\n else:\n K.set_value(self.states[0], np.zeros(\n [batch_size] +\n tensor_shape.as_shape(self.cell.state_size).as_list()))\n else:\n if not isinstance(states, (list, tuple)):\n states = [states]\n if len(states) != len(self.states):\n raise ValueError('Layer ' + self.name + ' expects ' +\n str(len(self.states)) + ' states, '\n 'but it received ' + str(len(states)) +\n ' state values. Input received: ' + str(states))\n for index, (value, state) in enumerate(zip(states, self.states)):\n if _is_multiple_state(self.cell.state_size):\n dim = self.cell.state_size[index]\n else:\n dim = self.cell.state_size\n if value.shape != tuple([batch_size] +\n tensor_shape.as_shape(dim).as_list()):\n raise ValueError(\n 'State ' + str(index) + ' is incompatible with layer ' +\n self.name + ': expected shape=' + str(\n (batch_size, dim)) + ', found shape=' + str(value.shape))\n # TODO(fchollet): consider batch calls to `set_value`.\n K.set_value(state, value)\n\n def get_config(self):\n config = {\n 'return_sequences': self.return_sequences,\n 'return_state': self.return_state,\n 'go_backwards': self.go_backwards,\n 'stateful': self.stateful,\n 'unroll': self.unroll,\n 'time_major': self.time_major\n }\n if self._num_constants is not None:\n config['num_constants'] = self._num_constants\n if self.zero_output_for_mask:\n config['zero_output_for_mask'] = self.zero_output_for_mask\n\n cell_config = self.cell.get_config()\n config['cell'] = {\n 'class_name': self.cell.__class__.__name__,\n 'config': cell_config\n }\n base_config = super(RNN, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n @classmethod\n def from_config(cls, config, custom_objects=None):\n from tensorflow.python.keras.layers import deserialize as deserialize_layer # pylint: disable=g-import-not-at-top\n cell = deserialize_layer(config.pop('cell'), custom_objects=custom_objects)\n num_constants = config.pop('num_constants', None)\n layer = cls(cell, **config)\n layer._num_constants = num_constants\n return layer\n\n @property\n def trainable_weights(self):\n if not self.trainable:\n return []\n if isinstance(self.cell, Layer):\n return self.cell.trainable_weights\n return []\n\n @property\n def non_trainable_weights(self):\n if isinstance(self.cell, Layer):\n if not self.trainable:\n return self.cell.weights\n return self.cell.non_trainable_weights\n return []\n\n @property\n def losses(self):\n layer_losses = super(RNN, self).losses\n if isinstance(self.cell, Layer):\n return self.cell.losses + layer_losses\n return layer_losses\n\n @property\n def updates(self):\n updates = []\n if isinstance(self.cell, Layer):\n updates += self.cell.updates\n return updates + self._updates\n\n\n@keras_export('keras.layers.SimpleRNNCell')\nclass SimpleRNNCell(Layer):\n \"\"\"Cell class for SimpleRNN.\n\n Arguments:\n units: Positive integer, dimensionality of the output space.\n activation: Activation function to use.\n Default: hyperbolic tangent (`tanh`).\n If you pass `None`, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).\n use_bias: Boolean, whether the layer uses a bias vector.\n kernel_initializer: Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs.\n recurrent_initializer: Initializer for the `recurrent_kernel`\n weights matrix,\n used for the linear transformation of the recurrent state.\n bias_initializer: Initializer for the bias vector.\n kernel_regularizer: Regularizer function applied to\n the `kernel` weights matrix.\n recurrent_regularizer: Regularizer function applied to\n the `recurrent_kernel` weights matrix.\n bias_regularizer: Regularizer function applied to the bias vector.\n kernel_constraint: Constraint function applied to\n the `kernel` weights matrix.\n recurrent_constraint: Constraint function applied to\n the `recurrent_kernel` weights matrix.\n bias_constraint: Constraint function applied to the bias vector.\n dropout: Float between 0 and 1.\n Fraction of the units to drop for\n the linear transformation of the inputs.\n recurrent_dropout: Float between 0 and 1.\n Fraction of the units to drop for\n the linear transformation of the recurrent state.\n \"\"\"\n\n def __init__(self,\n units,\n activation='tanh',\n use_bias=True,\n kernel_initializer='glorot_uniform',\n recurrent_initializer='orthogonal',\n bias_initializer='zeros',\n kernel_regularizer=None,\n recurrent_regularizer=None,\n bias_regularizer=None,\n kernel_constraint=None,\n recurrent_constraint=None,\n bias_constraint=None,\n dropout=0.,\n recurrent_dropout=0.,\n **kwargs):\n super(SimpleRNNCell, self).__init__(**kwargs)\n self.units = units\n self.activation = activations.get(activation)\n self.use_bias = use_bias\n\n self.kernel_initializer = initializers.get(kernel_initializer)\n self.recurrent_initializer = initializers.get(recurrent_initializer)\n self.bias_initializer = initializers.get(bias_initializer)\n\n self.kernel_regularizer = regularizers.get(kernel_regularizer)\n self.recurrent_regularizer = regularizers.get(recurrent_regularizer)\n self.bias_regularizer = regularizers.get(bias_regularizer)\n\n self.kernel_constraint = constraints.get(kernel_constraint)\n self.recurrent_constraint = constraints.get(recurrent_constraint)\n self.bias_constraint = constraints.get(bias_constraint)\n\n self.dropout = min(1., max(0., dropout))\n self.recurrent_dropout = min(1., max(0., recurrent_dropout))\n self.state_size = self.units\n self.output_size = self.units\n self._dropout_mask = None\n self._recurrent_dropout_mask = None\n\n @tf_utils.shape_type_conversion\n def build(self, input_shape):\n self.kernel = self.add_weight(\n shape=(input_shape[-1], self.units),\n name='kernel',\n initializer=self.kernel_initializer,\n regularizer=self.kernel_regularizer,\n constraint=self.kernel_constraint)\n self.recurrent_kernel = self.add_weight(\n shape=(self.units, self.units),\n name='recurrent_kernel',\n initializer=self.recurrent_initializer,\n regularizer=self.recurrent_regularizer,\n constraint=self.recurrent_constraint)\n if self.use_bias:\n self.bias = self.add_weight(\n shape=(self.units,),\n name='bias',\n initializer=self.bias_initializer,\n regularizer=self.bias_regularizer,\n constraint=self.bias_constraint)\n else:\n self.bias = None\n self.built = True\n\n def call(self, inputs, states, training=None):\n prev_output = states[0]\n if 0 < self.dropout < 1 and self._dropout_mask is None:\n self._dropout_mask = _generate_dropout_mask(\n array_ops.ones_like(inputs),\n self.dropout,\n training=training)\n if (0 < self.recurrent_dropout < 1 and\n self._recurrent_dropout_mask is None):\n self._recurrent_dropout_mask = _generate_dropout_mask(\n array_ops.ones_like(prev_output),\n self.recurrent_dropout,\n training=training)\n\n dp_mask = self._dropout_mask\n rec_dp_mask = self._recurrent_dropout_mask\n\n if dp_mask is not None:\n h = K.dot(inputs * dp_mask, self.kernel)\n else:\n h = K.dot(inputs, self.kernel)\n if self.bias is not None:\n h = K.bias_add(h, self.bias)\n\n if rec_dp_mask is not None:\n prev_output *= rec_dp_mask\n output = h + K.dot(prev_output, self.recurrent_kernel)\n if self.activation is not None:\n output = self.activation(output)\n\n return output, [output]\n\n def get_initial_state(self, inputs=None, batch_size=None, dtype=None):\n return _generate_zero_filled_state_for_cell(self, inputs, batch_size, dtype)\n\n def get_config(self):\n config = {\n 'units':\n self.units,\n 'activation':\n activations.serialize(self.activation),\n 'use_bias':\n self.use_bias,\n 'kernel_initializer':\n initializers.serialize(self.kernel_initializer),\n 'recurrent_initializer':\n initializers.serialize(self.recurrent_initializer),\n 'bias_initializer':\n initializers.serialize(self.bias_initializer),\n 'kernel_regularizer':\n regularizers.serialize(self.kernel_regularizer),\n 'recurrent_regularizer':\n regularizers.serialize(self.recurrent_regularizer),\n 'bias_regularizer':\n regularizers.serialize(self.bias_regularizer),\n 'kernel_constraint':\n constraints.serialize(self.kernel_constraint),\n 'recurrent_constraint':\n constraints.serialize(self.recurrent_constraint),\n 'bias_constraint':\n constraints.serialize(self.bias_constraint),\n 'dropout':\n self.dropout,\n 'recurrent_dropout':\n self.recurrent_dropout\n }\n base_config = super(SimpleRNNCell, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.layers.SimpleRNN')\nclass SimpleRNN(RNN):\n \"\"\"Fully-connected RNN where the output is to be fed back to input.\n\n Arguments:\n units: Positive integer, dimensionality of the output space.\n activation: Activation function to use.\n Default: hyperbolic tangent (`tanh`).\n If you pass None, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).\n use_bias: Boolean, whether the layer uses a bias vector.\n kernel_initializer: Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs.\n recurrent_initializer: Initializer for the `recurrent_kernel`\n weights matrix,\n used for the linear transformation of the recurrent state.\n bias_initializer: Initializer for the bias vector.\n kernel_regularizer: Regularizer function applied to\n the `kernel` weights matrix.\n recurrent_regularizer: Regularizer function applied to\n the `recurrent_kernel` weights matrix.\n bias_regularizer: Regularizer function applied to the bias vector.\n activity_regularizer: Regularizer function applied to\n the output of the layer (its \"activation\")..\n kernel_constraint: Constraint function applied to\n the `kernel` weights matrix.\n recurrent_constraint: Constraint function applied to\n the `recurrent_kernel` weights matrix.\n bias_constraint: Constraint function applied to the bias vector.\n dropout: Float between 0 and 1.\n Fraction of the units to drop for\n the linear transformation of the inputs.\n recurrent_dropout: Float between 0 and 1.\n Fraction of the units to drop for\n the linear transformation of the recurrent state.\n return_sequences: Boolean. Whether to return the last output\n in the output sequence, or the full sequence.\n return_state: Boolean. Whether to return the last state\n in addition to the output.\n go_backwards: Boolean (default False).\n If True, process the input sequence backwards and return the\n reversed sequence.\n stateful: Boolean (default False). If True, the last state\n for each sample at index i in a batch will be used as initial\n state for the sample of index i in the following batch.\n unroll: Boolean (default False).\n If True, the network will be unrolled,\n else a symbolic loop will be used.\n Unrolling can speed-up a RNN,\n although it tends to be more memory-intensive.\n Unrolling is only suitable for short sequences.\n \"\"\"\n\n def __init__(self,\n units,\n activation='tanh',\n use_bias=True,\n kernel_initializer='glorot_uniform',\n recurrent_initializer='orthogonal',\n bias_initializer='zeros',\n kernel_regularizer=None,\n recurrent_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n recurrent_constraint=None,\n bias_constraint=None,\n dropout=0.,\n recurrent_dropout=0.,\n return_sequences=False,\n return_state=False,\n go_backwards=False,\n stateful=False,\n unroll=False,\n **kwargs):\n if 'implementation' in kwargs:\n kwargs.pop('implementation')\n logging.warning('The `implementation` argument '\n 'in `SimpleRNN` has been deprecated. '\n 'Please remove it from your layer call.')\n cell = SimpleRNNCell(\n units,\n activation=activation,\n use_bias=use_bias,\n kernel_initializer=kernel_initializer,\n recurrent_initializer=recurrent_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=kernel_regularizer,\n recurrent_regularizer=recurrent_regularizer,\n bias_regularizer=bias_regularizer,\n kernel_constraint=kernel_constraint,\n recurrent_constraint=recurrent_constraint,\n bias_constraint=bias_constraint,\n dropout=dropout,\n recurrent_dropout=recurrent_dropout)\n super(SimpleRNN, self).__init__(\n cell,\n return_sequences=return_sequences,\n return_state=return_state,\n go_backwards=go_backwards,\n stateful=stateful,\n unroll=unroll,\n **kwargs)\n self.activity_regularizer = regularizers.get(activity_regularizer)\n self.input_spec = [InputSpec(ndim=3)]\n\n def call(self, inputs, mask=None, training=None, initial_state=None):\n self.cell._dropout_mask = None\n self.cell._recurrent_dropout_mask = None\n return super(SimpleRNN, self).call(\n inputs, mask=mask, training=training, initial_state=initial_state)\n\n @property\n def units(self):\n return self.cell.units\n\n @property\n def activation(self):\n return self.cell.activation\n\n @property\n def use_bias(self):\n return self.cell.use_bias\n\n @property\n def kernel_initializer(self):\n return self.cell.kernel_initializer\n\n @property\n def recurrent_initializer(self):\n return self.cell.recurrent_initializer\n\n @property\n def bias_initializer(self):\n return self.cell.bias_initializer\n\n @property\n def kernel_regularizer(self):\n return self.cell.kernel_regularizer\n\n @property\n def recurrent_regularizer(self):\n return self.cell.recurrent_regularizer\n\n @property\n def bias_regularizer(self):\n return self.cell.bias_regularizer\n\n @property\n def kernel_constraint(self):\n return self.cell.kernel_constraint\n\n @property\n def recurrent_constraint(self):\n return self.cell.recurrent_constraint\n\n @property\n def bias_constraint(self):\n return self.cell.bias_constraint\n\n @property\n def dropout(self):\n return self.cell.dropout\n\n @property\n def recurrent_dropout(self):\n return self.cell.recurrent_dropout\n\n def get_config(self):\n config = {\n 'units':\n self.units,\n 'activation':\n activations.serialize(self.activation),\n 'use_bias':\n self.use_bias,\n 'kernel_initializer':\n initializers.serialize(self.kernel_initializer),\n 'recurrent_initializer':\n initializers.serialize(self.recurrent_initializer),\n 'bias_initializer':\n initializers.serialize(self.bias_initializer),\n 'kernel_regularizer':\n regularizers.serialize(self.kernel_regularizer),\n 'recurrent_regularizer':\n regularizers.serialize(self.recurrent_regularizer),\n 'bias_regularizer':\n regularizers.serialize(self.bias_regularizer),\n 'activity_regularizer':\n regularizers.serialize(self.activity_regularizer),\n 'kernel_constraint':\n constraints.serialize(self.kernel_constraint),\n 'recurrent_constraint':\n constraints.serialize(self.recurrent_constraint),\n 'bias_constraint':\n constraints.serialize(self.bias_constraint),\n 'dropout':\n self.dropout,\n 'recurrent_dropout':\n self.recurrent_dropout\n }\n base_config = super(SimpleRNN, self).get_config()\n del base_config['cell']\n return dict(list(base_config.items()) + list(config.items()))\n\n @classmethod\n def from_config(cls, config):\n if 'implementation' in config:\n config.pop('implementation')\n return cls(**config)\n\n\n@keras_export('keras.layers.GRUCell')\nclass GRUCell(Layer):\n \"\"\"Cell class for the GRU layer.\n\n Arguments:\n units: Positive integer, dimensionality of the output space.\n activation: Activation function to use.\n Default: hyperbolic tangent (`tanh`).\n If you pass None, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).\n recurrent_activation: Activation function to use\n for the recurrent step.\n Default: hard sigmoid (`hard_sigmoid`).\n If you pass `None`, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).\n use_bias: Boolean, whether the layer uses a bias vector.\n kernel_initializer: Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs.\n recurrent_initializer: Initializer for the `recurrent_kernel`\n weights matrix,\n used for the linear transformation of the recurrent state.\n bias_initializer: Initializer for the bias vector.\n kernel_regularizer: Regularizer function applied to\n the `kernel` weights matrix.\n recurrent_regularizer: Regularizer function applied to\n the `recurrent_kernel` weights matrix.\n bias_regularizer: Regularizer function applied to the bias vector.\n kernel_constraint: Constraint function applied to\n the `kernel` weights matrix.\n recurrent_constraint: Constraint function applied to\n the `recurrent_kernel` weights matrix.\n bias_constraint: Constraint function applied to the bias vector.\n dropout: Float between 0 and 1.\n Fraction of the units to drop for\n the linear transformation of the inputs.\n recurrent_dropout: Float between 0 and 1.\n Fraction of the units to drop for\n the linear transformation of the recurrent state.\n implementation: Implementation mode, either 1 or 2.\n Mode 1 will structure its operations as a larger number of\n smaller dot products and additions, whereas mode 2 will\n batch them into fewer, larger operations. These modes will\n have different performance profiles on different hardware and\n for different applications.\n reset_after: GRU convention (whether to apply reset gate after or\n before matrix multiplication). False = \"before\" (default),\n True = \"after\" (CuDNN compatible).\n \"\"\"\n\n def __init__(self,\n units,\n activation='tanh',\n recurrent_activation='hard_sigmoid',\n use_bias=True,\n kernel_initializer='glorot_uniform',\n recurrent_initializer='orthogonal',\n bias_initializer='zeros',\n kernel_regularizer=None,\n recurrent_regularizer=None,\n bias_regularizer=None,\n kernel_constraint=None,\n recurrent_constraint=None,\n bias_constraint=None,\n dropout=0.,\n recurrent_dropout=0.,\n implementation=1,\n reset_after=False,\n **kwargs):\n super(GRUCell, self).__init__(**kwargs)\n self.units = units\n self.activation = activations.get(activation)\n self.recurrent_activation = activations.get(recurrent_activation)\n self.use_bias = use_bias\n\n self.kernel_initializer = initializers.get(kernel_initializer)\n self.recurrent_initializer = initializers.get(recurrent_initializer)\n self.bias_initializer = initializers.get(bias_initializer)\n\n self.kernel_regularizer = regularizers.get(kernel_regularizer)\n self.recurrent_regularizer = regularizers.get(recurrent_regularizer)\n self.bias_regularizer = regularizers.get(bias_regularizer)\n\n self.kernel_constraint = constraints.get(kernel_constraint)\n self.recurrent_constraint = constraints.get(recurrent_constraint)\n self.bias_constraint = constraints.get(bias_constraint)\n\n self.dropout = min(1., max(0., dropout))\n self.recurrent_dropout = min(1., max(0., recurrent_dropout))\n self.implementation = implementation\n self.reset_after = reset_after\n self.state_size = self.units\n self.output_size = self.units\n self._dropout_mask = None\n self._recurrent_dropout_mask = None\n\n @tf_utils.shape_type_conversion\n def build(self, input_shape):\n input_dim = input_shape[-1]\n self.kernel = self.add_weight(\n shape=(input_dim, self.units * 3),\n name='kernel',\n initializer=self.kernel_initializer,\n regularizer=self.kernel_regularizer,\n constraint=self.kernel_constraint)\n self.recurrent_kernel = self.add_weight(\n shape=(self.units, self.units * 3),\n name='recurrent_kernel',\n initializer=self.recurrent_initializer,\n regularizer=self.recurrent_regularizer,\n constraint=self.recurrent_constraint)\n\n if self.use_bias:\n if not self.reset_after:\n bias_shape = (3 * self.units,)\n else:\n # separate biases for input and recurrent kernels\n # Note: the shape is intentionally different from CuDNNGRU biases\n # `(2 * 3 * self.units,)`, so that we can distinguish the classes\n # when loading and converting saved weights.\n bias_shape = (2, 3 * self.units)\n self.bias = self.add_weight(shape=bias_shape,\n name='bias',\n initializer=self.bias_initializer,\n regularizer=self.bias_regularizer,\n constraint=self.bias_constraint)\n else:\n self.bias = None\n self.built = True\n\n def call(self, inputs, states, training=None):\n h_tm1 = states[0] # previous memory\n\n if 0 < self.dropout < 1 and self._dropout_mask is None:\n self._dropout_mask = _generate_dropout_mask(\n array_ops.ones_like(inputs),\n self.dropout,\n training=training,\n count=3)\n if (0 < self.recurrent_dropout < 1 and\n self._recurrent_dropout_mask is None):\n self._recurrent_dropout_mask = _generate_dropout_mask(\n array_ops.ones_like(h_tm1),\n self.recurrent_dropout,\n training=training,\n count=3)\n\n # dropout matrices for input units\n dp_mask = self._dropout_mask\n # dropout matrices for recurrent units\n rec_dp_mask = self._recurrent_dropout_mask\n\n if self.use_bias:\n if not self.reset_after:\n input_bias, recurrent_bias = self.bias, None\n else:\n input_bias, recurrent_bias = array_ops.unstack(self.bias)\n\n if self.implementation == 1:\n if 0. < self.dropout < 1.:\n inputs_z = inputs * dp_mask[0]\n inputs_r = inputs * dp_mask[1]\n inputs_h = inputs * dp_mask[2]\n else:\n inputs_z = inputs\n inputs_r = inputs\n inputs_h = inputs\n\n x_z = K.dot(inputs_z, self.kernel[:, :self.units])\n x_r = K.dot(inputs_r, self.kernel[:, self.units:self.units * 2])\n x_h = K.dot(inputs_h, self.kernel[:, self.units * 2:])\n\n if self.use_bias:\n x_z = K.bias_add(x_z, input_bias[:self.units])\n x_r = K.bias_add(x_r, input_bias[self.units: self.units * 2])\n x_h = K.bias_add(x_h, input_bias[self.units * 2:])\n\n if 0. < self.recurrent_dropout < 1.:\n h_tm1_z = h_tm1 * rec_dp_mask[0]\n h_tm1_r = h_tm1 * rec_dp_mask[1]\n h_tm1_h = h_tm1 * rec_dp_mask[2]\n else:\n h_tm1_z = h_tm1\n h_tm1_r = h_tm1\n h_tm1_h = h_tm1\n\n recurrent_z = K.dot(h_tm1_z, self.recurrent_kernel[:, :self.units])\n recurrent_r = K.dot(h_tm1_r,\n self.recurrent_kernel[:, self.units:self.units * 2])\n if self.reset_after and self.use_bias:\n recurrent_z = K.bias_add(recurrent_z, recurrent_bias[:self.units])\n recurrent_r = K.bias_add(recurrent_r,\n recurrent_bias[self.units:self.units * 2])\n\n z = self.recurrent_activation(x_z + recurrent_z)\n r = self.recurrent_activation(x_r + recurrent_r)\n\n # reset gate applied after/before matrix multiplication\n if self.reset_after:\n recurrent_h = K.dot(h_tm1_h, self.recurrent_kernel[:, self.units * 2:])\n if self.use_bias:\n recurrent_h = K.bias_add(recurrent_h, recurrent_bias[self.units * 2:])\n recurrent_h = r * recurrent_h\n else:\n recurrent_h = K.dot(r * h_tm1_h,\n self.recurrent_kernel[:, self.units * 2:])\n\n hh = self.activation(x_h + recurrent_h)\n else:\n if 0. < self.dropout < 1.:\n inputs *= dp_mask[0]\n\n # inputs projected by all gate matrices at once\n matrix_x = K.dot(inputs, self.kernel)\n if self.use_bias:\n # biases: bias_z_i, bias_r_i, bias_h_i\n matrix_x = K.bias_add(matrix_x, input_bias)\n\n x_z = matrix_x[:, :self.units]\n x_r = matrix_x[:, self.units: 2 * self.units]\n x_h = matrix_x[:, 2 * self.units:]\n\n if 0. < self.recurrent_dropout < 1.:\n h_tm1 *= rec_dp_mask[0]\n\n if self.reset_after:\n # hidden state projected by all gate matrices at once\n matrix_inner = K.dot(h_tm1, self.recurrent_kernel)\n if self.use_bias:\n matrix_inner = K.bias_add(matrix_inner, recurrent_bias)\n else:\n # hidden state projected separately for update/reset and new\n matrix_inner = K.dot(h_tm1, self.recurrent_kernel[:, :2 * self.units])\n\n recurrent_z = matrix_inner[:, :self.units]\n recurrent_r = matrix_inner[:, self.units:2 * self.units]\n\n z = self.recurrent_activation(x_z + recurrent_z)\n r = self.recurrent_activation(x_r + recurrent_r)\n\n if self.reset_after:\n recurrent_h = r * matrix_inner[:, 2 * self.units:]\n else:\n recurrent_h = K.dot(r * h_tm1,\n self.recurrent_kernel[:, 2 * self.units:])\n\n hh = self.activation(x_h + recurrent_h)\n # previous and candidate state mixed by update gate\n h = z * h_tm1 + (1 - z) * hh\n return h, [h]\n\n def get_config(self):\n config = {\n 'units': self.units,\n 'activation': activations.serialize(self.activation),\n 'recurrent_activation':\n activations.serialize(self.recurrent_activation),\n 'use_bias': self.use_bias,\n 'kernel_initializer': initializers.serialize(self.kernel_initializer),\n 'recurrent_initializer':\n initializers.serialize(self.recurrent_initializer),\n 'bias_initializer': initializers.serialize(self.bias_initializer),\n 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer),\n 'recurrent_regularizer':\n regularizers.serialize(self.recurrent_regularizer),\n 'bias_regularizer': regularizers.serialize(self.bias_regularizer),\n 'kernel_constraint': constraints.serialize(self.kernel_constraint),\n 'recurrent_constraint':\n constraints.serialize(self.recurrent_constraint),\n 'bias_constraint': constraints.serialize(self.bias_constraint),\n 'dropout': self.dropout,\n 'recurrent_dropout': self.recurrent_dropout,\n 'implementation': self.implementation,\n 'reset_after': self.reset_after\n }\n base_config = super(GRUCell, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n def get_initial_state(self, inputs=None, batch_size=None, dtype=None):\n return _generate_zero_filled_state_for_cell(self, inputs, batch_size, dtype)\n\n\n@keras_export(v1=['keras.layers.GRU'])\nclass GRU(RNN):\n \"\"\"Gated Recurrent Unit - Cho et al. 2014.\n\n There are two variants. The default one is based on 1406.1078v3 and\n has reset gate applied to hidden state before matrix multiplication. The\n other one is based on original 1406.1078v1 and has the order reversed.\n\n The second variant is compatible with CuDNNGRU (GPU-only) and allows\n inference on CPU. Thus it has separate biases for `kernel` and\n `recurrent_kernel`. Use `'reset_after'=True` and\n `recurrent_activation='sigmoid'`.\n\n Arguments:\n units: Positive integer, dimensionality of the output space.\n activation: Activation function to use.\n Default: hyperbolic tangent (`tanh`).\n If you pass `None`, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).\n recurrent_activation: Activation function to use\n for the recurrent step.\n Default: hard sigmoid (`hard_sigmoid`).\n If you pass `None`, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).\n use_bias: Boolean, whether the layer uses a bias vector.\n kernel_initializer: Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs.\n recurrent_initializer: Initializer for the `recurrent_kernel`\n weights matrix,\n used for the linear transformation of the recurrent state.\n bias_initializer: Initializer for the bias vector.\n kernel_regularizer: Regularizer function applied to\n the `kernel` weights matrix.\n recurrent_regularizer: Regularizer function applied to\n the `recurrent_kernel` weights matrix.\n bias_regularizer: Regularizer function applied to the bias vector.\n activity_regularizer: Regularizer function applied to\n the output of the layer (its \"activation\")..\n kernel_constraint: Constraint function applied to\n the `kernel` weights matrix.\n recurrent_constraint: Constraint function applied to\n the `recurrent_kernel` weights matrix.\n bias_constraint: Constraint function applied to the bias vector.\n dropout: Float between 0 and 1.\n Fraction of the units to drop for\n the linear transformation of the inputs.\n recurrent_dropout: Float between 0 and 1.\n Fraction of the units to drop for\n the linear transformation of the recurrent state.\n implementation: Implementation mode, either 1 or 2.\n Mode 1 will structure its operations as a larger number of\n smaller dot products and additions, whereas mode 2 will\n batch them into fewer, larger operations. These modes will\n have different performance profiles on different hardware and\n for different applications.\n return_sequences: Boolean. Whether to return the last output\n in the output sequence, or the full sequence.\n return_state: Boolean. Whether to return the last state\n in addition to the output.\n go_backwards: Boolean (default False).\n If True, process the input sequence backwards and return the\n reversed sequence.\n stateful: Boolean (default False). If True, the last state\n for each sample at index i in a batch will be used as initial\n state for the sample of index i in the following batch.\n unroll: Boolean (default False).\n If True, the network will be unrolled,\n else a symbolic loop will be used.\n Unrolling can speed-up a RNN,\n although it tends to be more memory-intensive.\n Unrolling is only suitable for short sequences.\n reset_after: GRU convention (whether to apply reset gate after or\n before matrix multiplication). False = \"before\" (default),\n True = \"after\" (CuDNN compatible).\n\n \"\"\"\n\n def __init__(self,\n units,\n activation='tanh',\n recurrent_activation='hard_sigmoid',\n use_bias=True,\n kernel_initializer='glorot_uniform',\n recurrent_initializer='orthogonal',\n bias_initializer='zeros',\n kernel_regularizer=None,\n recurrent_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n recurrent_constraint=None,\n bias_constraint=None,\n dropout=0.,\n recurrent_dropout=0.,\n implementation=1,\n return_sequences=False,\n return_state=False,\n go_backwards=False,\n stateful=False,\n unroll=False,\n reset_after=False,\n **kwargs):\n if implementation == 0:\n logging.warning('`implementation=0` has been deprecated, '\n 'and now defaults to `implementation=1`.'\n 'Please update your layer call.')\n cell = GRUCell(\n units,\n activation=activation,\n recurrent_activation=recurrent_activation,\n use_bias=use_bias,\n kernel_initializer=kernel_initializer,\n recurrent_initializer=recurrent_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=kernel_regularizer,\n recurrent_regularizer=recurrent_regularizer,\n bias_regularizer=bias_regularizer,\n kernel_constraint=kernel_constraint,\n recurrent_constraint=recurrent_constraint,\n bias_constraint=bias_constraint,\n dropout=dropout,\n recurrent_dropout=recurrent_dropout,\n implementation=implementation,\n reset_after=reset_after)\n super(GRU, self).__init__(\n cell,\n return_sequences=return_sequences,\n return_state=return_state,\n go_backwards=go_backwards,\n stateful=stateful,\n unroll=unroll,\n **kwargs)\n self.activity_regularizer = regularizers.get(activity_regularizer)\n self.input_spec = [InputSpec(ndim=3)]\n\n def call(self, inputs, mask=None, training=None, initial_state=None):\n self.cell._dropout_mask = None\n self.cell._recurrent_dropout_mask = None\n return super(GRU, self).call(\n inputs, mask=mask, training=training, initial_state=initial_state)\n\n @property\n def units(self):\n return self.cell.units\n\n @property\n def activation(self):\n return self.cell.activation\n\n @property\n def recurrent_activation(self):\n return self.cell.recurrent_activation\n\n @property\n def use_bias(self):\n return self.cell.use_bias\n\n @property\n def kernel_initializer(self):\n return self.cell.kernel_initializer\n\n @property\n def recurrent_initializer(self):\n return self.cell.recurrent_initializer\n\n @property\n def bias_initializer(self):\n return self.cell.bias_initializer\n\n @property\n def kernel_regularizer(self):\n return self.cell.kernel_regularizer\n\n @property\n def recurrent_regularizer(self):\n return self.cell.recurrent_regularizer\n\n @property\n def bias_regularizer(self):\n return self.cell.bias_regularizer\n\n @property\n def kernel_constraint(self):\n return self.cell.kernel_constraint\n\n @property\n def recurrent_constraint(self):\n return self.cell.recurrent_constraint\n\n @property\n def bias_constraint(self):\n return self.cell.bias_constraint\n\n @property\n def dropout(self):\n return self.cell.dropout\n\n @property\n def recurrent_dropout(self):\n return self.cell.recurrent_dropout\n\n @property\n def implementation(self):\n return self.cell.implementation\n\n @property\n def reset_after(self):\n return self.cell.reset_after\n\n def get_config(self):\n config = {\n 'units':\n self.units,\n 'activation':\n activations.serialize(self.activation),\n 'recurrent_activation':\n activations.serialize(self.recurrent_activation),\n 'use_bias':\n self.use_bias,\n 'kernel_initializer':\n initializers.serialize(self.kernel_initializer),\n 'recurrent_initializer':\n initializers.serialize(self.recurrent_initializer),\n 'bias_initializer':\n initializers.serialize(self.bias_initializer),\n 'kernel_regularizer':\n regularizers.serialize(self.kernel_regularizer),\n 'recurrent_regularizer':\n regularizers.serialize(self.recurrent_regularizer),\n 'bias_regularizer':\n regularizers.serialize(self.bias_regularizer),\n 'activity_regularizer':\n regularizers.serialize(self.activity_regularizer),\n 'kernel_constraint':\n constraints.serialize(self.kernel_constraint),\n 'recurrent_constraint':\n constraints.serialize(self.recurrent_constraint),\n 'bias_constraint':\n constraints.serialize(self.bias_constraint),\n 'dropout':\n self.dropout,\n 'recurrent_dropout':\n self.recurrent_dropout,\n 'implementation':\n self.implementation,\n 'reset_after':\n self.reset_after\n }\n base_config = super(GRU, self).get_config()\n del base_config['cell']\n return dict(list(base_config.items()) + list(config.items()))\n\n @classmethod\n def from_config(cls, config):\n if 'implementation' in config and config['implementation'] == 0:\n config['implementation'] = 1\n return cls(**config)\n\n\n@keras_export('keras.layers.GRU', v1=[])\nclass UnifiedGRU(GRU):\n \"\"\"Gated Recurrent Unit - Cho et al. 2014.\n\n `UnifiedGRU` unifies the implementations between standard `GRU` layer and\n `CuDNNGRU` layer. Based on available runtime hardware and constraints,\n `UnifiedGRU` will choose different implementations to maximize the\n performance. For instance, if GPU is available and all the parameters meet the\n requirement of CuDNN kernel, `UnifiedGRU` will use CuDNN kernel for the\n calculation. The requirements to use CuDNN kernel are:\n\n 1. `activation` == 'tanh'\n 2. `recurrent_activation` == 'sigmoid'\n 3. `recurrent_dropout` == 0\n 4. `unroll` is False\n 5. `use_bias` is True\n 6. `reset_after` is True\n 7. Use masking in previous layers.\n\n There are two variants. The default one is based on\n [v3](https://arxiv.org/abs/1406.1078v3) and has reset gate applied to hidden\n state before matrix multiplication. The other one is based on\n [original](https://arxiv.org/abs/1406.1078v1) and has the order reversed.\n\n The second variant is compatible with CuDNNGRU (GPU-only) and allows\n inference on CPU. Thus it has separate biases for `kernel` and\n `recurrent_kernel`. Use `'reset_after'=True` and\n `recurrent_activation='sigmoid'`.\n\n Arguments:\n units: Positive integer, dimensionality of the output space.\n activation: Activation function to use.\n Default: hyperbolic tangent (`tanh`).\n If you pass `None`, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).\n recurrent_activation: Activation function to use\n for the recurrent step.\n Default: sigmoid (`sigmoid`).\n If you pass `None`, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).\n use_bias: Boolean, whether the layer uses a bias vector.\n kernel_initializer: Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs.\n recurrent_initializer: Initializer for the `recurrent_kernel`\n weights matrix,\n used for the linear transformation of the recurrent state.\n bias_initializer: Initializer for the bias vector.\n kernel_regularizer: Regularizer function applied to\n the `kernel` weights matrix.\n recurrent_regularizer: Regularizer function applied to\n the `recurrent_kernel` weights matrix.\n bias_regularizer: Regularizer function applied to the bias vector.\n activity_regularizer: Regularizer function applied to\n the output of the layer (its \"activation\")..\n kernel_constraint: Constraint function applied to\n the `kernel` weights matrix.\n recurrent_constraint: Constraint function applied to\n the `recurrent_kernel` weights matrix.\n bias_constraint: Constraint function applied to the bias vector.\n dropout: Float between 0 and 1.\n Fraction of the units to drop for\n the linear transformation of the inputs.\n recurrent_dropout: Float between 0 and 1.\n Fraction of the units to drop for\n the linear transformation of the recurrent state.\n implementation: Implementation mode, either 1 or 2.\n Mode 1 will structure its operations as a larger number of\n smaller dot products and additions, whereas mode 2 will\n batch them into fewer, larger operations. These modes will\n have different performance profiles on different hardware and\n for different applications.\n return_sequences: Boolean. Whether to return the last output\n in the output sequence, or the full sequence.\n return_state: Boolean. Whether to return the last state\n in addition to the output.\n go_backwards: Boolean (default False).\n If True, process the input sequence backwards and return the\n reversed sequence.\n stateful: Boolean (default False). If True, the last state\n for each sample at index i in a batch will be used as initial\n state for the sample of index i in the following batch.\n unroll: Boolean (default False).\n If True, the network will be unrolled,\n else a symbolic loop will be used.\n Unrolling can speed-up a RNN,\n although it tends to be more memory-intensive.\n Unrolling is only suitable for short sequences.\n reset_after: GRU convention (whether to apply reset gate after or\n before matrix multiplication). False = \"before\",\n True = \"after\" (default and CuDNN compatible).\n \"\"\"\n\n def __init__(self,\n units,\n activation='tanh',\n recurrent_activation='sigmoid',\n use_bias=True,\n kernel_initializer='glorot_uniform',\n recurrent_initializer='orthogonal',\n bias_initializer='zeros',\n kernel_regularizer=None,\n recurrent_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n recurrent_constraint=None,\n bias_constraint=None,\n dropout=0.,\n recurrent_dropout=0.,\n implementation=1,\n return_sequences=False,\n return_state=False,\n go_backwards=False,\n stateful=False,\n unroll=False,\n time_major=False,\n reset_after=True,\n **kwargs):\n # return_runtime is a flag for testing, which shows the real backend\n # implementation chosen by grappler in graph mode.\n self._return_runtime = kwargs.pop('return_runtime', False)\n\n super(UnifiedGRU, self).__init__(\n units,\n activation=activation,\n recurrent_activation=recurrent_activation,\n use_bias=use_bias,\n kernel_initializer=kernel_initializer,\n recurrent_initializer=recurrent_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=kernel_regularizer,\n recurrent_regularizer=recurrent_regularizer,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n kernel_constraint=kernel_constraint,\n recurrent_constraint=recurrent_constraint,\n bias_constraint=bias_constraint,\n dropout=dropout,\n recurrent_dropout=recurrent_dropout,\n implementation=implementation,\n return_sequences=return_sequences,\n return_state=return_state,\n go_backwards=go_backwards,\n stateful=stateful,\n unroll=unroll,\n time_major=time_major,\n reset_after=reset_after,\n **kwargs)\n self._dropout_mask = None\n # CuDNN uses following setting by default and not configurable.\n self.could_use_cudnn = (\n activation == 'tanh' and recurrent_activation == 'sigmoid' and\n recurrent_dropout == 0 and not unroll and use_bias and\n reset_after is True)\n\n def call(self, inputs, mask=None, training=None, initial_state=None):\n # GRU does not support constants. Ignore it during process.\n inputs, initial_state, _ = self._process_inputs(inputs, initial_state, None)\n\n if isinstance(mask, list):\n mask = mask[0]\n\n input_shape = K.int_shape(inputs)\n timesteps = input_shape[0] if self.time_major else input_shape[1]\n\n if mask is not None or not self.could_use_cudnn:\n # CuDNN does not support masking, fall back to use the normal GRU.\n kwargs = {'training': training}\n self.cell._dropout_mask = None\n self.cell._recurrent_dropout_mask = None\n\n def step(cell_inputs, cell_states):\n return self.cell.call(cell_inputs, cell_states, **kwargs)\n\n last_output, outputs, states = K.rnn(\n step,\n inputs,\n initial_state,\n constants=None,\n go_backwards=self.go_backwards,\n mask=mask,\n unroll=self.unroll,\n input_length=timesteps,\n time_major=self.time_major,\n zero_output_for_mask=self.zero_output_for_mask)\n # This is a dummy tensor for testing purpose.\n runtime = constant_op.constant(\n 'unknown', dtype=dtypes.string, name='runtime')\n else:\n last_output, outputs, runtime, states = self._defun_gru_call(\n inputs, initial_state, training)\n\n if self.stateful:\n updates = [state_ops.assign(self.states[0], states[0])]\n self.add_update(updates, inputs)\n\n if self.return_sequences:\n output = outputs\n else:\n output = last_output\n\n if self.return_state:\n return [output] + states\n elif self._return_runtime:\n return output, runtime\n else:\n return output\n\n def _defun_gru_call(self, inputs, initial_state, training):\n # Use the new defun approach for backend implementation swap.\n # Note that different implementations need to have same function\n # signature, eg, the tensor parameters need to have same shape and dtypes.\n if self.go_backwards:\n # Reverse time axis.\n inputs = K.reverse(inputs, 0 if self.time_major else 1)\n if 0 < self.dropout < 1:\n if self._dropout_mask is None:\n self._dropout_mask = _generate_dropout_mask(\n array_ops.ones_like(inputs),\n self.dropout,\n training=training,\n count=3)\n\n inputs *= self._dropout_mask[0]\n experimental_api_name = 'gru_' + str(uuid.uuid4())\n defun_standard_gru = _generate_defun_backend(\n experimental_api_name, _CPU_DEVICE_NAME, standard_gru)\n defun_cudnn_gru = _generate_defun_backend(\n experimental_api_name, _GPU_DEVICE_NAME, cudnn_gru)\n if ops.executing_eagerly_outside_functions():\n # Under eager context, the device placement is already known. Prefer the\n # GPU implementation when GPU is available.\n if context.num_gpus() > 0:\n last_output, outputs, new_h, runtime = defun_cudnn_gru(\n inputs=inputs,\n init_h=initial_state[0],\n kernel=self.cell.kernel,\n recurrent_kernel=self.cell.recurrent_kernel,\n bias=self.cell.bias,\n time_major=self.time_major)\n else:\n last_output, outputs, new_h, runtime = defun_standard_gru(\n inputs=inputs,\n init_h=initial_state[0],\n kernel=self.cell.kernel,\n recurrent_kernel=self.cell.recurrent_kernel,\n bias=self.cell.bias,\n activation=self.activation,\n recurrent_activation=self.recurrent_activation,\n time_major=self.time_major)\n else:\n # Call the normal GRU impl and register the CuDNN impl function. The\n # grappler will kick in during session execution to optimize the graph.\n last_output, outputs, new_h, runtime = defun_standard_gru(\n inputs=inputs,\n init_h=initial_state[0],\n kernel=self.cell.kernel,\n recurrent_kernel=self.cell.recurrent_kernel,\n bias=self.cell.bias,\n activation=self.activation,\n recurrent_activation=self.recurrent_activation,\n time_major=self.time_major)\n\n function.register(defun_cudnn_gru, inputs, initial_state[0],\n self.cell.kernel, self.cell.recurrent_kernel,\n self.cell.bias, self.time_major)\n states = [new_h]\n return last_output, outputs, runtime, states\n\n\ndef standard_gru(inputs, init_h, kernel, recurrent_kernel, bias, activation,\n recurrent_activation, time_major):\n \"\"\"GRU with standard kernel implementation.\n\n This implementation can be run on all types of hardware.\n\n This implementation lifts out all the layer weights and make them function\n parameters. It has same number of tensor input params as the CuDNN\n counterpart. The RNN step logic has been simplified, eg dropout and mask is\n removed since CuDNN implementation does not support that.\n\n Args:\n inputs: input tensor of GRU layer.\n init_h: initial state tensor for the cell output.\n kernel: weights for cell kernel.\n recurrent_kernel: weights for cell recurrent kernel.\n bias: weights for cell kernel bias and recurrent bias. The bias contains the\n combined input_bias and recurrent_bias.\n activation: Activation function to use for output.\n recurrent_activation: Activation function to use for hidden recurrent state.\n time_major: boolean, whether the inputs are in the format of\n [time, batch, feature] or [batch, time, feature].\n\n Returns:\n last_output: output tensor for the last timestep, which has shape\n [batch, units].\n outputs: output tensor for all timesteps, which has shape\n [batch, time, units].\n state_0: the cell output, which has same shape as init_h.\n runtime: constant string tensor which indicate real runtime hardware. This\n value is for testing purpose and should be used by user.\n \"\"\"\n input_shape = K.int_shape(inputs)\n timesteps = input_shape[0] if time_major else input_shape[1]\n\n input_bias, recurrent_bias = array_ops.unstack(bias)\n\n def step(cell_inputs, cell_states):\n \"\"\"Step function that will be used by Keras RNN backend.\"\"\"\n h_tm1 = cell_states[0]\n\n # inputs projected by all gate matrices at once\n matrix_x = K.dot(cell_inputs, kernel)\n matrix_x = K.bias_add(matrix_x, input_bias)\n\n x_z, x_r, x_h = array_ops.split(matrix_x, 3, axis=1)\n\n # hidden state projected by all gate matrices at once\n matrix_inner = K.dot(h_tm1, recurrent_kernel)\n matrix_inner = K.bias_add(matrix_inner, recurrent_bias)\n\n recurrent_z, recurrent_r, recurrent_h = array_ops.split(matrix_inner, 3,\n axis=1)\n z = recurrent_activation(x_z + recurrent_z)\n r = recurrent_activation(x_r + recurrent_r)\n hh = activation(x_h + r * recurrent_h)\n\n # previous and candidate state mixed by update gate\n h = z * h_tm1 + (1 - z) * hh\n return h, [h]\n\n last_output, outputs, new_states = K.rnn(\n step,\n inputs, [init_h],\n constants=None,\n unroll=False,\n time_major=time_major,\n input_length=timesteps)\n return last_output, outputs, new_states[0], constant_op.constant(\n 'cpu', dtype=dtypes.string, name='runtime')\n\n\ndef cudnn_gru(inputs, init_h, kernel, recurrent_kernel, bias, time_major):\n \"\"\"GRU with CuDNN implementation which is only available for GPU.\"\"\"\n if not time_major:\n inputs = array_ops.transpose(inputs, perm=(1, 0, 2))\n init_h = array_ops.expand_dims(init_h, axis=0)\n\n weights = array_ops.split(kernel, 3, axis=1)\n weights += array_ops.split(recurrent_kernel, 3, axis=1)\n # Note that the bias was initialized as shape (2, 3 * units), flat it into\n # (6 * units)\n bias = array_ops.split(K.flatten(bias), 6)\n # Note that the gate order for CuDNN is different from the canonical format.\n # canonical format is [z, r, h], whereas CuDNN is [r, z, h]. The swap need to\n # be done for kernel, recurrent_kernel, input_bias, recurrent_bias.\n # z is update gate weights.\n # r is reset gate weights.\n # h is output gate weights.\n weights[0], weights[1] = weights[1], weights[0]\n weights[3], weights[4] = weights[4], weights[3]\n bias[0], bias[1] = bias[1], bias[0]\n bias[3], bias[4] = bias[4], bias[3]\n\n params = _canonical_to_params(\n weights=weights,\n biases=bias,\n shape=constant_op.constant([-1]),\n transpose_weights=True)\n\n outputs, h, _, _ = gen_cudnn_rnn_ops.cudnn_rnn(\n inputs,\n input_h=init_h,\n input_c=0,\n params=params,\n is_training=True,\n rnn_mode='gru')\n last_output = outputs[-1]\n if not time_major:\n outputs = array_ops.transpose(outputs, perm=[1, 0, 2])\n h = h[0]\n return last_output, outputs, h, constant_op.constant(\n 'cudnn', dtype=dtypes.string, name='runtime')\n\n\n@keras_export('keras.layers.LSTMCell')\nclass LSTMCell(Layer):\n \"\"\"Cell class for the LSTM layer.\n\n Arguments:\n units: Positive integer, dimensionality of the output space.\n activation: Activation function to use.\n Default: hyperbolic tangent (`tanh`).\n If you pass `None`, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).\n recurrent_activation: Activation function to use\n for the recurrent step.\n Default: hard sigmoid (`hard_sigmoid`).\n If you pass `None`, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).\n use_bias: Boolean, whether the layer uses a bias vector.\n kernel_initializer: Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs.\n recurrent_initializer: Initializer for the `recurrent_kernel`\n weights matrix,\n used for the linear transformation of the recurrent state.\n bias_initializer: Initializer for the bias vector.\n unit_forget_bias: Boolean.\n If True, add 1 to the bias of the forget gate at initialization.\n Setting it to true will also force `bias_initializer=\"zeros\"`.\n This is recommended in [Jozefowicz et\n al.](http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf)\n kernel_regularizer: Regularizer function applied to\n the `kernel` weights matrix.\n recurrent_regularizer: Regularizer function applied to\n the `recurrent_kernel` weights matrix.\n bias_regularizer: Regularizer function applied to the bias vector.\n kernel_constraint: Constraint function applied to\n the `kernel` weights matrix.\n recurrent_constraint: Constraint function applied to\n the `recurrent_kernel` weights matrix.\n bias_constraint: Constraint function applied to the bias vector.\n dropout: Float between 0 and 1.\n Fraction of the units to drop for\n the linear transformation of the inputs.\n recurrent_dropout: Float between 0 and 1.\n Fraction of the units to drop for\n the linear transformation of the recurrent state.\n implementation: Implementation mode, either 1 or 2.\n Mode 1 will structure its operations as a larger number of\n smaller dot products and additions, whereas mode 2 will\n batch them into fewer, larger operations. These modes will\n have different performance profiles on different hardware and\n for different applications.\n \"\"\"\n\n def __init__(self,\n units,\n activation='tanh',\n recurrent_activation='hard_sigmoid',\n use_bias=True,\n kernel_initializer='glorot_uniform',\n recurrent_initializer='orthogonal',\n bias_initializer='zeros',\n unit_forget_bias=True,\n kernel_regularizer=None,\n recurrent_regularizer=None,\n bias_regularizer=None,\n kernel_constraint=None,\n recurrent_constraint=None,\n bias_constraint=None,\n dropout=0.,\n recurrent_dropout=0.,\n implementation=1,\n **kwargs):\n super(LSTMCell, self).__init__(**kwargs)\n self.units = units\n self.activation = activations.get(activation)\n self.recurrent_activation = activations.get(recurrent_activation)\n self.use_bias = use_bias\n\n self.kernel_initializer = initializers.get(kernel_initializer)\n self.recurrent_initializer = initializers.get(recurrent_initializer)\n self.bias_initializer = initializers.get(bias_initializer)\n self.unit_forget_bias = unit_forget_bias\n\n self.kernel_regularizer = regularizers.get(kernel_regularizer)\n self.recurrent_regularizer = regularizers.get(recurrent_regularizer)\n self.bias_regularizer = regularizers.get(bias_regularizer)\n\n self.kernel_constraint = constraints.get(kernel_constraint)\n self.recurrent_constraint = constraints.get(recurrent_constraint)\n self.bias_constraint = constraints.get(bias_constraint)\n\n self.dropout = min(1., max(0., dropout))\n self.recurrent_dropout = min(1., max(0., recurrent_dropout))\n self.implementation = implementation\n self.state_size = [self.units, self.units]\n self.output_size = self.units\n self._dropout_mask = None\n self._recurrent_dropout_mask = None\n\n @tf_utils.shape_type_conversion\n def build(self, input_shape):\n input_dim = input_shape[-1]\n self.kernel = self.add_weight(\n shape=(input_dim, self.units * 4),\n name='kernel',\n initializer=self.kernel_initializer,\n regularizer=self.kernel_regularizer,\n constraint=self.kernel_constraint)\n self.recurrent_kernel = self.add_weight(\n shape=(self.units, self.units * 4),\n name='recurrent_kernel',\n initializer=self.recurrent_initializer,\n regularizer=self.recurrent_regularizer,\n constraint=self.recurrent_constraint)\n\n if self.use_bias:\n if self.unit_forget_bias:\n\n def bias_initializer(_, *args, **kwargs):\n return K.concatenate([\n self.bias_initializer((self.units,), *args, **kwargs),\n initializers.Ones()((self.units,), *args, **kwargs),\n self.bias_initializer((self.units * 2,), *args, **kwargs),\n ])\n else:\n bias_initializer = self.bias_initializer\n self.bias = self.add_weight(\n shape=(self.units * 4,),\n name='bias',\n initializer=bias_initializer,\n regularizer=self.bias_regularizer,\n constraint=self.bias_constraint)\n else:\n self.bias = None\n self.built = True\n\n def _compute_carry_and_output(self, x, h_tm1, c_tm1):\n \"\"\"Computes carry and output using split kernels.\"\"\"\n x_i, x_f, x_c, x_o = x\n h_tm1_i, h_tm1_f, h_tm1_c, h_tm1_o = h_tm1\n i = self.recurrent_activation(\n x_i + K.dot(h_tm1_i, self.recurrent_kernel[:, :self.units]))\n f = self.recurrent_activation(x_f + K.dot(\n h_tm1_f, self.recurrent_kernel[:, self.units:self.units * 2]))\n c = f * c_tm1 + i * self.activation(x_c + K.dot(\n h_tm1_c, self.recurrent_kernel[:, self.units * 2:self.units * 3]))\n o = self.recurrent_activation(\n x_o + K.dot(h_tm1_o, self.recurrent_kernel[:, self.units * 3:]))\n return c, o\n\n def _compute_carry_and_output_fused(self, z, c_tm1):\n \"\"\"Computes carry and output using fused kernels.\"\"\"\n z0, z1, z2, z3 = z\n i = self.recurrent_activation(z0)\n f = self.recurrent_activation(z1)\n c = f * c_tm1 + i * self.activation(z2)\n o = self.recurrent_activation(z3)\n return c, o\n\n def call(self, inputs, states, training=None):\n if 0 < self.dropout < 1 and self._dropout_mask is None:\n self._dropout_mask = _generate_dropout_mask(\n array_ops.ones_like(inputs),\n self.dropout,\n training=training,\n count=4)\n if (0 < self.recurrent_dropout < 1 and\n self._recurrent_dropout_mask is None):\n self._recurrent_dropout_mask = _generate_dropout_mask(\n array_ops.ones_like(states[0]),\n self.recurrent_dropout,\n training=training,\n count=4)\n\n # dropout matrices for input units\n dp_mask = self._dropout_mask\n # dropout matrices for recurrent units\n rec_dp_mask = self._recurrent_dropout_mask\n\n h_tm1 = states[0] # previous memory state\n c_tm1 = states[1] # previous carry state\n\n if self.implementation == 1:\n if 0 < self.dropout < 1.:\n inputs_i = inputs * dp_mask[0]\n inputs_f = inputs * dp_mask[1]\n inputs_c = inputs * dp_mask[2]\n inputs_o = inputs * dp_mask[3]\n else:\n inputs_i = inputs\n inputs_f = inputs\n inputs_c = inputs\n inputs_o = inputs\n x_i = K.dot(inputs_i, self.kernel[:, :self.units])\n x_f = K.dot(inputs_f, self.kernel[:, self.units:self.units * 2])\n x_c = K.dot(inputs_c, self.kernel[:, self.units * 2:self.units * 3])\n x_o = K.dot(inputs_o, self.kernel[:, self.units * 3:])\n if self.use_bias:\n x_i = K.bias_add(x_i, self.bias[:self.units])\n x_f = K.bias_add(x_f, self.bias[self.units:self.units * 2])\n x_c = K.bias_add(x_c, self.bias[self.units * 2:self.units * 3])\n x_o = K.bias_add(x_o, self.bias[self.units * 3:])\n\n if 0 < self.recurrent_dropout < 1.:\n h_tm1_i = h_tm1 * rec_dp_mask[0]\n h_tm1_f = h_tm1 * rec_dp_mask[1]\n h_tm1_c = h_tm1 * rec_dp_mask[2]\n h_tm1_o = h_tm1 * rec_dp_mask[3]\n else:\n h_tm1_i = h_tm1\n h_tm1_f = h_tm1\n h_tm1_c = h_tm1\n h_tm1_o = h_tm1\n x = (x_i, x_f, x_c, x_o)\n h_tm1 = (h_tm1_i, h_tm1_f, h_tm1_c, h_tm1_o)\n c, o = self._compute_carry_and_output(x, h_tm1, c_tm1)\n else:\n if 0. < self.dropout < 1.:\n inputs *= dp_mask[0]\n z = K.dot(inputs, self.kernel)\n if 0. < self.recurrent_dropout < 1.:\n h_tm1 *= rec_dp_mask[0]\n z += K.dot(h_tm1, self.recurrent_kernel)\n if self.use_bias:\n z = K.bias_add(z, self.bias)\n\n z0 = z[:, :self.units]\n z1 = z[:, self.units:2 * self.units]\n z2 = z[:, 2 * self.units:3 * self.units]\n z3 = z[:, 3 * self.units:]\n\n z = (z0, z1, z2, z3)\n c, o = self._compute_carry_and_output_fused(z, c_tm1)\n\n h = o * self.activation(c)\n return h, [h, c]\n\n def get_config(self):\n config = {\n 'units':\n self.units,\n 'activation':\n activations.serialize(self.activation),\n 'recurrent_activation':\n activations.serialize(self.recurrent_activation),\n 'use_bias':\n self.use_bias,\n 'kernel_initializer':\n initializers.serialize(self.kernel_initializer),\n 'recurrent_initializer':\n initializers.serialize(self.recurrent_initializer),\n 'bias_initializer':\n initializers.serialize(self.bias_initializer),\n 'unit_forget_bias':\n self.unit_forget_bias,\n 'kernel_regularizer':\n regularizers.serialize(self.kernel_regularizer),\n 'recurrent_regularizer':\n regularizers.serialize(self.recurrent_regularizer),\n 'bias_regularizer':\n regularizers.serialize(self.bias_regularizer),\n 'kernel_constraint':\n constraints.serialize(self.kernel_constraint),\n 'recurrent_constraint':\n constraints.serialize(self.recurrent_constraint),\n 'bias_constraint':\n constraints.serialize(self.bias_constraint),\n 'dropout':\n self.dropout,\n 'recurrent_dropout':\n self.recurrent_dropout,\n 'implementation':\n self.implementation\n }\n base_config = super(LSTMCell, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n def get_initial_state(self, inputs=None, batch_size=None, dtype=None):\n return list(_generate_zero_filled_state_for_cell(\n self, inputs, batch_size, dtype))\n\n\n@keras_export('keras.experimental.PeepholeLSTMCell')\nclass PeepholeLSTMCell(LSTMCell):\n \"\"\"Equivalent to LSTMCell class but adds peephole connections.\n\n Peephole connections allow the gates to utilize the previous internal state as\n well as the previous hidden state (which is what LSTMCell is limited to).\n This allows PeepholeLSTMCell to better learn precise timings over LSTMCell.\n\n From [Gers et al.](http://www.jmlr.org/papers/volume3/gers02a/gers02a.pdf):\n\n \"We find that LSTM augmented by 'peephole connections' from its internal\n cells to its multiplicative gates can learn the fine distinction between\n sequences of spikes spaced either 50 or 49 time steps apart without the help\n of any short training exemplars.\"\n\n The peephole implementation is based on:\n\n https://research.google.com/pubs/archive/43905.pdf\n\n Hasim Sak, Andrew Senior, and Francoise Beaufays.\n \"Long short-term memory recurrent neural network architectures for\n large scale acoustic modeling.\" INTERSPEECH, 2014.\n\n Example:\n\n ```python\n # Create 2 PeepholeLSTMCells\n peephole_lstm_cells = [PeepholeLSTMCell(size) for size in [128, 256]]\n # Create a layer composed sequentially of the peephole LSTM cells.\n layer = RNN(peephole_lstm_cells)\n input = keras.Input((timesteps, input_dim))\n output = layer(input)\n ```\n \"\"\"\n\n def build(self, input_shape):\n super(PeepholeLSTMCell, self).build(input_shape)\n # The following are the weight matrices for the peephole connections. These\n # are multiplied with the previous internal state during the computation of\n # carry and output.\n self.input_gate_peephole_weights = self.add_weight(\n shape=(self.units,),\n name='input_gate_peephole_weights',\n initializer=self.kernel_initializer)\n self.forget_gate_peephole_weights = self.add_weight(\n shape=(self.units,),\n name='forget_gate_peephole_weights',\n initializer=self.kernel_initializer)\n self.output_gate_peephole_weights = self.add_weight(\n shape=(self.units,),\n name='output_gate_peephole_weights',\n initializer=self.kernel_initializer)\n\n def _compute_carry_and_output(self, x, h_tm1, c_tm1):\n x_i, x_f, x_c, x_o = x\n h_tm1_i, h_tm1_f, h_tm1_c, h_tm1_o = h_tm1\n i = self.recurrent_activation(\n x_i + K.dot(h_tm1_i, self.recurrent_kernel[:, :self.units]) +\n self.input_gate_peephole_weights * c_tm1)\n f = self.recurrent_activation(x_f + K.dot(\n h_tm1_f, self.recurrent_kernel[:, self.units:self.units * 2]) +\n self.forget_gate_peephole_weights * c_tm1)\n c = f * c_tm1 + i * self.activation(x_c + K.dot(\n h_tm1_c, self.recurrent_kernel[:, self.units * 2:self.units * 3]))\n o = self.recurrent_activation(\n x_o + K.dot(h_tm1_o, self.recurrent_kernel[:, self.units * 3:]) +\n self.output_gate_peephole_weights * c)\n return c, o\n\n def _compute_carry_and_output_fused(self, z, c_tm1):\n z0, z1, z2, z3 = z\n i = self.recurrent_activation(z0 +\n self.input_gate_peephole_weights * c_tm1)\n f = self.recurrent_activation(z1 +\n self.forget_gate_peephole_weights * c_tm1)\n c = f * c_tm1 + i * self.activation(z2)\n o = self.recurrent_activation(z3 + self.output_gate_peephole_weights * c)\n return c, o\n\n\n@keras_export(v1=['keras.layers.LSTM'])\nclass LSTM(RNN):\n \"\"\"Long Short-Term Memory layer - Hochreiter 1997.\n\n Note that this cell is not optimized for performance on GPU. Please use\n `tf.keras.layers.CuDNNLSTM` for better performance on GPU.\n\n Arguments:\n units: Positive integer, dimensionality of the output space.\n activation: Activation function to use.\n Default: hyperbolic tangent (`tanh`).\n If you pass `None`, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).\n recurrent_activation: Activation function to use\n for the recurrent step.\n Default: hard sigmoid (`hard_sigmoid`).\n If you pass `None`, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).\n use_bias: Boolean, whether the layer uses a bias vector.\n kernel_initializer: Initializer for the `kernel` weights matrix,\n used for the linear transformation of the inputs..\n recurrent_initializer: Initializer for the `recurrent_kernel`\n weights matrix,\n used for the linear transformation of the recurrent state..\n bias_initializer: Initializer for the bias vector.\n unit_forget_bias: Boolean.\n If True, add 1 to the bias of the forget gate at initialization.\n Setting it to true will also force `bias_initializer=\"zeros\"`.\n This is recommended in [Jozefowicz et\n al.](http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf)\n kernel_regularizer: Regularizer function applied to\n the `kernel` weights matrix.\n recurrent_regularizer: Regularizer function applied to\n the `recurrent_kernel` weights matrix.\n bias_regularizer: Regularizer function applied to the bias vector.\n activity_regularizer: Regularizer function applied to\n the output of the layer (its \"activation\")..\n kernel_constraint: Constraint function applied to\n the `kernel` weights matrix.\n recurrent_constraint: Constraint function applied to\n the `recurrent_kernel` weights matrix.\n bias_constraint: Constraint function applied to the bias vector.\n dropout: Float between 0 and 1.\n Fraction of the units to drop for\n the linear transformation of the inputs.\n recurrent_dropout: Float between 0 and 1.\n Fraction of the units to drop for\n the linear transformation of the recurrent state.\n implementation: Implementation mode, either 1 or 2.\n Mode 1 will structure its operations as a larger number of\n smaller dot products and additions, whereas mode 2 will\n batch them into fewer, larger operations. These modes will\n have different performance profiles on different hardware and\n for different applications.\n return_sequences: Boolean. Whether to return the last output.\n in the output sequence, or the full sequence.\n return_state: Boolean. Whether to return the last state\n in addition to the output.\n go_backwards: Boolean (default False).\n If True, process the input sequence backwards and return the\n reversed sequence.\n stateful: Boolean (default False). If True, the last state\n for each sample at index i in a batch will be used as initial\n state for the sample of index i in the following batch.\n unroll: Boolean (default False).\n If True, the network will be unrolled,\n else a symbolic loop will be used.\n Unrolling can speed-up a RNN,\n although it tends to be more memory-intensive.\n Unrolling is only suitable for short sequences.\n\n \"\"\"\n\n def __init__(self,\n units,\n activation='tanh',\n recurrent_activation='hard_sigmoid',\n use_bias=True,\n kernel_initializer='glorot_uniform',\n recurrent_initializer='orthogonal',\n bias_initializer='zeros',\n unit_forget_bias=True,\n kernel_regularizer=None,\n recurrent_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n recurrent_constraint=None,\n bias_constraint=None,\n dropout=0.,\n recurrent_dropout=0.,\n implementation=1,\n return_sequences=False,\n return_state=False,\n go_backwards=False,\n stateful=False,\n unroll=False,\n **kwargs):\n if implementation == 0:\n logging.warning('`implementation=0` has been deprecated, '\n 'and now defaults to `implementation=1`.'\n 'Please update your layer call.')\n if context.executing_eagerly() and context.num_gpus() > 0:\n logging.warn('%s: Note that this layer is not optimized for performance. '\n 'Please use tf.keras.layers.CuDNNLSTM for better '\n 'performance on GPU.', self)\n cell = LSTMCell(\n units,\n activation=activation,\n recurrent_activation=recurrent_activation,\n use_bias=use_bias,\n kernel_initializer=kernel_initializer,\n recurrent_initializer=recurrent_initializer,\n unit_forget_bias=unit_forget_bias,\n bias_initializer=bias_initializer,\n kernel_regularizer=kernel_regularizer,\n recurrent_regularizer=recurrent_regularizer,\n bias_regularizer=bias_regularizer,\n kernel_constraint=kernel_constraint,\n recurrent_constraint=recurrent_constraint,\n bias_constraint=bias_constraint,\n dropout=dropout,\n recurrent_dropout=recurrent_dropout,\n implementation=implementation)\n super(LSTM, self).__init__(\n cell,\n return_sequences=return_sequences,\n return_state=return_state,\n go_backwards=go_backwards,\n stateful=stateful,\n unroll=unroll,\n **kwargs)\n self.activity_regularizer = regularizers.get(activity_regularizer)\n self.input_spec = [InputSpec(ndim=3)]\n\n def call(self, inputs, mask=None, training=None, initial_state=None):\n self.cell._dropout_mask = None\n self.cell._recurrent_dropout_mask = None\n return super(LSTM, self).call(\n inputs, mask=mask, training=training, initial_state=initial_state)\n\n @property\n def units(self):\n return self.cell.units\n\n @property\n def activation(self):\n return self.cell.activation\n\n @property\n def recurrent_activation(self):\n return self.cell.recurrent_activation\n\n @property\n def use_bias(self):\n return self.cell.use_bias\n\n @property\n def kernel_initializer(self):\n return self.cell.kernel_initializer\n\n @property\n def recurrent_initializer(self):\n return self.cell.recurrent_initializer\n\n @property\n def bias_initializer(self):\n return self.cell.bias_initializer\n\n @property\n def unit_forget_bias(self):\n return self.cell.unit_forget_bias\n\n @property\n def kernel_regularizer(self):\n return self.cell.kernel_regularizer\n\n @property\n def recurrent_regularizer(self):\n return self.cell.recurrent_regularizer\n\n @property\n def bias_regularizer(self):\n return self.cell.bias_regularizer\n\n @property\n def kernel_constraint(self):\n return self.cell.kernel_constraint\n\n @property\n def recurrent_constraint(self):\n return self.cell.recurrent_constraint\n\n @property\n def bias_constraint(self):\n return self.cell.bias_constraint\n\n @property\n def dropout(self):\n return self.cell.dropout\n\n @property\n def recurrent_dropout(self):\n return self.cell.recurrent_dropout\n\n @property\n def implementation(self):\n return self.cell.implementation\n\n def get_config(self):\n config = {\n 'units':\n self.units,\n 'activation':\n activations.serialize(self.activation),\n 'recurrent_activation':\n activations.serialize(self.recurrent_activation),\n 'use_bias':\n self.use_bias,\n 'kernel_initializer':\n initializers.serialize(self.kernel_initializer),\n 'recurrent_initializer':\n initializers.serialize(self.recurrent_initializer),\n 'bias_initializer':\n initializers.serialize(self.bias_initializer),\n 'unit_forget_bias':\n self.unit_forget_bias,\n 'kernel_regularizer':\n regularizers.serialize(self.kernel_regularizer),\n 'recurrent_regularizer':\n regularizers.serialize(self.recurrent_regularizer),\n 'bias_regularizer':\n regularizers.serialize(self.bias_regularizer),\n 'activity_regularizer':\n regularizers.serialize(self.activity_regularizer),\n 'kernel_constraint':\n constraints.serialize(self.kernel_constraint),\n 'recurrent_constraint':\n constraints.serialize(self.recurrent_constraint),\n 'bias_constraint':\n constraints.serialize(self.bias_constraint),\n 'dropout':\n self.dropout,\n 'recurrent_dropout':\n self.recurrent_dropout,\n 'implementation':\n self.implementation\n }\n base_config = super(LSTM, self).get_config()\n del base_config['cell']\n return dict(list(base_config.items()) + list(config.items()))\n\n @classmethod\n def from_config(cls, config):\n if 'implementation' in config and config['implementation'] == 0:\n config['implementation'] = 1\n return cls(**config)\n\n\n@keras_export('keras.layers.LSTM', v1=[])\nclass UnifiedLSTM(LSTM):\n \"\"\"Long Short-Term Memory layer - Hochreiter 1997.\n\n `UnifiedLSTM` unifies the implementations between standard `LSTM` layer and\n `CuDNNLSTM` layer. Based on available runtime hardware and constrains,\n `UnifiedLSTM` will choose different implementations to maximize the\n performance. For instance, if GPU is available and all the parameters meet the\n requirement of CuDNN kernel, `UnifiedLSTM` will use CuDNN kernel for the\n calculation.\n\n Arguments:\n units: Positive integer, dimensionality of the output space.\n activation: Activation function to use.\n Default: hyperbolic tangent (`tanh`). If you pass `None`, no activation\n is applied (ie. \"linear\" activation: `a(x) = x`).\n recurrent_activation: Activation function to use for the recurrent step.\n Default: sigmoid (`sigmoid`). If you pass `None`, no activation is\n applied (ie. \"linear\" activation: `a(x) = x`).\n use_bias: Boolean, whether the layer uses a bias vector.\n kernel_initializer: Initializer for the `kernel` weights matrix, used for\n the linear transformation of the inputs..\n recurrent_initializer: Initializer for the `recurrent_kernel` weights\n matrix, used for the linear transformation of the recurrent state..\n bias_initializer: Initializer for the bias vector.\n unit_forget_bias: Boolean. If True, add 1 to the bias of the forget gate at\n initialization. Setting it to true will also force\n `bias_initializer=\"zeros\"`. This is recommended in [Jozefowicz et\n al.](http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf)\n kernel_regularizer: Regularizer function applied to the `kernel` weights\n matrix.\n recurrent_regularizer: Regularizer function applied to the\n `recurrent_kernel` weights matrix.\n bias_regularizer: Regularizer function applied to the bias vector.\n activity_regularizer: Regularizer function applied to the output of the\n layer (its \"activation\")..\n kernel_constraint: Constraint function applied to the `kernel` weights\n matrix.\n recurrent_constraint: Constraint function applied to the `recurrent_kernel`\n weights matrix.\n bias_constraint: Constraint function applied to the bias vector.\n dropout: Float between 0 and 1. Fraction of the units to drop for the linear\n transformation of the inputs.\n recurrent_dropout: Float between 0 and 1. Fraction of the units to drop for\n the linear transformation of the recurrent state.\n implementation: Implementation mode, either 1 or 2. Mode 1 will structure\n its operations as a larger number of smaller dot products and additions,\n whereas mode 2 will batch them into fewer, larger operations. These modes\n will have different performance profiles on different hardware and for\n different applications.\n return_sequences: Boolean. Whether to return the last output. in the output\n sequence, or the full sequence.\n return_state: Boolean. Whether to return the last state in addition to the\n output.\n go_backwards: Boolean (default False). If True, process the input sequence\n backwards and return the reversed sequence.\n stateful: Boolean (default False). If True, the last state for each sample\n at index i in a batch will be used as initial state for the sample of\n index i in the following batch.\n unroll: Boolean (default False). If True, the network will be unrolled, else\n a symbolic loop will be used. Unrolling can speed-up a RNN, although it\n tends to be more memory-intensive. Unrolling is only suitable for short\n sequences.\n \"\"\"\n\n def __init__(self,\n units,\n activation='tanh',\n recurrent_activation='sigmoid',\n use_bias=True,\n kernel_initializer='glorot_uniform',\n recurrent_initializer='orthogonal',\n bias_initializer='zeros',\n unit_forget_bias=True,\n kernel_regularizer=None,\n recurrent_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n recurrent_constraint=None,\n bias_constraint=None,\n dropout=0.,\n recurrent_dropout=0.,\n implementation=1,\n return_sequences=False,\n return_state=False,\n go_backwards=False,\n stateful=False,\n time_major=False,\n unroll=False,\n **kwargs):\n # return_runtime is a flag for testing, which shows the real backend\n # implementation chosen by grappler in graph mode.\n self.return_runtime = kwargs.pop('return_runtime', False)\n\n super(UnifiedLSTM, self).__init__(\n units,\n activation=activation,\n recurrent_activation=recurrent_activation,\n use_bias=use_bias,\n kernel_initializer=kernel_initializer,\n recurrent_initializer=recurrent_initializer,\n bias_initializer=bias_initializer,\n unit_forget_bias=unit_forget_bias,\n kernel_regularizer=kernel_regularizer,\n recurrent_regularizer=recurrent_regularizer,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n kernel_constraint=kernel_constraint,\n recurrent_constraint=recurrent_constraint,\n bias_constraint=bias_constraint,\n dropout=dropout,\n recurrent_dropout=recurrent_dropout,\n implementation=implementation,\n return_sequences=return_sequences,\n return_state=return_state,\n go_backwards=go_backwards,\n stateful=stateful,\n time_major=time_major,\n unroll=unroll,\n **kwargs)\n\n self.state_spec = [\n InputSpec(shape=(None, dim)) for dim in (self.units, self.units)\n ]\n self._dropout_mask = None\n self.could_use_cudnn = (\n activation == 'tanh' and recurrent_activation == 'sigmoid' and\n recurrent_dropout == 0 and not unroll and use_bias)\n\n def call(self, inputs, mask=None, training=None, initial_state=None):\n # LSTM does not support constants. Ignore it during process.\n inputs, initial_state, _ = self._process_inputs(inputs, initial_state, None)\n\n if isinstance(mask, list):\n mask = mask[0]\n\n input_shape = K.int_shape(inputs)\n timesteps = input_shape[0] if self.time_major else input_shape[1]\n\n if mask is not None or not self.could_use_cudnn:\n # CuDNN does not support masking, fall back to use the normal LSTM.\n kwargs = {'training': training}\n\n def step(inputs, states):\n return self.cell.call(inputs, states, **kwargs)\n\n last_output, outputs, states = K.rnn(\n step,\n inputs,\n initial_state,\n constants=None,\n go_backwards=self.go_backwards,\n mask=mask,\n unroll=self.unroll,\n input_length=timesteps,\n time_major=self.time_major,\n zero_output_for_mask=self.zero_output_for_mask)\n runtime = constant_op.constant(\n 'unknown', dtype=dtypes.string, name='runtime')\n else:\n # Use the new defun approach for backend implementation swap.\n # Note that different implementations need to have same function\n # signature, eg, the tensor parameters need to have same shape and dtypes.\n # Since the CuDNN has an extra set of bias, those bias will be passed to\n # both normal and CuDNN implementations.\n if self.go_backwards:\n # Reverse time axis.\n inputs = K.reverse(inputs, 0 if self.time_major else 1)\n\n if 0 < self.dropout < 1:\n if self._dropout_mask is None:\n self._dropout_mask = _generate_dropout_mask(\n array_ops.ones_like(inputs),\n self.dropout,\n training=training,\n count=4)\n\n inputs *= self._dropout_mask[0]\n\n # Each time a defun function is called, we will give a unique identifiable\n # API name, so that the grappler won't get confused when it sees multiple\n # LSTM layer added into same graph, and it will be able to pair up the\n # different implementations across them.\n experimental_api_name = 'lstm_' + str(uuid.uuid4())\n defun_standard_lstm = _generate_defun_backend(\n experimental_api_name, _CPU_DEVICE_NAME, standard_lstm)\n defun_cudnn_lstm = _generate_defun_backend(\n experimental_api_name, _GPU_DEVICE_NAME, cudnn_lstm)\n\n if ops.executing_eagerly_outside_functions():\n # Under eager context, the device placement is already known. Prefer the\n # GPU implementation here.\n if context.num_gpus() > 0:\n last_output, outputs, new_h, new_c, runtime = defun_cudnn_lstm(\n inputs, initial_state[0], initial_state[1], self.cell.kernel,\n self.cell.recurrent_kernel, self.cell.bias, self.time_major)\n else:\n last_output, outputs, new_h, new_c, runtime = defun_standard_lstm(\n inputs, initial_state[0], initial_state[1], self.cell.kernel,\n self.cell.recurrent_kernel, self.cell.bias, self.activation,\n self.recurrent_activation, self.time_major)\n else:\n # Call the normal LSTM impl and register the CuDNN impl function. The\n # grappler will kick in during session execution to optimize the graph.\n last_output, outputs, new_h, new_c, runtime = defun_standard_lstm(\n inputs, initial_state[0], initial_state[1], self.cell.kernel,\n self.cell.recurrent_kernel, self.cell.bias, self.activation,\n self.recurrent_activation, self.time_major)\n\n function.register(defun_cudnn_lstm, inputs, initial_state[0],\n initial_state[1], self.cell.kernel,\n self.cell.recurrent_kernel, self.cell.bias,\n self.time_major)\n states = [new_h, new_c]\n\n if self.stateful:\n updates = []\n for i in range(len(states)):\n updates.append(state_ops.assign(self.states[i], states[i]))\n self.add_update(updates, inputs)\n\n if self.return_sequences:\n output = outputs\n else:\n output = last_output\n\n if self.return_state:\n return [output] + states\n elif self.return_runtime:\n return output, runtime\n else:\n return output\n\n\ndef _canonical_to_params(weights, biases, shape, transpose_weights=False):\n \"\"\"Utility function convert variable to CuDNN compatible parameter.\n\n Note that Keras weights for kernels are different from the CuDNN format. Eg.:\n\n ```\n Keras CuDNN\n [[0, 1, 2], <---> [[0, 2, 4],\n [3, 4, 5]] [1, 3, 5]]\n ```\n\n If the input weights need to be in a unified format, then set\n `transpose_weights=True` to convert the weights.\n\n Args:\n weights: list of weights for the individual kernels and recurrent kernels.\n biases: list of biases for individual gate.\n shape: the shape for the converted variables that will be feed to CuDNN.\n transpose_weights: boolean, whether to transpose the weights.\n\n Returns:\n The converted weights that can be feed to CuDNN ops as param.\n \"\"\"\n def convert(w):\n return array_ops.transpose(w) if transpose_weights else w\n\n weights = [array_ops.reshape(convert(x), shape) for x in weights]\n biases = [array_ops.reshape(x, shape) for x in biases]\n return array_ops.concat(weights + biases, axis=0)\n\n\ndef standard_lstm(inputs, init_h, init_c, kernel, recurrent_kernel, bias,\n activation, recurrent_activation, time_major):\n \"\"\"LSTM with standard kernel implementation.\n\n This implementation can be run on all types for hardware.\n\n This implementation lifts out all the layer weights and make them function\n parameters. It has same number of tensor input params as the CuDNN\n counterpart. The RNN step logic has been simplified, eg dropout and mask is\n removed since CuDNN implementation does not support that.\n\n Note that the first half of the bias tensor should be ignored by this impl.\n The CuDNN impl need an extra set of input gate bias. In order to make the both\n function take same shape of parameter, that extra set of bias is also feed\n here.\n\n Args:\n inputs: input tensor of LSTM layer.\n init_h: initial state tensor for the cell output.\n init_c: initial state tensor for the cell hidden state.\n kernel: weights for cell kernel.\n recurrent_kernel: weights for cell recurrent kernel.\n bias: weights for cell kernel bias and recurrent bias. Only recurrent bias\n is used in this case.\n activation: Activation function to use for output.\n recurrent_activation: Activation function to use for hidden recurrent state.\n time_major: boolean, whether the inputs are in the format of\n [time, batch, feature] or [batch, time, feature].\n\n Returns:\n last_output: output tensor for the last timestep, which has shape\n [batch, units].\n outputs: output tensor for all timesteps, which has shape\n [batch, time, units].\n state_0: the cell output, which has same shape as init_h.\n state_1: the cell hidden state, which has same shape as init_c.\n runtime: constant string tensor which indicate real runtime hardware. This\n value is for testing purpose and should be used by user.\n \"\"\"\n input_shape = K.int_shape(inputs)\n timesteps = input_shape[0] if time_major else input_shape[1]\n\n def step(cell_inputs, cell_states):\n \"\"\"Step function that will be used by Keras RNN backend.\"\"\"\n h_tm1 = cell_states[0] # previous memory state\n c_tm1 = cell_states[1] # previous carry state\n\n z = K.dot(cell_inputs, kernel)\n z += K.dot(h_tm1, recurrent_kernel)\n z = K.bias_add(z, bias)\n\n z0, z1, z2, z3 = array_ops.split(z, 4, axis=1)\n\n i = recurrent_activation(z0)\n f = recurrent_activation(z1)\n c = f * c_tm1 + i * activation(z2)\n o = recurrent_activation(z3)\n\n h = o * activation(c)\n return h, [h, c]\n\n last_output, outputs, new_states = K.rnn(\n step,\n inputs, [init_h, init_c],\n constants=None,\n unroll=False,\n time_major=time_major,\n input_length=timesteps)\n return last_output, outputs, new_states[0], new_states[\n 1], constant_op.constant('cpu', dtype=dtypes.string, name='runtime')\n\n\ndef cudnn_lstm(inputs, input_h, input_c, kernel, recurrent_kernel, bias,\n time_major):\n \"\"\"LSTM with CuDNN implementation which is only available for GPU.\"\"\"\n if not time_major:\n inputs = array_ops.transpose(inputs, perm=(1, 0, 2))\n input_h = array_ops.expand_dims(input_h, axis=0)\n input_c = array_ops.expand_dims(input_c, axis=0)\n\n weights = array_ops.split(kernel, 4, axis=1)\n weights += array_ops.split(recurrent_kernel, 4, axis=1)\n # CuDNN has an extra set of bias for inputs, we disable them (setting to 0),\n # so that mathematically it is same as the canonical LSTM implementation.\n full_bias = array_ops.concat((array_ops.zeros_like(bias), bias), 0)\n\n params = _canonical_to_params(\n weights=weights,\n biases=array_ops.split(full_bias, 8),\n shape=constant_op.constant([-1]),\n transpose_weights=True)\n\n outputs, h, c, _ = gen_cudnn_rnn_ops.cudnn_rnn(\n inputs, input_h=input_h, input_c=input_c, params=params, is_training=True)\n last_output = outputs[-1]\n if not time_major:\n outputs = array_ops.transpose(outputs, perm=[1, 0, 2])\n h = h[0]\n c = c[0]\n\n return last_output, outputs, h, c, constant_op.constant(\n 'cudnn', dtype=dtypes.string, name='runtime')\n\n\ndef _generate_dropout_mask(ones, rate, training=None, count=1):\n def dropped_inputs():\n return K.dropout(ones, rate)\n\n if count > 1:\n return [\n K.in_train_phase(dropped_inputs, ones, training=training)\n for _ in range(count)\n ]\n return K.in_train_phase(dropped_inputs, ones, training=training)\n\n\ndef _standardize_args(\n inputs, initial_state, constants, num_constants, num_inputs=1):\n \"\"\"Standardizes `__call__` to a single list of tensor inputs.\n\n When running a model loaded from a file, the input tensors\n `initial_state` and `constants` can be passed to `RNN.__call__()` as part\n of `inputs` instead of by the dedicated keyword arguments. This method\n makes sure the arguments are separated and that `initial_state` and\n `constants` are lists of tensors (or None).\n\n Arguments:\n inputs: Tensor or list/tuple of tensors. which may include constants\n and initial states. In that case `num_constant` must be specified.\n initial_state: Tensor or list of tensors or None, initial states.\n constants: Tensor or list of tensors or None, constant tensors.\n num_constants: Expected number of constants (if constants are passed as\n part of the `inputs` list.\n num_inputs: Expected number of real input tensors (exclude initial_states\n and constants).\n\n Returns:\n inputs: Single tensor or tuple of tensors.\n initial_state: List of tensors or None.\n constants: List of tensors or None.\n \"\"\"\n if isinstance(inputs, list):\n # There are several situations here:\n # In the graph mode, __call__ will be only called once. The initial_state\n # and constants could be in inputs (from file loading).\n # In the eager mode, __call__ will be called twice, once during\n # rnn_layer(inputs=input_t, constants=c_t, ...), and second time will be\n # model.fit/train_on_batch/predict with real np data. In the second case,\n # the inputs will contain initial_state and constants, and more importantly,\n # the real inputs will be in a flat list, instead of nested tuple.\n #\n # For either case, we will use num_inputs to split the input list, and\n # restructure the real input into tuple.\n assert initial_state is None and constants is None\n inputs = nest.flatten(inputs)\n if num_constants is not None:\n constants = inputs[-num_constants:]\n inputs = inputs[:-num_constants]\n if num_inputs is None:\n num_inputs = 1\n if len(inputs) > num_inputs:\n initial_state = inputs[num_inputs:]\n inputs = inputs[:num_inputs]\n\n if len(inputs) > 1:\n inputs = tuple(inputs)\n else:\n inputs = inputs[0]\n\n def to_list_or_none(x):\n if x is None or isinstance(x, list):\n return x\n if isinstance(x, tuple):\n return list(x)\n return [x]\n\n initial_state = to_list_or_none(initial_state)\n constants = to_list_or_none(constants)\n\n return inputs, initial_state, constants\n\n\ndef _is_multiple_state(state_size):\n \"\"\"Check whether the state_size contains multiple states.\"\"\"\n return (hasattr(state_size, '__len__') and\n not isinstance(state_size, tensor_shape.TensorShape))\n\n\ndef _generate_zero_filled_state_for_cell(cell, inputs, batch_size, dtype):\n if inputs is not None:\n batch_size = array_ops.shape(inputs)[0]\n dtype = inputs.dtype\n return _generate_zero_filled_state(batch_size, cell.state_size, dtype)\n\n\ndef _generate_zero_filled_state(batch_size_tensor, state_size, dtype):\n \"\"\"Generate a zero filled tensor with shape [batch_size, state_size].\"\"\"\n if batch_size_tensor is None or dtype is None:\n raise ValueError(\n 'batch_size and dtype cannot be None while constructing initial state: '\n 'batch_size={}, dtype={}'.format(batch_size_tensor, dtype))\n\n def create_zeros(unnested_state_size):\n flat_dims = tensor_shape.as_shape(unnested_state_size).as_list()\n init_state_size = [batch_size_tensor] + flat_dims\n return array_ops.zeros(init_state_size, dtype=dtype)\n\n if nest.is_sequence(state_size):\n return nest.map_structure(create_zeros, state_size)\n else:\n return create_zeros(state_size)\n\n\ndef _generate_defun_backend(unique_api_name, preferred_device, func):\n function_attributes = {\n _DEFUN_API_NAME_ATTRIBUTE: unique_api_name,\n _DEFUN_DEVICE_ATTRIBUTE: preferred_device,\n }\n return function.defun_with_attributes(func=func,\n attributes=function_attributes)\n", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Script to test TF-TRT INT8 conversion without calibration on Mnist model.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.contrib.tensorrt.python import trt_convert\n# pylint: disable=unused-import\nfrom tensorflow.contrib.tensorrt.python.ops import trt_engine_op\n# pylint: enable=unused-import\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.python import data\nfrom tensorflow.python import keras\nfrom tensorflow.python.estimator.estimator import Estimator\nfrom tensorflow.python.estimator.model_fn import EstimatorSpec\nfrom tensorflow.python.estimator.model_fn import ModeKeys\nfrom tensorflow.python.estimator.run_config import RunConfig\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import graph_util\nfrom tensorflow.python.framework import importer\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.keras.datasets import mnist\nfrom tensorflow.python.layers import layers\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gen_array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import metrics\nfrom tensorflow.python.ops import nn\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops.losses import losses\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.summary import summary\nfrom tensorflow.python.training import saver\nfrom tensorflow.python.training.adam import AdamOptimizer\nfrom tensorflow.python.training.checkpoint_management import latest_checkpoint\nfrom tensorflow.python.training.training_util import get_global_step\n\nINPUT_NODE_NAME = 'input'\nOUTPUT_NODE_NAME = 'output'\n\n\nclass QuantizationAwareTrainingMNISTTest(test_util.TensorFlowTestCase):\n\n def _BuildGraph(self, x):\n\n def _Quantize(x, r):\n x = gen_array_ops.quantize_and_dequantize_v2(x, -r, r)\n return x\n\n def _DenseLayer(x, num_inputs, num_outputs, quantization_range, name):\n \"\"\"Dense layer with quantized outputs.\n\n Args:\n x: input to the dense layer\n num_inputs: number of input columns of x\n num_outputs: number of output columns\n quantization_range: the min/max range for quantization\n name: name of the variable scope\n\n Returns:\n The output of the layer.\n \"\"\"\n with variable_scope.variable_scope(name):\n kernel = variable_scope.get_variable(\n 'kernel',\n shape=[num_inputs, num_outputs],\n dtype=dtypes.float32,\n initializer=keras.initializers.glorot_uniform())\n bias = variable_scope.get_variable(\n 'bias',\n shape=[num_outputs],\n dtype=dtypes.float32,\n initializer=keras.initializers.zeros())\n x = math_ops.matmul(x, kernel)\n x = _Quantize(x, quantization_range)\n x = nn.bias_add(x, bias)\n x = _Quantize(x, quantization_range)\n return x\n\n x = _Quantize(x, 1)\n # Conv + Bias + Relu6\n x = layers.conv2d(x, filters=32, kernel_size=3, use_bias=True)\n x = nn.relu6(x)\n # Conv + Bias + Relu6\n x = layers.conv2d(x, filters=64, kernel_size=3, use_bias=True)\n x = nn.relu6(x)\n # Reduce\n x = math_ops.reduce_mean(x, [1, 2])\n x = _Quantize(x, 6)\n # FC1\n x = _DenseLayer(x, 64, 512, 6, name='dense')\n x = nn.relu6(x)\n # FC2\n x = _DenseLayer(x, 512, 10, 25, name='dense_1')\n x = array_ops.identity(x, name=OUTPUT_NODE_NAME)\n return x\n\n def _GetGraphDef(self, use_trt, max_batch_size, model_dir):\n \"\"\"Get the frozen mnist GraphDef.\n\n Args:\n use_trt: whether use TF-TRT to convert the graph.\n max_batch_size: the max batch size to apply during TF-TRT conversion.\n model_dir: the model directory to load the checkpoints.\n\n Returns:\n The frozen mnist GraphDef.\n \"\"\"\n graph = ops.Graph()\n with self.session(graph=graph) as sess:\n with graph.device('/GPU:0'):\n x = array_ops.placeholder(\n shape=(None, 28, 28, 1), dtype=dtypes.float32, name=INPUT_NODE_NAME)\n self._BuildGraph(x)\n # Load weights\n mnist_saver = saver.Saver()\n checkpoint_file = latest_checkpoint(model_dir)\n mnist_saver.restore(sess, checkpoint_file)\n # Freeze\n graph_def = graph_util.convert_variables_to_constants(\n sess, sess.graph_def, output_node_names=[OUTPUT_NODE_NAME])\n # Convert with TF-TRT\n if use_trt:\n logging.info('Number of nodes before TF-TRT conversion: %d',\n len(graph_def.node))\n graph_def = trt_convert.create_inference_graph(\n graph_def,\n outputs=[OUTPUT_NODE_NAME],\n max_batch_size=max_batch_size,\n precision_mode='INT8',\n # There is a 2GB GPU memory limit for each test, so we set\n # max_workspace_size_bytes to 256MB to leave enough room for TF\n # runtime to allocate GPU memory.\n max_workspace_size_bytes=1 << 28,\n minimum_segment_size=2,\n use_calibration=False,\n )\n logging.info('Number of nodes after TF-TRT conversion: %d',\n len(graph_def.node))\n num_engines = len(\n [1 for n in graph_def.node if str(n.op) == 'TRTEngineOp'])\n self.assertEqual(1, num_engines)\n return graph_def\n\n def _Run(self, is_training, use_trt, batch_size, num_epochs, model_dir):\n \"\"\"Train or evaluate the model.\n\n Args:\n is_training: whether to train or evaluate the model. In training mode,\n quantization will be simulated where the quantize_and_dequantize_v2 are\n placed.\n use_trt: if true, use TRT INT8 mode for evaluation, which will perform\n real quantization. Otherwise use native TensorFlow which will perform\n simulated quantization. Ignored if is_training is True.\n batch_size: batch size.\n num_epochs: how many epochs to train. Ignored if is_training is False.\n model_dir: where to save or load checkpoint.\n\n Returns:\n The Estimator evaluation result.\n \"\"\"\n # Get dataset\n train_data, test_data = mnist.load_data()\n\n def _PreprocessFn(x, y):\n x = math_ops.cast(x, dtypes.float32)\n x = array_ops.expand_dims(x, axis=2)\n x = 2.0 * (x / 255.0) - 1.0\n y = math_ops.cast(y, dtypes.int32)\n return x, y\n\n def _EvalInputFn():\n mnist_x, mnist_y = test_data\n dataset = data.Dataset.from_tensor_slices((mnist_x, mnist_y))\n dataset = dataset.apply(\n data.experimental.map_and_batch(\n map_func=_PreprocessFn,\n batch_size=batch_size,\n num_parallel_calls=8))\n dataset = dataset.repeat(count=1)\n iterator = dataset.make_one_shot_iterator()\n features, labels = iterator.get_next()\n return features, labels\n\n def _TrainInputFn():\n mnist_x, mnist_y = train_data\n dataset = data.Dataset.from_tensor_slices((mnist_x, mnist_y))\n dataset = dataset.shuffle(2 * len(mnist_x))\n dataset = dataset.apply(\n data.experimental.map_and_batch(\n map_func=_PreprocessFn,\n batch_size=batch_size,\n num_parallel_calls=8))\n dataset = dataset.repeat(count=num_epochs)\n iterator = dataset.make_one_shot_iterator()\n features, labels = iterator.get_next()\n return features, labels\n\n def _ModelFn(features, labels, mode):\n if is_training:\n logits_out = self._BuildGraph(features)\n else:\n graph_def = self._GetGraphDef(use_trt, batch_size, model_dir)\n logits_out = importer.import_graph_def(\n graph_def,\n input_map={INPUT_NODE_NAME: features},\n return_elements=[OUTPUT_NODE_NAME + ':0'],\n name='')[0]\n\n loss = losses.sparse_softmax_cross_entropy(\n labels=labels, logits=logits_out)\n summary.scalar('loss', loss)\n\n classes_out = math_ops.argmax(logits_out, axis=1, name='classes_out')\n accuracy = metrics.accuracy(\n labels=labels, predictions=classes_out, name='acc_op')\n summary.scalar('accuracy', accuracy[1])\n\n if mode == ModeKeys.EVAL:\n return EstimatorSpec(\n mode, loss=loss, eval_metric_ops={'accuracy': accuracy})\n elif mode == ModeKeys.TRAIN:\n optimizer = AdamOptimizer(learning_rate=1e-2)\n train_op = optimizer.minimize(loss, global_step=get_global_step())\n return EstimatorSpec(mode, loss=loss, train_op=train_op)\n\n config_proto = config_pb2.ConfigProto()\n config_proto.gpu_options.allow_growth = True\n estimator = Estimator(\n model_fn=_ModelFn,\n model_dir=model_dir if is_training else None,\n config=RunConfig(session_config=config_proto))\n\n if is_training:\n estimator.train(_TrainInputFn)\n results = estimator.evaluate(_EvalInputFn)\n logging.info('accuracy: %s', str(results['accuracy']))\n return results\n\n # To generate the checkpoint, set a different model_dir and call self._Run()\n # by setting is_training=True and num_epochs=1000, e.g.:\n # model_dir = '/tmp/quantization_mnist'\n # self._Run(\n # is_training=True,\n # use_trt=False,\n # batch_size=128,\n # num_epochs=100,\n # model_dir=model_dir)\n def testEval(self):\n if not trt_convert.is_tensorrt_enabled():\n return\n model_dir = test.test_src_dir_path('contrib/tensorrt/test/testdata')\n\n accuracy_tf_native = self._Run(\n is_training=False,\n use_trt=False,\n batch_size=128,\n num_epochs=None,\n model_dir=model_dir)['accuracy']\n logging.info('accuracy_tf_native: %f', accuracy_tf_native)\n self.assertAllClose(accuracy_tf_native, 0.9662)\n\n if trt_convert.get_linked_tensorrt_version()[0] < 5:\n return\n\n accuracy_tf_trt = self._Run(\n is_training=False,\n use_trt=True,\n batch_size=128,\n num_epochs=None,\n model_dir=model_dir)['accuracy']\n logging.info('accuracy_tf_trt: %f', accuracy_tf_trt)\n self.assertAllClose(accuracy_tf_trt, 0.9677)\n\n\nif __name__ == '__main__':\n test.main()\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\n\n\"\"\"Contains the convolutional layer classes and their functional aliases.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.keras import layers as keras_layers\nfrom tensorflow.python.layers import base\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util.tf_export import tf_export\n\n\n@tf_export(v1=['layers.Conv1D'])\nclass Conv1D(keras_layers.Conv1D, base.Layer):\n \"\"\"1D convolution layer (e.g. temporal convolution).\n\n This layer creates a convolution kernel that is convolved\n (actually cross-correlated) with the layer input to produce a tensor of\n outputs. If `use_bias` is True (and a `bias_initializer` is provided),\n a bias vector is created and added to the outputs. Finally, if\n `activation` is not `None`, it is applied to the outputs as well.\n\n Arguments:\n filters: Integer, the dimensionality of the output space (i.e. the number\n of filters in the convolution).\n kernel_size: An integer or tuple/list of a single integer, specifying the\n length of the 1D convolution window.\n strides: An integer or tuple/list of a single integer,\n specifying the stride length of the convolution.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: One of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, length, channels)` while `channels_first` corresponds to\n inputs with shape `(batch, channels, length)`.\n dilation_rate: An integer or tuple/list of a single integer, specifying\n the dilation rate to use for dilated convolution.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any `strides` value != 1.\n activation: Activation function. Set it to None to maintain a\n linear activation.\n use_bias: Boolean, whether the layer uses a bias.\n kernel_initializer: An initializer for the convolution kernel.\n bias_initializer: An initializer for the bias vector. If None, the default\n initializer will be used.\n kernel_regularizer: Optional regularizer for the convolution kernel.\n bias_regularizer: Optional regularizer for the bias vector.\n activity_regularizer: Optional regularizer function for the output.\n kernel_constraint: Optional projection function to be applied to the\n kernel after being updated by an `Optimizer` (e.g. used to implement\n norm constraints or value constraints for layer weights). The function\n must take as input the unprojected variable and must return the\n projected variable (which must have the same shape). Constraints are\n not safe to use when doing asynchronous distributed training.\n bias_constraint: Optional projection function to be applied to the\n bias after being updated by an `Optimizer`.\n trainable: Boolean, if `True` also add variables to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).\n name: A string, the name of the layer.\n \"\"\"\n\n def __init__(self, filters,\n kernel_size,\n strides=1,\n padding='valid',\n data_format='channels_last',\n dilation_rate=1,\n activation=None,\n use_bias=True,\n kernel_initializer=None,\n bias_initializer=init_ops.zeros_initializer(),\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n trainable=True,\n name=None,\n **kwargs):\n super(Conv1D, self).__init__(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n activation=activation,\n use_bias=use_bias,\n kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n kernel_constraint=kernel_constraint,\n bias_constraint=bias_constraint,\n trainable=trainable,\n name=name, **kwargs)\n\n\[email protected](\n date=None,\n instructions='Use tf.keras.layers.Conv1D instead.')\n@tf_export(v1=['layers.conv1d'])\ndef conv1d(inputs,\n filters,\n kernel_size,\n strides=1,\n padding='valid',\n data_format='channels_last',\n dilation_rate=1,\n activation=None,\n use_bias=True,\n kernel_initializer=None,\n bias_initializer=init_ops.zeros_initializer(),\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n trainable=True,\n name=None,\n reuse=None):\n \"\"\"Functional interface for 1D convolution layer (e.g. temporal convolution).\n\n This layer creates a convolution kernel that is convolved\n (actually cross-correlated) with the layer input to produce a tensor of\n outputs. If `use_bias` is True (and a `bias_initializer` is provided),\n a bias vector is created and added to the outputs. Finally, if\n `activation` is not `None`, it is applied to the outputs as well.\n\n Arguments:\n inputs: Tensor input.\n filters: Integer, the dimensionality of the output space (i.e. the number\n of filters in the convolution).\n kernel_size: An integer or tuple/list of a single integer, specifying the\n length of the 1D convolution window.\n strides: An integer or tuple/list of a single integer,\n specifying the stride length of the convolution.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: One of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, length, channels)` while `channels_first` corresponds to\n inputs with shape `(batch, channels, length)`.\n dilation_rate: An integer or tuple/list of a single integer, specifying\n the dilation rate to use for dilated convolution.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any `strides` value != 1.\n activation: Activation function. Set it to None to maintain a\n linear activation.\n use_bias: Boolean, whether the layer uses a bias.\n kernel_initializer: An initializer for the convolution kernel.\n bias_initializer: An initializer for the bias vector. If None, the default\n initializer will be used.\n kernel_regularizer: Optional regularizer for the convolution kernel.\n bias_regularizer: Optional regularizer for the bias vector.\n activity_regularizer: Optional regularizer function for the output.\n kernel_constraint: Optional projection function to be applied to the\n kernel after being updated by an `Optimizer` (e.g. used to implement\n norm constraints or value constraints for layer weights). The function\n must take as input the unprojected variable and must return the\n projected variable (which must have the same shape). Constraints are\n not safe to use when doing asynchronous distributed training.\n bias_constraint: Optional projection function to be applied to the\n bias after being updated by an `Optimizer`.\n trainable: Boolean, if `True` also add variables to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).\n name: A string, the name of the layer.\n reuse: Boolean, whether to reuse the weights of a previous layer\n by the same name.\n\n Returns:\n Output tensor.\n\n Raises:\n ValueError: if eager execution is enabled.\n \"\"\"\n layer = Conv1D(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n activation=activation,\n use_bias=use_bias,\n kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n kernel_constraint=kernel_constraint,\n bias_constraint=bias_constraint,\n trainable=trainable,\n name=name,\n _reuse=reuse,\n _scope=name)\n return layer.apply(inputs)\n\n\n@tf_export(v1=['layers.Conv2D'])\nclass Conv2D(keras_layers.Conv2D, base.Layer):\n \"\"\"2D convolution layer (e.g. spatial convolution over images).\n\n This layer creates a convolution kernel that is convolved\n (actually cross-correlated) with the layer input to produce a tensor of\n outputs. If `use_bias` is True (and a `bias_initializer` is provided),\n a bias vector is created and added to the outputs. Finally, if\n `activation` is not `None`, it is applied to the outputs as well.\n\n Arguments:\n filters: Integer, the dimensionality of the output space (i.e. the number\n of filters in the convolution).\n kernel_size: An integer or tuple/list of 2 integers, specifying the\n height and width of the 2D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 2 integers,\n specifying the strides of the convolution along the height and width.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: One of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first` corresponds to\n inputs with shape `(batch, channels, height, width)`.\n\n dilation_rate: An integer or tuple/list of 2 integers, specifying\n the dilation rate to use for dilated convolution.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any stride value != 1.\n activation: Activation function. Set it to None to maintain a\n linear activation.\n use_bias: Boolean, whether the layer uses a bias.\n kernel_initializer: An initializer for the convolution kernel.\n bias_initializer: An initializer for the bias vector. If None, the default\n initializer will be used.\n kernel_regularizer: Optional regularizer for the convolution kernel.\n bias_regularizer: Optional regularizer for the bias vector.\n activity_regularizer: Optional regularizer function for the output.\n kernel_constraint: Optional projection function to be applied to the\n kernel after being updated by an `Optimizer` (e.g. used to implement\n norm constraints or value constraints for layer weights). The function\n must take as input the unprojected variable and must return the\n projected variable (which must have the same shape). Constraints are\n not safe to use when doing asynchronous distributed training.\n bias_constraint: Optional projection function to be applied to the\n bias after being updated by an `Optimizer`.\n trainable: Boolean, if `True` also add variables to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).\n name: A string, the name of the layer.\n \"\"\"\n\n def __init__(self, filters,\n kernel_size,\n strides=(1, 1),\n padding='valid',\n data_format='channels_last',\n dilation_rate=(1, 1),\n activation=None,\n use_bias=True,\n kernel_initializer=None,\n bias_initializer=init_ops.zeros_initializer(),\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n trainable=True,\n name=None,\n **kwargs):\n super(Conv2D, self).__init__(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n activation=activation,\n use_bias=use_bias,\n kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n kernel_constraint=kernel_constraint,\n bias_constraint=bias_constraint,\n trainable=trainable,\n name=name, **kwargs)\n\n\[email protected](\n date=None,\n instructions='Use tf.keras.layers.Conv2D instead.')\n@tf_export(v1=['layers.conv2d'])\ndef conv2d(inputs,\n filters,\n kernel_size,\n strides=(1, 1),\n padding='valid',\n data_format='channels_last',\n dilation_rate=(1, 1),\n activation=None,\n use_bias=True,\n kernel_initializer=None,\n bias_initializer=init_ops.zeros_initializer(),\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n trainable=True,\n name=None,\n reuse=None):\n \"\"\"Functional interface for the 2D convolution layer.\n\n This layer creates a convolution kernel that is convolved\n (actually cross-correlated) with the layer input to produce a tensor of\n outputs. If `use_bias` is True (and a `bias_initializer` is provided),\n a bias vector is created and added to the outputs. Finally, if\n `activation` is not `None`, it is applied to the outputs as well.\n\n Arguments:\n inputs: Tensor input.\n filters: Integer, the dimensionality of the output space (i.e. the number\n of filters in the convolution).\n kernel_size: An integer or tuple/list of 2 integers, specifying the\n height and width of the 2D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 2 integers,\n specifying the strides of the convolution along the height and width.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: One of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first` corresponds to\n inputs with shape `(batch, channels, height, width)`.\n\n dilation_rate: An integer or tuple/list of 2 integers, specifying\n the dilation rate to use for dilated convolution.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any stride value != 1.\n activation: Activation function. Set it to None to maintain a\n linear activation.\n use_bias: Boolean, whether the layer uses a bias.\n kernel_initializer: An initializer for the convolution kernel.\n bias_initializer: An initializer for the bias vector. If None, the default\n initializer will be used.\n kernel_regularizer: Optional regularizer for the convolution kernel.\n bias_regularizer: Optional regularizer for the bias vector.\n activity_regularizer: Optional regularizer function for the output.\n kernel_constraint: Optional projection function to be applied to the\n kernel after being updated by an `Optimizer` (e.g. used to implement\n norm constraints or value constraints for layer weights). The function\n must take as input the unprojected variable and must return the\n projected variable (which must have the same shape). Constraints are\n not safe to use when doing asynchronous distributed training.\n bias_constraint: Optional projection function to be applied to the\n bias after being updated by an `Optimizer`.\n trainable: Boolean, if `True` also add variables to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).\n name: A string, the name of the layer.\n reuse: Boolean, whether to reuse the weights of a previous layer\n by the same name.\n\n Returns:\n Output tensor.\n\n Raises:\n ValueError: if eager execution is enabled.\n \"\"\"\n layer = Conv2D(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n activation=activation,\n use_bias=use_bias,\n kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n kernel_constraint=kernel_constraint,\n bias_constraint=bias_constraint,\n trainable=trainable,\n name=name,\n _reuse=reuse,\n _scope=name)\n return layer.apply(inputs)\n\n\n@tf_export(v1=['layers.Conv3D'])\nclass Conv3D(keras_layers.Conv3D, base.Layer):\n \"\"\"3D convolution layer (e.g. spatial convolution over volumes).\n\n This layer creates a convolution kernel that is convolved\n (actually cross-correlated) with the layer input to produce a tensor of\n outputs. If `use_bias` is True (and a `bias_initializer` is provided),\n a bias vector is created and added to the outputs. Finally, if\n `activation` is not `None`, it is applied to the outputs as well.\n\n Arguments:\n filters: Integer, the dimensionality of the output space (i.e. the number\n of filters in the convolution).\n kernel_size: An integer or tuple/list of 3 integers, specifying the\n depth, height and width of the 3D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 3 integers,\n specifying the strides of the convolution along the depth,\n height and width.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: One of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, depth, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, depth, height, width)`.\n dilation_rate: An integer or tuple/list of 3 integers, specifying\n the dilation rate to use for dilated convolution.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any stride value != 1.\n activation: Activation function. Set it to None to maintain a\n linear activation.\n use_bias: Boolean, whether the layer uses a bias.\n kernel_initializer: An initializer for the convolution kernel.\n bias_initializer: An initializer for the bias vector. If None, the default\n initializer will be used.\n kernel_regularizer: Optional regularizer for the convolution kernel.\n bias_regularizer: Optional regularizer for the bias vector.\n activity_regularizer: Optional regularizer function for the output.\n kernel_constraint: Optional projection function to be applied to the\n kernel after being updated by an `Optimizer` (e.g. used to implement\n norm constraints or value constraints for layer weights). The function\n must take as input the unprojected variable and must return the\n projected variable (which must have the same shape). Constraints are\n not safe to use when doing asynchronous distributed training.\n bias_constraint: Optional projection function to be applied to the\n bias after being updated by an `Optimizer`.\n trainable: Boolean, if `True` also add variables to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).\n name: A string, the name of the layer.\n \"\"\"\n\n def __init__(self, filters,\n kernel_size,\n strides=(1, 1, 1),\n padding='valid',\n data_format='channels_last',\n dilation_rate=(1, 1, 1),\n activation=None,\n use_bias=True,\n kernel_initializer=None,\n bias_initializer=init_ops.zeros_initializer(),\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n trainable=True,\n name=None,\n **kwargs):\n super(Conv3D, self).__init__(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n activation=activation,\n use_bias=use_bias,\n kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n kernel_constraint=kernel_constraint,\n bias_constraint=bias_constraint,\n trainable=trainable,\n name=name, **kwargs)\n\n\[email protected](\n date=None,\n instructions='Use tf.keras.layers.Conv3D instead.')\n@tf_export(v1=['layers.conv3d'])\ndef conv3d(inputs,\n filters,\n kernel_size,\n strides=(1, 1, 1),\n padding='valid',\n data_format='channels_last',\n dilation_rate=(1, 1, 1),\n activation=None,\n use_bias=True,\n kernel_initializer=None,\n bias_initializer=init_ops.zeros_initializer(),\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n trainable=True,\n name=None,\n reuse=None):\n \"\"\"Functional interface for the 3D convolution layer.\n\n This layer creates a convolution kernel that is convolved\n (actually cross-correlated) with the layer input to produce a tensor of\n outputs. If `use_bias` is True (and a `bias_initializer` is provided),\n a bias vector is created and added to the outputs. Finally, if\n `activation` is not `None`, it is applied to the outputs as well.\n\n Arguments:\n inputs: Tensor input.\n filters: Integer, the dimensionality of the output space (i.e. the number\n of filters in the convolution).\n kernel_size: An integer or tuple/list of 3 integers, specifying the\n depth, height and width of the 3D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 3 integers,\n specifying the strides of the convolution along the depth,\n height and width.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: One of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, depth, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, depth, height, width)`.\n dilation_rate: An integer or tuple/list of 3 integers, specifying\n the dilation rate to use for dilated convolution.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any stride value != 1.\n activation: Activation function. Set it to None to maintain a\n linear activation.\n use_bias: Boolean, whether the layer uses a bias.\n kernel_initializer: An initializer for the convolution kernel.\n bias_initializer: An initializer for the bias vector. If None, the default\n initializer will be used.\n kernel_regularizer: Optional regularizer for the convolution kernel.\n bias_regularizer: Optional regularizer for the bias vector.\n activity_regularizer: Optional regularizer function for the output.\n kernel_constraint: Optional projection function to be applied to the\n kernel after being updated by an `Optimizer` (e.g. used to implement\n norm constraints or value constraints for layer weights). The function\n must take as input the unprojected variable and must return the\n projected variable (which must have the same shape). Constraints are\n not safe to use when doing asynchronous distributed training.\n bias_constraint: Optional projection function to be applied to the\n bias after being updated by an `Optimizer`.\n trainable: Boolean, if `True` also add variables to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).\n name: A string, the name of the layer.\n reuse: Boolean, whether to reuse the weights of a previous layer\n by the same name.\n\n Returns:\n Output tensor.\n\n Raises:\n ValueError: if eager execution is enabled.\n \"\"\"\n layer = Conv3D(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n activation=activation,\n use_bias=use_bias,\n kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n kernel_constraint=kernel_constraint,\n bias_constraint=bias_constraint,\n trainable=trainable,\n name=name,\n _reuse=reuse,\n _scope=name)\n return layer.apply(inputs)\n\n\n@tf_export(v1=['layers.SeparableConv1D'])\nclass SeparableConv1D(keras_layers.SeparableConv1D, base.Layer):\n \"\"\"Depthwise separable 1D convolution.\n\n This layer performs a depthwise convolution that acts separately on\n channels, followed by a pointwise convolution that mixes channels.\n If `use_bias` is True and a bias initializer is provided,\n it adds a bias vector to the output.\n It then optionally applies an activation function to produce the final output.\n\n Arguments:\n filters: Integer, the dimensionality of the output space (i.e. the number\n of filters in the convolution).\n kernel_size: A single integer specifying the spatial\n dimensions of the filters.\n strides: A single integer specifying the strides\n of the convolution.\n Specifying any `stride` value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: One of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, length, channels)` while `channels_first` corresponds to\n inputs with shape `(batch, channels, length)`.\n dilation_rate: A single integer, specifying\n the dilation rate to use for dilated convolution.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any stride value != 1.\n depth_multiplier: The number of depthwise convolution output channels for\n each input channel. The total number of depthwise convolution output\n channels will be equal to `num_filters_in * depth_multiplier`.\n activation: Activation function. Set it to None to maintain a\n linear activation.\n use_bias: Boolean, whether the layer uses a bias.\n depthwise_initializer: An initializer for the depthwise convolution kernel.\n pointwise_initializer: An initializer for the pointwise convolution kernel.\n bias_initializer: An initializer for the bias vector. If None, the default\n initializer will be used.\n depthwise_regularizer: Optional regularizer for the depthwise\n convolution kernel.\n pointwise_regularizer: Optional regularizer for the pointwise\n convolution kernel.\n bias_regularizer: Optional regularizer for the bias vector.\n activity_regularizer: Optional regularizer function for the output.\n depthwise_constraint: Optional projection function to be applied to the\n depthwise kernel after being updated by an `Optimizer` (e.g. used for\n norm constraints or value constraints for layer weights). The function\n must take as input the unprojected variable and must return the\n projected variable (which must have the same shape). Constraints are\n not safe to use when doing asynchronous distributed training.\n pointwise_constraint: Optional projection function to be applied to the\n pointwise kernel after being updated by an `Optimizer`.\n bias_constraint: Optional projection function to be applied to the\n bias after being updated by an `Optimizer`.\n trainable: Boolean, if `True` also add variables to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).\n name: A string, the name of the layer.\n \"\"\"\n\n def __init__(self, filters,\n kernel_size,\n strides=1,\n padding='valid',\n data_format='channels_last',\n dilation_rate=1,\n depth_multiplier=1,\n activation=None,\n use_bias=True,\n depthwise_initializer=None,\n pointwise_initializer=None,\n bias_initializer=init_ops.zeros_initializer(),\n depthwise_regularizer=None,\n pointwise_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n depthwise_constraint=None,\n pointwise_constraint=None,\n bias_constraint=None,\n trainable=True,\n name=None,\n **kwargs):\n super(SeparableConv1D, self).__init__(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n depth_multiplier=depth_multiplier,\n activation=activation,\n use_bias=use_bias,\n depthwise_initializer=depthwise_initializer,\n pointwise_initializer=pointwise_initializer,\n bias_initializer=bias_initializer,\n depthwise_regularizer=depthwise_regularizer,\n pointwise_regularizer=pointwise_regularizer,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n depthwise_constraint=depthwise_constraint,\n pointwise_constraint=pointwise_constraint,\n bias_constraint=bias_constraint,\n trainable=trainable,\n name=name,\n **kwargs)\n\n\n@tf_export(v1=['layers.SeparableConv2D'])\nclass SeparableConv2D(keras_layers.SeparableConv2D, base.Layer):\n \"\"\"Depthwise separable 2D convolution.\n\n This layer performs a depthwise convolution that acts separately on\n channels, followed by a pointwise convolution that mixes channels.\n If `use_bias` is True and a bias initializer is provided,\n it adds a bias vector to the output.\n It then optionally applies an activation function to produce the final output.\n\n Arguments:\n filters: Integer, the dimensionality of the output space (i.e. the number\n of filters in the convolution).\n kernel_size: A tuple or list of 2 integers specifying the spatial\n dimensions of the filters. Can be a single integer to specify the same\n value for all spatial dimensions.\n strides: A tuple or list of 2 positive integers specifying the strides\n of the convolution. Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any `stride` value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: One of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first` corresponds to\n inputs with shape `(batch, channels, height, width)`.\n\n dilation_rate: An integer or tuple/list of 2 integers, specifying\n the dilation rate to use for dilated convolution.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any stride value != 1.\n depth_multiplier: The number of depthwise convolution output channels for\n each input channel. The total number of depthwise convolution output\n channels will be equal to `num_filters_in * depth_multiplier`.\n activation: Activation function. Set it to None to maintain a\n linear activation.\n use_bias: Boolean, whether the layer uses a bias.\n depthwise_initializer: An initializer for the depthwise convolution kernel.\n pointwise_initializer: An initializer for the pointwise convolution kernel.\n bias_initializer: An initializer for the bias vector. If None, the default\n initializer will be used.\n depthwise_regularizer: Optional regularizer for the depthwise\n convolution kernel.\n pointwise_regularizer: Optional regularizer for the pointwise\n convolution kernel.\n bias_regularizer: Optional regularizer for the bias vector.\n activity_regularizer: Optional regularizer function for the output.\n depthwise_constraint: Optional projection function to be applied to the\n depthwise kernel after being updated by an `Optimizer` (e.g. used for\n norm constraints or value constraints for layer weights). The function\n must take as input the unprojected variable and must return the\n projected variable (which must have the same shape). Constraints are\n not safe to use when doing asynchronous distributed training.\n pointwise_constraint: Optional projection function to be applied to the\n pointwise kernel after being updated by an `Optimizer`.\n bias_constraint: Optional projection function to be applied to the\n bias after being updated by an `Optimizer`.\n trainable: Boolean, if `True` also add variables to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).\n name: A string, the name of the layer.\n \"\"\"\n\n def __init__(self, filters,\n kernel_size,\n strides=(1, 1),\n padding='valid',\n data_format='channels_last',\n dilation_rate=(1, 1),\n depth_multiplier=1,\n activation=None,\n use_bias=True,\n depthwise_initializer=None,\n pointwise_initializer=None,\n bias_initializer=init_ops.zeros_initializer(),\n depthwise_regularizer=None,\n pointwise_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n depthwise_constraint=None,\n pointwise_constraint=None,\n bias_constraint=None,\n trainable=True,\n name=None,\n **kwargs):\n super(SeparableConv2D, self).__init__(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n depth_multiplier=depth_multiplier,\n activation=activation,\n use_bias=use_bias,\n depthwise_initializer=depthwise_initializer,\n pointwise_initializer=pointwise_initializer,\n bias_initializer=bias_initializer,\n depthwise_regularizer=depthwise_regularizer,\n pointwise_regularizer=pointwise_regularizer,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n depthwise_constraint=depthwise_constraint,\n pointwise_constraint=pointwise_constraint,\n bias_constraint=bias_constraint,\n trainable=trainable,\n name=name,\n **kwargs)\n\n\[email protected](\n date=None,\n instructions='Use tf.keras.layers.SeparableConv1D instead.')\n@tf_export(v1=['layers.separable_conv1d'])\ndef separable_conv1d(inputs,\n filters,\n kernel_size,\n strides=1,\n padding='valid',\n data_format='channels_last',\n dilation_rate=1,\n depth_multiplier=1,\n activation=None,\n use_bias=True,\n depthwise_initializer=None,\n pointwise_initializer=None,\n bias_initializer=init_ops.zeros_initializer(),\n depthwise_regularizer=None,\n pointwise_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n depthwise_constraint=None,\n pointwise_constraint=None,\n bias_constraint=None,\n trainable=True,\n name=None,\n reuse=None):\n \"\"\"Functional interface for the depthwise separable 1D convolution layer.\n\n This layer performs a depthwise convolution that acts separately on\n channels, followed by a pointwise convolution that mixes channels.\n If `use_bias` is True and a bias initializer is provided,\n it adds a bias vector to the output.\n It then optionally applies an activation function to produce the final output.\n\n Arguments:\n inputs: Input tensor.\n filters: Integer, the dimensionality of the output space (i.e. the number\n of filters in the convolution).\n kernel_size: A single integer specifying the spatial\n dimensions of the filters.\n strides: A single integer specifying the strides\n of the convolution.\n Specifying any `stride` value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: One of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, length, channels)` while `channels_first` corresponds to\n inputs with shape `(batch, channels, length)`.\n dilation_rate: A single integer, specifying\n the dilation rate to use for dilated convolution.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any stride value != 1.\n depth_multiplier: The number of depthwise convolution output channels for\n each input channel. The total number of depthwise convolution output\n channels will be equal to `num_filters_in * depth_multiplier`.\n activation: Activation function. Set it to None to maintain a\n linear activation.\n use_bias: Boolean, whether the layer uses a bias.\n depthwise_initializer: An initializer for the depthwise convolution kernel.\n pointwise_initializer: An initializer for the pointwise convolution kernel.\n bias_initializer: An initializer for the bias vector. If None, the default\n initializer will be used.\n depthwise_regularizer: Optional regularizer for the depthwise\n convolution kernel.\n pointwise_regularizer: Optional regularizer for the pointwise\n convolution kernel.\n bias_regularizer: Optional regularizer for the bias vector.\n activity_regularizer: Optional regularizer function for the output.\n depthwise_constraint: Optional projection function to be applied to the\n depthwise kernel after being updated by an `Optimizer` (e.g. used for\n norm constraints or value constraints for layer weights). The function\n must take as input the unprojected variable and must return the\n projected variable (which must have the same shape). Constraints are\n not safe to use when doing asynchronous distributed training.\n pointwise_constraint: Optional projection function to be applied to the\n pointwise kernel after being updated by an `Optimizer`.\n bias_constraint: Optional projection function to be applied to the\n bias after being updated by an `Optimizer`.\n trainable: Boolean, if `True` also add variables to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).\n name: A string, the name of the layer.\n reuse: Boolean, whether to reuse the weights of a previous layer\n by the same name.\n\n Returns:\n Output tensor.\n\n Raises:\n ValueError: if eager execution is enabled.\n \"\"\"\n layer = SeparableConv1D(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n depth_multiplier=depth_multiplier,\n activation=activation,\n use_bias=use_bias,\n depthwise_initializer=depthwise_initializer,\n pointwise_initializer=pointwise_initializer,\n bias_initializer=bias_initializer,\n depthwise_regularizer=depthwise_regularizer,\n pointwise_regularizer=pointwise_regularizer,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n depthwise_constraint=depthwise_constraint,\n pointwise_constraint=pointwise_constraint,\n bias_constraint=bias_constraint,\n trainable=trainable,\n name=name,\n _reuse=reuse,\n _scope=name)\n return layer.apply(inputs)\n\n\[email protected](\n date=None,\n instructions='Use tf.keras.layers.SeparableConv2D instead.')\n@tf_export(v1=['layers.separable_conv2d'])\ndef separable_conv2d(inputs,\n filters,\n kernel_size,\n strides=(1, 1),\n padding='valid',\n data_format='channels_last',\n dilation_rate=(1, 1),\n depth_multiplier=1,\n activation=None,\n use_bias=True,\n depthwise_initializer=None,\n pointwise_initializer=None,\n bias_initializer=init_ops.zeros_initializer(),\n depthwise_regularizer=None,\n pointwise_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n depthwise_constraint=None,\n pointwise_constraint=None,\n bias_constraint=None,\n trainable=True,\n name=None,\n reuse=None):\n \"\"\"Functional interface for the depthwise separable 2D convolution layer.\n\n This layer performs a depthwise convolution that acts separately on\n channels, followed by a pointwise convolution that mixes channels.\n If `use_bias` is True and a bias initializer is provided,\n it adds a bias vector to the output.\n It then optionally applies an activation function to produce the final output.\n\n Arguments:\n inputs: Input tensor.\n filters: Integer, the dimensionality of the output space (i.e. the number\n of filters in the convolution).\n kernel_size: A tuple or list of 2 integers specifying the spatial\n dimensions of the filters. Can be a single integer to specify the same\n value for all spatial dimensions.\n strides: A tuple or list of 2 positive integers specifying the strides\n of the convolution. Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any `stride` value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: One of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first` corresponds to\n inputs with shape `(batch, channels, height, width)`.\n\n dilation_rate: An integer or tuple/list of 2 integers, specifying\n the dilation rate to use for dilated convolution.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any stride value != 1.\n depth_multiplier: The number of depthwise convolution output channels for\n each input channel. The total number of depthwise convolution output\n channels will be equal to `num_filters_in * depth_multiplier`.\n activation: Activation function. Set it to None to maintain a\n linear activation.\n use_bias: Boolean, whether the layer uses a bias.\n depthwise_initializer: An initializer for the depthwise convolution kernel.\n pointwise_initializer: An initializer for the pointwise convolution kernel.\n bias_initializer: An initializer for the bias vector. If None, the default\n initializer will be used.\n depthwise_regularizer: Optional regularizer for the depthwise\n convolution kernel.\n pointwise_regularizer: Optional regularizer for the pointwise\n convolution kernel.\n bias_regularizer: Optional regularizer for the bias vector.\n activity_regularizer: Optional regularizer function for the output.\n depthwise_constraint: Optional projection function to be applied to the\n depthwise kernel after being updated by an `Optimizer` (e.g. used for\n norm constraints or value constraints for layer weights). The function\n must take as input the unprojected variable and must return the\n projected variable (which must have the same shape). Constraints are\n not safe to use when doing asynchronous distributed training.\n pointwise_constraint: Optional projection function to be applied to the\n pointwise kernel after being updated by an `Optimizer`.\n bias_constraint: Optional projection function to be applied to the\n bias after being updated by an `Optimizer`.\n trainable: Boolean, if `True` also add variables to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).\n name: A string, the name of the layer.\n reuse: Boolean, whether to reuse the weights of a previous layer\n by the same name.\n\n Returns:\n Output tensor.\n\n Raises:\n ValueError: if eager execution is enabled.\n \"\"\"\n layer = SeparableConv2D(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n depth_multiplier=depth_multiplier,\n activation=activation,\n use_bias=use_bias,\n depthwise_initializer=depthwise_initializer,\n pointwise_initializer=pointwise_initializer,\n bias_initializer=bias_initializer,\n depthwise_regularizer=depthwise_regularizer,\n pointwise_regularizer=pointwise_regularizer,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n depthwise_constraint=depthwise_constraint,\n pointwise_constraint=pointwise_constraint,\n bias_constraint=bias_constraint,\n trainable=trainable,\n name=name,\n _reuse=reuse,\n _scope=name)\n return layer.apply(inputs)\n\n\n@tf_export(v1=['layers.Conv2DTranspose'])\nclass Conv2DTranspose(keras_layers.Conv2DTranspose, base.Layer):\n \"\"\"Transposed 2D convolution layer (sometimes called 2D Deconvolution).\n\n The need for transposed convolutions generally arises\n from the desire to use a transformation going in the opposite direction\n of a normal convolution, i.e., from something that has the shape of the\n output of some convolution to something that has the shape of its input\n while maintaining a connectivity pattern that is compatible with\n said convolution.\n\n Arguments:\n filters: Integer, the dimensionality of the output space (i.e. the number\n of filters in the convolution).\n kernel_size: A tuple or list of 2 positive integers specifying the spatial\n dimensions of the filters. Can be a single integer to specify the same\n value for all spatial dimensions.\n strides: A tuple or list of 2 positive integers specifying the strides\n of the convolution. Can be a single integer to specify the same value for\n all spatial dimensions.\n padding: one of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first` corresponds to\n inputs with shape `(batch, channels, height, width)`.\n activation: Activation function. Set it to None to maintain a\n linear activation.\n use_bias: Boolean, whether the layer uses a bias.\n kernel_initializer: An initializer for the convolution kernel.\n bias_initializer: An initializer for the bias vector. If None, the default\n initializer will be used.\n kernel_regularizer: Optional regularizer for the convolution kernel.\n bias_regularizer: Optional regularizer for the bias vector.\n activity_regularizer: Optional regularizer function for the output.\n kernel_constraint: Optional projection function to be applied to the\n kernel after being updated by an `Optimizer` (e.g. used to implement\n norm constraints or value constraints for layer weights). The function\n must take as input the unprojected variable and must return the\n projected variable (which must have the same shape). Constraints are\n not safe to use when doing asynchronous distributed training.\n bias_constraint: Optional projection function to be applied to the\n bias after being updated by an `Optimizer`.\n trainable: Boolean, if `True` also add variables to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).\n name: A string, the name of the layer.\n \"\"\"\n\n def __init__(self, filters,\n kernel_size,\n strides=(1, 1),\n padding='valid',\n data_format='channels_last',\n activation=None,\n use_bias=True,\n kernel_initializer=None,\n bias_initializer=init_ops.zeros_initializer(),\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n trainable=True,\n name=None,\n **kwargs):\n super(Conv2DTranspose, self).__init__(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n activation=activation,\n use_bias=use_bias,\n kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n kernel_constraint=kernel_constraint,\n bias_constraint=bias_constraint,\n trainable=trainable,\n name=name,\n **kwargs)\n\n\[email protected](\n date=None,\n instructions='Use tf.keras.layers.Conv2DTranspose instead.')\n@tf_export(v1=['layers.conv2d_transpose'])\ndef conv2d_transpose(inputs,\n filters,\n kernel_size,\n strides=(1, 1),\n padding='valid',\n data_format='channels_last',\n activation=None,\n use_bias=True,\n kernel_initializer=None,\n bias_initializer=init_ops.zeros_initializer(),\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n trainable=True,\n name=None,\n reuse=None):\n \"\"\"Functional interface for transposed 2D convolution layer.\n\n The need for transposed convolutions generally arises\n from the desire to use a transformation going in the opposite direction\n of a normal convolution, i.e., from something that has the shape of the\n output of some convolution to something that has the shape of its input\n while maintaining a connectivity pattern that is compatible with\n said convolution.\n\n Arguments:\n inputs: Input tensor.\n filters: Integer, the dimensionality of the output space (i.e. the number\n of filters in the convolution).\n kernel_size: A tuple or list of 2 positive integers specifying the spatial\n dimensions of the filters. Can be a single integer to specify the same\n value for all spatial dimensions.\n strides: A tuple or list of 2 positive integers specifying the strides\n of the convolution. Can be a single integer to specify the same value for\n all spatial dimensions.\n padding: one of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first` corresponds to\n inputs with shape `(batch, channels, height, width)`.\n activation: Activation function. Set it to `None` to maintain a\n linear activation.\n use_bias: Boolean, whether the layer uses a bias.\n kernel_initializer: An initializer for the convolution kernel.\n bias_initializer: An initializer for the bias vector. If `None`, the default\n initializer will be used.\n kernel_regularizer: Optional regularizer for the convolution kernel.\n bias_regularizer: Optional regularizer for the bias vector.\n activity_regularizer: Optional regularizer function for the output.\n kernel_constraint: Optional projection function to be applied to the\n kernel after being updated by an `Optimizer` (e.g. used to implement\n norm constraints or value constraints for layer weights). The function\n must take as input the unprojected variable and must return the\n projected variable (which must have the same shape). Constraints are\n not safe to use when doing asynchronous distributed training.\n bias_constraint: Optional projection function to be applied to the\n bias after being updated by an `Optimizer`.\n trainable: Boolean, if `True` also add variables to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).\n name: A string, the name of the layer.\n reuse: Boolean, whether to reuse the weights of a previous layer\n by the same name.\n\n Returns:\n Output tensor.\n\n Raises:\n ValueError: if eager execution is enabled.\n \"\"\"\n layer = Conv2DTranspose(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n activation=activation,\n use_bias=use_bias,\n kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n kernel_constraint=kernel_constraint,\n bias_constraint=bias_constraint,\n trainable=trainable,\n name=name,\n _reuse=reuse,\n _scope=name)\n return layer.apply(inputs)\n\n\n@tf_export(v1=['layers.Conv3DTranspose'])\nclass Conv3DTranspose(keras_layers.Conv3DTranspose, base.Layer):\n \"\"\"Transposed 3D convolution layer (sometimes called 3D Deconvolution).\n\n Arguments:\n filters: Integer, the dimensionality of the output space (i.e. the number\n of filters in the convolution).\n kernel_size: An integer or tuple/list of 3 integers, specifying the\n depth, height and width of the 3D convolution window.\n Can be a single integer to specify the same value for all spatial\n dimensions.\n strides: An integer or tuple/list of 3 integers, specifying the strides\n of the convolution along the depth, height and width.\n Can be a single integer to specify the same value for all spatial\n dimensions.\n padding: One of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, depth, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, depth, height, width)`.\n activation: Activation function. Set it to `None` to maintain a\n linear activation.\n use_bias: Boolean, whether the layer uses a bias.\n kernel_initializer: An initializer for the convolution kernel.\n bias_initializer: An initializer for the bias vector. If `None`, the default\n initializer will be used.\n kernel_regularizer: Optional regularizer for the convolution kernel.\n bias_regularizer: Optional regularizer for the bias vector.\n activity_regularizer: Optional regularizer function for the output.\n kernel_constraint: Optional projection function to be applied to the\n kernel after being updated by an `Optimizer` (e.g. used to implement\n norm constraints or value constraints for layer weights). The function\n must take as input the unprojected variable and must return the\n projected variable (which must have the same shape). Constraints are\n not safe to use when doing asynchronous distributed training.\n bias_constraint: Optional projection function to be applied to the\n bias after being updated by an `Optimizer`.\n trainable: Boolean, if `True` also add variables to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).\n name: A string, the name of the layer.\n \"\"\"\n\n def __init__(self,\n filters,\n kernel_size,\n strides=(1, 1, 1),\n padding='valid',\n data_format='channels_last',\n activation=None,\n use_bias=True,\n kernel_initializer=None,\n bias_initializer=init_ops.zeros_initializer(),\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n trainable=True,\n name=None,\n **kwargs):\n super(Conv3DTranspose, self).__init__(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n activation=activation,\n use_bias=use_bias,\n kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n kernel_constraint=kernel_constraint,\n bias_constraint=bias_constraint,\n trainable=trainable,\n name=name,\n **kwargs)\n\n\[email protected](\n date=None,\n instructions='Use tf.keras.layers.Conv3DTranspose instead.')\n@tf_export(v1=['layers.conv3d_transpose'])\ndef conv3d_transpose(inputs,\n filters,\n kernel_size,\n strides=(1, 1, 1),\n padding='valid',\n data_format='channels_last',\n activation=None,\n use_bias=True,\n kernel_initializer=None,\n bias_initializer=init_ops.zeros_initializer(),\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n trainable=True,\n name=None,\n reuse=None):\n \"\"\"Functional interface for transposed 3D convolution layer.\n\n Arguments:\n inputs: Input tensor.\n filters: Integer, the dimensionality of the output space (i.e. the number\n of filters in the convolution).\n kernel_size: A tuple or list of 3 positive integers specifying the spatial\n dimensions of the filters. Can be a single integer to specify the same\n value for all spatial dimensions.\n strides: A tuple or list of 3 positive integers specifying the strides\n of the convolution. Can be a single integer to specify the same value for\n all spatial dimensions.\n padding: one of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, depth, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, depth, height, width)`.\n activation: Activation function. Set it to None to maintain a\n linear activation.\n use_bias: Boolean, whether the layer uses a bias.\n kernel_initializer: An initializer for the convolution kernel.\n bias_initializer: An initializer for the bias vector. If None, the default\n initializer will be used.\n kernel_regularizer: Optional regularizer for the convolution kernel.\n bias_regularizer: Optional regularizer for the bias vector.\n activity_regularizer: Optional regularizer function for the output.\n kernel_constraint: Optional projection function to be applied to the\n kernel after being updated by an `Optimizer` (e.g. used to implement\n norm constraints or value constraints for layer weights). The function\n must take as input the unprojected variable and must return the\n projected variable (which must have the same shape). Constraints are\n not safe to use when doing asynchronous distributed training.\n bias_constraint: Optional projection function to be applied to the\n bias after being updated by an `Optimizer`.\n trainable: Boolean, if `True` also add variables to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).\n name: A string, the name of the layer.\n reuse: Boolean, whether to reuse the weights of a previous layer\n by the same name.\n\n Returns:\n Output tensor.\n\n Raises:\n ValueError: if eager execution is enabled.\n \"\"\"\n layer = Conv3DTranspose(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n activation=activation,\n use_bias=use_bias,\n kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n kernel_constraint=kernel_constraint,\n bias_constraint=bias_constraint,\n trainable=trainable,\n name=name,\n _reuse=reuse,\n _scope=name)\n return layer.apply(inputs)\n\n\n# Aliases\n\nConvolution1D = Conv1D\nConvolution2D = Conv2D\nConvolution3D = Conv3D\nSeparableConvolution2D = SeparableConv2D\nConvolution2DTranspose = Deconvolution2D = Deconv2D = Conv2DTranspose\nConvolution3DTranspose = Deconvolution3D = Deconv3D = Conv3DTranspose\nconvolution1d = conv1d\nconvolution2d = conv2d\nconvolution3d = conv3d\nseparable_convolution2d = separable_conv2d\nconvolution2d_transpose = deconvolution2d = deconv2d = conv2d_transpose\nconvolution3d_transpose = deconvolution3d = deconv3d = conv3d_transpose\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# ==============================================================================\n\n\"\"\"Utilty functions for control flow.\n\nThis file is necessary to avoid cyclic dependencies between ops.py and\ncontrol_flow_ops.py.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport traceback\n\nfrom tensorflow.python.platform import tf_logging as logging\n\nENABLE_CONTROL_FLOW_V2 = (os.getenv(\"TF_ENABLE_CONTROL_FLOW_V2\", \"0\") != \"0\" or\n os.getenv(\"TF_ENABLE_COND_V2\", \"0\") != \"0\" or\n os.getenv(\"TF_ENABLE_WHILE_V2\", \"0\") != \"0\" or\n os.getenv(\"TF_ENABLE_TENSOR_ARRAY_V2\", \"0\") != \"0\")\n\n\ndef EnableControlFlowV2(graph):\n \"\"\"Returns whether control flow v2 should be used in `graph`.\"\"\"\n # Enable new control flow in FuncGraphs (but not legacy _FuncGraphs).\n # TODO(skyewm): do something better than hasattr without messing up imports.\n return ENABLE_CONTROL_FLOW_V2 or (\n graph.building_function and not hasattr(graph, \"_captured\"))\n\n\ndef IsInXLAContext(op):\n try:\n xla_compile = op.get_attr(\"_XlaCompile\")\n if xla_compile: return True\n except ValueError:\n pass\n ctxt = op._get_control_flow_context() # pylint: disable=protected-access\n return GetContainingXLAContext(ctxt) is not None\n\n\ndef InXlaContext(graph):\n ctxt = graph._get_control_flow_context() # pylint: disable=protected-access\n return GetContainingXLAContext(ctxt) is not None\n\n\ndef GraphOrParentsInXlaContext(graph):\n while True:\n if InXlaContext(graph): return True\n try:\n graph = graph.outer_graph\n except AttributeError:\n return False\n\n\ndef IsInWhileLoop(op):\n ctxt = op._get_control_flow_context() # pylint: disable=protected-access\n return GetContainingWhileContext(ctxt) is not None\n\n\ndef IsInCond(op):\n ctxt = op._get_control_flow_context() # pylint: disable=protected-access\n return GetContainingCondContext(ctxt) is not None\n\n\ndef IsSwitch(op):\n \"\"\"Return true if `op` is a Switch.\"\"\"\n return op.type == \"Switch\" or op.type == \"RefSwitch\"\n\n\ndef IsMerge(op):\n \"\"\"Return true if `op` is a Merge.\"\"\"\n return op.type == \"Merge\" or op.type == \"RefMerge\"\n\n\ndef IsLoopEnter(op):\n \"\"\"Returns true if `op` is an Enter.\"\"\"\n return op.type == \"Enter\" or op.type == \"RefEnter\"\n\n\ndef IsLoopExit(op):\n \"\"\"Return true if `op` is an Exit.\"\"\"\n return op.type == \"Exit\" or op.type == \"RefExit\"\n\n\ndef IsCondSwitch(op):\n \"\"\"Return true if `op` is the Switch for a conditional.\"\"\"\n if not IsSwitch(op):\n return False\n if not op.outputs:\n return False\n # Switch nodes are not part of the cond control flow context that they\n # represent, so consider the consumers of its outputs to determine if it is\n # cond switch or not. A switch is a cond switch iff all its consumers are in\n # cond contexts.\n is_cond_switch = True\n for o in op.outputs:\n for c in o.consumers():\n ctxt = c._get_control_flow_context() # pylint: disable=protected-access\n if IsLoopEnter(c):\n ctxt = ctxt.outer_context\n is_cond_switch = is_cond_switch and (ctxt is not None and\n ctxt.IsCondContext())\n return is_cond_switch\n\n\ndef IsCondMerge(op):\n \"\"\"Return true if `op` is the Merge for a conditional.\"\"\"\n if not IsMerge(op):\n return False\n if not op.inputs:\n return False\n # Merge nodes are not part of the cond control flow context that they\n # represent, so consider the inputs to the merge of to determine if it is\n # cond merge or not: A merge is a cond merge iff all its inputs are in\n # cond contexts.\n is_cond_merge = True\n for i in op.inputs:\n ctxt = GetOutputContext(i.op)\n is_cond_merge = is_cond_merge and ctxt is not None and ctxt.IsCondContext()\n return is_cond_merge\n\n\ndef IsLoopSwitch(op):\n \"\"\"Return true if `op` is the Switch for a while loop.\"\"\"\n if IsSwitch(op):\n ctxt = op._get_control_flow_context() # pylint: disable=protected-access\n return ctxt is not None and ctxt.IsWhileContext() and not IsCondSwitch(op)\n return False\n\n\ndef IsLoopMerge(op):\n \"\"\"Return true if `op` is the Merge for a while loop.\"\"\"\n if IsMerge(op):\n ctxt = op._get_control_flow_context() # pylint: disable=protected-access\n return ctxt is not None and ctxt.IsWhileContext() and not IsCondMerge(op)\n return False\n\n\ndef IsLoopConstantEnter(op):\n \"\"\"Return true iff op is a loop invariant.\"\"\"\n return IsLoopEnter(op) and op.get_attr(\"is_constant\")\n\n\ndef GetLoopConstantEnter(value):\n \"\"\"Return the enter op if we can infer `value` to be a loop invariant.\"\"\"\n id_ops = {\"Switch\", \"RefSwitch\", \"Identity\", \"RefIdentity\"}\n op = value.op\n while op.type in id_ops:\n op = op.inputs[0].op\n return op if IsLoopConstantEnter(op) else None\n\n\ndef GetOutputContext(op):\n \"\"\"Return the control flow context for the output of an op.\"\"\"\n ctxt = op._get_control_flow_context() # pylint: disable=protected-access\n # Exit nodes usually have a control flow context, except in the case where the\n # exit node was imported via import_graph_def (in which case no nodes have\n # control flow contexts).\n if ctxt is not None and IsLoopExit(op):\n ctxt = ctxt.outer_context\n return ctxt\n\n\ndef GetContainingWhileContext(ctxt, stop_ctxt=None):\n \"\"\"Returns the first ancestor WhileContext of `ctxt`.\n\n Returns `ctxt` if `ctxt` is a WhileContext, or None if `ctxt` is not in a\n while loop.\n\n Args:\n ctxt: ControlFlowContext\n stop_ctxt: ControlFlowContext, optional. If provided, the search will end\n if it sees stop_ctxt.\n\n Returns:\n `ctxt` if `ctxt` is a WhileContext, the most nested WhileContext containing\n `ctxt`, or None if `ctxt` is not in a while loop. If `stop_ctxt` is not\n `None`, this returns `ctxt` if it matches `stop_ctxt` in its traversal.\n \"\"\"\n while ctxt:\n if ctxt.IsWhileContext() or ctxt == stop_ctxt: return ctxt\n ctxt = ctxt.outer_context\n return None\n\n\ndef GetContainingXLAContext(ctxt):\n \"\"\"Returns the first ancestor XLAContext of `ctxt`.\n\n Returns `ctxt` if `ctxt` is a XLAContext, or None if `ctxt` is not in a\n while loop.\n\n Args:\n ctxt: ControlFlowContext\n\n Returns:\n `ctxt` if `ctxt` is a XLAContext, the most nested XLAContext containing\n `ctxt`, or None if `ctxt` is not in a while loop.\n \"\"\"\n while ctxt:\n if ctxt.IsXLAContext(): return ctxt\n ctxt = ctxt.outer_context\n return None\n\n\ndef GetContainingCondContext(ctxt):\n \"\"\"Returns the first ancestor CondContext of `ctxt`.\n\n Returns `ctxt` if `ctxt` is a CondContext, or None if `ctxt` is not in a cond.\n\n Args:\n ctxt: ControlFlowContext\n\n Returns:\n `ctxt` if `ctxt` is a CondContext, the most nested CondContext containing\n `ctxt`, or None if `ctxt` is not in a cond.\n \"\"\"\n while ctxt:\n if ctxt.IsCondContext(): return ctxt\n ctxt = ctxt.outer_context\n return None\n\n\ndef IsContainingContext(ctxt, maybe_containing_ctxt):\n \"\"\"Returns true if `maybe_containing_ctxt` is or contains `ctxt`.\"\"\"\n while ctxt is not maybe_containing_ctxt:\n if ctxt is None: return False\n ctxt = ctxt.outer_context\n return True\n\n\ndef OpInContext(op, ctxt):\n return IsContainingContext(op._get_control_flow_context(), ctxt) # pylint: disable=protected-access\n\n\ndef TensorInContext(tensor, ctxt):\n return OpInContext(tensor.op, ctxt)\n\n\ndef CheckInputFromValidContext(op, input_op):\n \"\"\"Returns whether `input_op` can be used from `op`s context.\n\n Conceptually, only inputs from op's while context or any ancestor while\n context (including outside of any context) are valid. In practice, there are\n many other edge cases as well.\n\n Args:\n op: Operation\n input_op: Operation\n\n Raises:\n ValueError: if input_op is from an invalid context.\n \"\"\"\n op_ctxt = op._get_control_flow_context() # pylint: disable=protected-access\n input_ctxt = GetOutputContext(input_op)\n valid = False\n\n if not input_ctxt:\n # input_op isn't in a control flow context.\n valid = True\n elif op_ctxt is input_ctxt:\n # input_op is in the same context as op.\n valid = True\n else:\n while_ctxt = GetContainingWhileContext(op_ctxt)\n input_while_ctxt = GetContainingWhileContext(input_ctxt)\n\n if while_ctxt is None:\n if input_while_ctxt is None:\n # Neither op nor input_op is in a while loop, but one or both are in\n # conds. We allow this, although execution will fail if the branch\n # corresponding to input_op's cond context isn't taken.\n valid = True\n # Invalid if op isn't in a while loop and input_op is. Unless...\n if IsLoopEnter(op):\n # WhileContext._BuildLoop clears context for Enter nodes.\n valid = True\n if IsSwitch(op):\n # CondContext.AddValue clears context for Switch nodes.\n valid = True\n elif IsContainingContext(while_ctxt, input_while_ctxt):\n # input_op is in a while loop which contains op's while loop (or not in a\n # while loop at all).\n valid = True\n elif (while_ctxt.grad_state and\n IsContainingContext(while_ctxt.grad_state.forward_context,\n input_while_ctxt)):\n # op is in a gradient context and input_op is in the associated forward\n # pass context or an ancestor thereof. This case is need to build while\n # loop gradients.\n # NOTE(skyewm): we theoretically also need this case for custom gradient\n # functions that close over tensors from ancestor contexts, but I haven't\n # verified this.\n valid = True\n elif (while_ctxt.grad_state and\n while_ctxt.grad_state.forward_context is\n input_while_ctxt._outer_context): # pylint: disable=protected-access\n # op is in a gradient context and input_op is in a child of the associated\n # forward pass context. This case is needed for the gradients of while\n # loops with conds.\n valid = True\n elif (input_while_ctxt.grad_state and\n input_while_ctxt.grad_state.forward_context is while_ctxt):\n # input_op is in the gradient context of op's context. This case is needed\n # when the gradient of a while loop gradient is requested (this will\n # eventually fail unless there is a stop_gradient() or similar).\n valid = True\n elif (input_while_ctxt.grad_state and\n input_ctxt.grad_state.forward_context.grad_state and\n input_ctxt.grad_state.forward_context.grad_state.forward_context is\n while_ctxt):\n # input_op is in the grad grad context of op's context. This case is\n # needed when the gradient of a while loop gradient is requested (this\n # will eventually fail unless there is a stop_gradient() or similar).\n valid = True\n\n if not valid:\n if while_ctxt:\n error_msg = (\n \"Cannot use '%s' as input to '%s' because they are in different while\"\n \" loops.\" % (op.name, input_op.name))\n else:\n error_msg = (\n \"Cannot use '%s' as input to '%s' because '%s' is in a while loop.\"\n % (input_op.name, op.name, input_op.name))\n\n # Log the error message plus the relevant stack traces. The stacks may be\n # useful for debugging this error, but we don't want to raise an\n # unreadable exception.\n log_msg = error_msg\n log_msg += \"\\n\\n%s while context: %s\" % (op.name, while_ctxt)\n log_msg += \"\\n%s while context: %s\" % (input_op.name, input_while_ctxt)\n log_msg += \"\\n\\nTraceback for %s:\\n%s\\nTraceback for %s:\\n%s\\n\" % (\n op.name, \"\".join(traceback.format_list(op.traceback)),\n input_op.name, \"\".join(traceback.format_list(input_op.traceback)))\n logging.info(log_msg)\n raise ValueError(error_msg + \" See info log for more details.\")\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Standard functions for creating slots.\n\nA slot is a `Variable` created with the same shape as a primary variable or\n`Tensor`. A slot is always scoped in the namespace of the primary object and\ntypically has the same device and type.\n\nSlots are typically used as accumulators to track values associated with\nthe primary object:\n\n```python\n# Optimizers can create a slot for each variable to track accumulators\naccumulators = {var : create_zeros_slot(var, \"momentum\") for var in vs}\nfor var in vs:\n apply_momentum(var, accumulators[var], lr, grad, momentum_tensor)\n\n# Slots can also be used for moving averages\nmavg = create_slot(var, var.initialized_value(), \"exponential_moving_avg\")\nupdate_mavg = mavg.assign_sub((mavg - var) * (1 - decay))\n```\n\"\"\"\n# pylint: disable=g-bad-name\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.distribute import distribution_strategy_context\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables\n\n\ndef _create_slot_var(primary, val, scope, validate_shape, shape, dtype):\n \"\"\"Helper function for creating a slot variable.\"\"\"\n\n # TODO(lukaszkaiser): Consider allowing partitioners to be set in the current\n # scope.\n current_partitioner = variable_scope.get_variable_scope().partitioner\n variable_scope.get_variable_scope().set_partitioner(None)\n # When init from val instead of callable initializer, the shape is expected to\n # be None, not <unknown> or any fully defined shape.\n shape = shape if callable(val) else None\n if resource_variable_ops.is_resource_variable(primary):\n use_resource = True\n elif isinstance(primary, variables.RefVariable):\n use_resource = False\n else:\n use_resource = None\n slot = variable_scope.get_variable(\n scope,\n initializer=val,\n trainable=False,\n use_resource=use_resource,\n shape=shape,\n dtype=dtype,\n validate_shape=validate_shape)\n variable_scope.get_variable_scope().set_partitioner(current_partitioner)\n\n # pylint: disable=protected-access\n if isinstance(primary, variables.Variable) and primary._save_slice_info:\n # Primary is a partitioned variable, so we need to also indicate that\n # the slot is a partitioned variable. Slots have the same partitioning\n # as their primaries.\n # For examples when using AdamOptimizer in linear model, slot.name\n # here can be \"linear//weights/Adam:0\", while primary.op.name is\n # \"linear//weight\". We want to get 'Adam' as real_slot_name, so we\n # remove \"'linear//weight' + '/'\" and ':0'.\n real_slot_name = slot.name[len(primary.op.name + \"/\"):-2]\n slice_info = primary._save_slice_info\n slot._set_save_slice_info(variables.Variable.SaveSliceInfo(\n slice_info.full_name + \"/\" + real_slot_name,\n slice_info.full_shape[:],\n slice_info.var_offset[:],\n slice_info.var_shape[:]))\n # pylint: enable=protected-access\n return slot\n\n\ndef create_slot(primary, val, name, colocate_with_primary=True):\n \"\"\"Create a slot initialized to the given value.\n\n The type of the slot is determined by the given value.\n\n Args:\n primary: The primary `Variable` or `Tensor`.\n val: A `Tensor` specifying the initial value of the slot.\n name: Name to use for the slot variable.\n colocate_with_primary: Boolean. If True the slot is located\n on the same device as `primary`.\n\n Returns:\n A `Variable` object.\n \"\"\"\n # Scope the slot name in the namespace of the primary variable.\n # Set \"primary.op.name + '/' + name\" as default name, so the scope name of\n # optimizer can be shared when reuse is True. Meanwhile when reuse is False\n # and the same name has been previously used, the scope name will add '_N'\n # as suffix for unique identifications.\n validate_shape = val.get_shape().is_fully_defined()\n if context.executing_eagerly():\n prefix = primary._shared_name # pylint: disable=protected-access\n else:\n prefix = primary.op.name\n with variable_scope.variable_scope(None, prefix + \"/\" + name):\n if colocate_with_primary:\n distribution_strategy = distribution_strategy_context.get_strategy()\n with distribution_strategy.extended.colocate_vars_with(primary):\n return _create_slot_var(primary, val, \"\", validate_shape, None, None)\n else:\n return _create_slot_var(primary, val, \"\", validate_shape, None, None)\n\n\ndef create_slot_with_initializer(primary, initializer, shape, dtype, name,\n colocate_with_primary=True):\n \"\"\"Creates a slot initialized using an `Initializer`.\n\n The type of the slot is determined by the given value.\n\n Args:\n primary: The primary `Variable` or `Tensor`.\n initializer: An `Initializer`. The initial value of the slot.\n shape: Shape of the initial value of the slot.\n dtype: Type of the value of the slot.\n name: Name to use for the slot variable.\n colocate_with_primary: Boolean. If True the slot is located\n on the same device as `primary`.\n\n Returns:\n A `Variable` object.\n \"\"\"\n # Scope the slot name in the namespace of the primary variable.\n # Set \"primary.op.name + '/' + name\" as default name, so the scope name of\n # optimizer can be shared when reuse is True. Meanwhile when reuse is False\n # and the same name has been previously used, the scope name will add '_N'\n # as suffix for unique identifications.\n validate_shape = shape.is_fully_defined()\n if context.executing_eagerly():\n prefix = primary._shared_name # pylint: disable=protected-access\n else:\n prefix = primary.op.name\n with variable_scope.variable_scope(None, prefix + \"/\" + name):\n if colocate_with_primary:\n distribution_strategy = distribution_strategy_context.get_strategy()\n with distribution_strategy.extended.colocate_vars_with(primary):\n return _create_slot_var(primary, initializer, \"\", validate_shape, shape,\n dtype)\n else:\n return _create_slot_var(primary, initializer, \"\", validate_shape, shape,\n dtype)\n\n\ndef create_zeros_slot(primary, name, dtype=None, colocate_with_primary=True):\n \"\"\"Create a slot initialized to 0 with same shape as the primary object.\n\n Args:\n primary: The primary `Variable` or `Tensor`.\n name: Name to use for the slot variable.\n dtype: Type of the slot variable. Defaults to the type of `primary`.\n colocate_with_primary: Boolean. If True the slot is located\n on the same device as `primary`.\n\n Returns:\n A `Variable` object.\n \"\"\"\n if dtype is None:\n dtype = primary.dtype\n slot_shape = primary.get_shape()\n if slot_shape.is_fully_defined():\n initializer = init_ops.zeros_initializer(dtype)\n return create_slot_with_initializer(\n primary, initializer, slot_shape, dtype, name,\n colocate_with_primary=colocate_with_primary)\n else:\n if isinstance(primary, variables.Variable):\n slot_shape = array_ops.shape(primary.initialized_value())\n else:\n slot_shape = array_ops.shape(primary)\n val = array_ops.zeros(slot_shape, dtype=dtype)\n return create_slot(primary, val, name,\n colocate_with_primary=colocate_with_primary)\n" ]
[ [ "tensorflow.python.framework.tensor_shape.scalar", "tensorflow.python.ops.gen_nn_ops.relu6", "tensorflow.python.ops.math_ops.subtract", "tensorflow.python.compat.compat.forward_compatible", "numpy.all", "tensorflow.python.ops.array_ops.stop_gradient", "tensorflow.python.framework.graph_util.tensor_shape_from_node_def_name", "tensorflow.python.ops.math_ops.divide", "tensorflow.python.ops.math_ops.less", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.ops.array_ops.required_space_to_batch_paddings", "numpy.full", "tensorflow.python.ops.array_ops.batch_to_space", "tensorflow.python.ops.math_ops.matmul", "numpy.zeros", "tensorflow.python.ops.gen_nn_ops.top_kv2", "tensorflow.python.ops.gen_nn_ops.fractional_avg_pool", "tensorflow.python.ops.math_ops.negative", "tensorflow.python.ops.gen_nn_ops.softmax_cross_entropy_with_logits", "tensorflow.python.util.deprecation.deprecated_args", "numpy.array", "tensorflow.python.ops.math_ops.range", "tensorflow.python.ops.gen_nn_ops.bias_add_v1", "tensorflow.python.ops.array_ops.space_to_batch", "tensorflow.python.ops.array_ops.space_to_batch_nd", "numpy.concatenate", "tensorflow.python.ops.gen_nn_ops.bias_add", "tensorflow.python.ops.array_ops.reverse_v2", "tensorflow.python.ops.gen_nn_ops.conv3d", "tensorflow.python.framework.random_seed.get_seed", "tensorflow.python.framework.tensor_shape.dimension_at_index", "tensorflow.python.ops.gen_nn_ops.avg_pool", "tensorflow.python.framework.dtypes.as_dtype", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.ops.gen_nn_ops.conv3d_backprop_input_v2", "tensorflow.python.ops.array_ops.stack", "tensorflow.python.ops.array_ops.concat", "tensorflow.python.ops.gen_nn_ops.nth_element", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.array_ops.squeeze", "tensorflow.python.ops.gen_nn_ops.leaky_relu", "tensorflow.python.ops.math_ops.floor", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.framework.tensor_util.constant_value", "tensorflow.python.ops.gen_nn_ops.relu", "tensorflow.python.ops.gen_nn_ops.max_pool_with_argmax", "tensorflow.python.ops.gen_nn_ops.conv2d_backprop_filter", "tensorflow.python.util.deprecation.deprecated_arg_values", "tensorflow.python.ops.gen_nn_ops.max_pool", "tensorflow.python.ops.gen_nn_ops.dilation2d", "tensorflow.python.util.deprecation.rewrite_argument_docstring", "tensorflow.python.framework.ops.RegisterStatistics", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.ops.array_ops.reshape", "numpy.broadcast_to", "tensorflow.python.ops.math_ops.maximum", "tensorflow.python.ops.random_ops.random_uniform", "tensorflow.python.util.deprecation.deprecated_argument_lookup", "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.framework.errors_impl.InvalidArgumentError", "numpy.any", "tensorflow.python.ops.math_ops.to_float", "tensorflow.python.ops.array_ops.rank", "tensorflow.python.ops.gen_nn_ops.fractional_max_pool", "numpy.asscalar", "tensorflow.python.framework.ops.OpStats", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.util.deprecation.deprecated", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.ops.gen_nn_ops.conv2d", "tensorflow.python.ops.array_ops.batch_to_space_nd", "tensorflow.python.ops.gen_nn_ops.conv2d_backprop_input", "tensorflow.python.ops.gen_nn_ops.sparse_softmax_cross_entropy_with_logits", "tensorflow.python.framework.tensor_shape.vector", "tensorflow.python.ops.gen_nn_ops.in_top_kv2", "tensorflow.python.framework.tensor_shape.as_shape", "tensorflow.python.ops.array_ops.expand_dims" ], [ "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.keras.backend.batch_get_value", "tensorflow.python.ops.array_ops.split", "tensorflow.python.keras.backend.int_shape", "tensorflow.python.keras.utils.generic_utils.to_list", "tensorflow.python.keras.regularizers.get", "tensorflow.python.framework.ops.executing_eagerly_outside_functions", "tensorflow.python.keras.backend.dot", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.keras.utils.generic_utils.has_arg", "tensorflow.python.ops.state_ops.assign", "tensorflow.python.ops.gen_cudnn_rnn_ops.cudnn_rnn", "tensorflow.python.keras.backend.reverse", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.ops.array_ops.transpose", "tensorflow.python.keras.backend.bias_add", "tensorflow.python.keras.layers.deserialize", "tensorflow.python.util.tf_export.keras_export", "tensorflow.python.keras.backend.is_keras_tensor", "tensorflow.python.ops.array_ops.unstack", "tensorflow.python.eager.function.register", "tensorflow.python.util.nest.map_structure", "tensorflow.python.keras.constraints.get", "tensorflow.python.eager.function.defun_with_attributes", "tensorflow.python.keras.backend.flatten", "tensorflow.python.platform.tf_logging.warning", "tensorflow.python.util.nest.is_sequence", "tensorflow.python.ops.array_ops.zeros_like", "tensorflow.python.keras.activations.get", "tensorflow.python.keras.backend.in_train_phase", "tensorflow.python.keras.regularizers.serialize", "tensorflow.python.keras.backend.rnn", "tensorflow.python.ops.array_ops.ones_like", "tensorflow.python.eager.context.num_gpus", "tensorflow.python.keras.backend.batch_set_value", "tensorflow.python.keras.activations.serialize", "tensorflow.python.ops.array_ops.concat", "tensorflow.python.platform.tf_logging.warn", "tensorflow.python.keras.backend.dropout", "tensorflow.python.keras.constraints.serialize", "tensorflow.python.ops.array_ops.reshape", "tensorflow.python.keras.engine.input_spec.InputSpec", "tensorflow.python.keras.initializers.Ones", "tensorflow.python.keras.backend.set_value", "tensorflow.python.keras.initializers.get", "tensorflow.python.framework.tensor_shape.as_shape", "tensorflow.python.ops.array_ops.expand_dims", "tensorflow.python.keras.initializers.serialize", "tensorflow.python.util.nest.flatten", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.contrib.tensorrt.python.trt_convert.create_inference_graph", "tensorflow.python.summary.summary.scalar", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.platform.test.test_src_dir_path", "tensorflow.python.training.checkpoint_management.latest_checkpoint", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.keras.initializers.zeros", "tensorflow.python.layers.layers.conv2d", "tensorflow.python.training.training_util.get_global_step", "tensorflow.python.ops.math_ops.argmax", "tensorflow.python.ops.nn.relu6", "tensorflow.python.ops.losses.losses.sparse_softmax_cross_entropy", "tensorflow.python.platform.test.main", "tensorflow.python.ops.variable_scope.variable_scope", "tensorflow.python.ops.gen_array_ops.quantize_and_dequantize_v2", "tensorflow.python.ops.math_ops.matmul", "tensorflow.contrib.tensorrt.python.trt_convert.get_linked_tensorrt_version", "tensorflow.python.ops.math_ops.cast", "tensorflow.contrib.tensorrt.python.trt_convert.is_tensorrt_enabled", "tensorflow.python.framework.importer.import_graph_def", "tensorflow.python.ops.math_ops.reduce_mean", "tensorflow.python.training.adam.AdamOptimizer", "tensorflow.core.protobuf.config_pb2.ConfigProto", "tensorflow.python.ops.nn.bias_add", "tensorflow.python.ops.metrics.accuracy", "tensorflow.python.keras.datasets.mnist.load_data", "tensorflow.python.estimator.model_fn.EstimatorSpec", "tensorflow.python.framework.ops.Graph", "tensorflow.python.data.Dataset.from_tensor_slices", "tensorflow.python.platform.tf_logging.info", "tensorflow.python.data.experimental.map_and_batch", "tensorflow.python.framework.graph_util.convert_variables_to_constants", "tensorflow.python.estimator.run_config.RunConfig", "tensorflow.python.ops.array_ops.expand_dims", "tensorflow.python.training.saver.Saver", "tensorflow.python.keras.initializers.glorot_uniform" ], [ "tensorflow.python.util.deprecation.deprecated", "tensorflow.python.ops.init_ops.zeros_initializer", "tensorflow.python.util.tf_export.tf_export" ], [ "tensorflow.python.platform.tf_logging.info" ], [ "tensorflow.python.ops.variables.Variable.SaveSliceInfo", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.variable_scope.get_variable_scope", "tensorflow.python.ops.variable_scope.get_variable", "tensorflow.python.ops.init_ops.zeros_initializer", "tensorflow.python.distribute.distribution_strategy_context.get_strategy", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.ops.variable_scope.variable_scope", "tensorflow.python.ops.resource_variable_ops.is_resource_variable", "tensorflow.python.eager.context.executing_eagerly" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.13" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "2.7", "2.6", "1.4", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.12" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.5", "1.7", "1.4" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "2.4", "2.3", "2.9", "2.5", "2.2", "2.10" ] } ]
cgangwar11/pandas
[ "972f491cb7fdcc3c1c2cb9f05644128f13457f87" ]
[ "pandas/core/indexes/datetimes.py" ]
[ "from datetime import date, datetime, time, timedelta, tzinfo\nimport operator\nfrom typing import Optional\nimport warnings\n\nimport numpy as np\n\nfrom pandas._libs import NaT, Period, Timestamp, index as libindex, lib\nfrom pandas._libs.tslibs import (\n Resolution,\n ints_to_pydatetime,\n parsing,\n timezones,\n to_offset,\n)\nfrom pandas._libs.tslibs.offsets import prefix_mapping\nfrom pandas._typing import DtypeObj, Label\nfrom pandas.errors import InvalidIndexError\nfrom pandas.util._decorators import cache_readonly, doc\n\nfrom pandas.core.dtypes.common import (\n DT64NS_DTYPE,\n is_datetime64_any_dtype,\n is_datetime64_dtype,\n is_datetime64tz_dtype,\n is_float,\n is_integer,\n is_scalar,\n)\nfrom pandas.core.dtypes.missing import is_valid_nat_for_dtype\n\nfrom pandas.core.arrays.datetimes import DatetimeArray, tz_to_dtype\nimport pandas.core.common as com\nfrom pandas.core.indexes.base import Index, maybe_extract_name\nfrom pandas.core.indexes.datetimelike import DatetimeTimedeltaMixin\nfrom pandas.core.indexes.extension import inherit_names\nfrom pandas.core.tools.times import to_time\n\n\ndef _new_DatetimeIndex(cls, d):\n \"\"\"\n This is called upon unpickling, rather than the default which doesn't\n have arguments and breaks __new__\n \"\"\"\n if \"data\" in d and not isinstance(d[\"data\"], DatetimeIndex):\n # Avoid need to verify integrity by calling simple_new directly\n data = d.pop(\"data\")\n if not isinstance(data, DatetimeArray):\n # For backward compat with older pickles, we may need to construct\n # a DatetimeArray to adapt to the newer _simple_new signature\n tz = d.pop(\"tz\")\n freq = d.pop(\"freq\")\n dta = DatetimeArray._simple_new(data, dtype=tz_to_dtype(tz), freq=freq)\n else:\n dta = data\n for key in [\"tz\", \"freq\"]:\n # These are already stored in our DatetimeArray; if they are\n # also in the pickle and don't match, we have a problem.\n if key in d:\n assert d.pop(key) == getattr(dta, key)\n result = cls._simple_new(dta, **d)\n else:\n with warnings.catch_warnings():\n # TODO: If we knew what was going in to **d, we might be able to\n # go through _simple_new instead\n warnings.simplefilter(\"ignore\")\n result = cls.__new__(cls, **d)\n\n return result\n\n\n@inherit_names(\n [\"to_perioddelta\", \"to_julian_date\", \"strftime\", \"isocalendar\"]\n + DatetimeArray._field_ops\n + [\n method\n for method in DatetimeArray._datetimelike_methods\n if method not in (\"tz_localize\",)\n ],\n DatetimeArray,\n wrap=True,\n)\n@inherit_names([\"is_normalized\", \"_resolution_obj\"], DatetimeArray, cache=True)\n@inherit_names(\n [\n \"_bool_ops\",\n \"_object_ops\",\n \"_field_ops\",\n \"_datetimelike_ops\",\n \"_datetimelike_methods\",\n \"tz\",\n \"tzinfo\",\n \"dtype\",\n \"to_pydatetime\",\n \"_has_same_tz\",\n \"_format_native_types\",\n \"date\",\n \"time\",\n \"timetz\",\n ]\n + DatetimeArray._bool_ops,\n DatetimeArray,\n)\nclass DatetimeIndex(DatetimeTimedeltaMixin):\n \"\"\"\n Immutable ndarray-like of datetime64 data.\n\n Represented internally as int64, and which can be boxed to Timestamp objects\n that are subclasses of datetime and carry metadata.\n\n Parameters\n ----------\n data : array-like (1-dimensional), optional\n Optional datetime-like data to construct index with.\n freq : str or pandas offset object, optional\n One of pandas date offset strings or corresponding objects. The string\n 'infer' can be passed in order to set the frequency of the index as the\n inferred frequency upon creation.\n tz : pytz.timezone or dateutil.tz.tzfile or datetime.tzinfo or str\n Set the Timezone of the data.\n normalize : bool, default False\n Normalize start/end dates to midnight before generating date range.\n closed : {'left', 'right'}, optional\n Set whether to include `start` and `end` that are on the\n boundary. The default includes boundary points on either end.\n ambiguous : 'infer', bool-ndarray, 'NaT', default 'raise'\n When clocks moved backward due to DST, ambiguous times may arise.\n For example in Central European Time (UTC+01), when going from 03:00\n DST to 02:00 non-DST, 02:30:00 local time occurs both at 00:30:00 UTC\n and at 01:30:00 UTC. In such a situation, the `ambiguous` parameter\n dictates how ambiguous times should be handled.\n\n - 'infer' will attempt to infer fall dst-transition hours based on\n order\n - bool-ndarray where True signifies a DST time, False signifies a\n non-DST time (note that this flag is only applicable for ambiguous\n times)\n - 'NaT' will return NaT where there are ambiguous times\n - 'raise' will raise an AmbiguousTimeError if there are ambiguous times.\n dayfirst : bool, default False\n If True, parse dates in `data` with the day first order.\n yearfirst : bool, default False\n If True parse dates in `data` with the year first order.\n dtype : numpy.dtype or DatetimeTZDtype or str, default None\n Note that the only NumPy dtype allowed is ‘datetime64[ns]’.\n copy : bool, default False\n Make a copy of input ndarray.\n name : label, default None\n Name to be stored in the index.\n\n Attributes\n ----------\n year\n month\n day\n hour\n minute\n second\n microsecond\n nanosecond\n date\n time\n timetz\n dayofyear\n weekofyear\n week\n dayofweek\n weekday\n quarter\n tz\n freq\n freqstr\n is_month_start\n is_month_end\n is_quarter_start\n is_quarter_end\n is_year_start\n is_year_end\n is_leap_year\n inferred_freq\n\n Methods\n -------\n normalize\n strftime\n snap\n tz_convert\n tz_localize\n round\n floor\n ceil\n to_period\n to_perioddelta\n to_pydatetime\n to_series\n to_frame\n month_name\n day_name\n mean\n\n See Also\n --------\n Index : The base pandas Index type.\n TimedeltaIndex : Index of timedelta64 data.\n PeriodIndex : Index of Period data.\n to_datetime : Convert argument to datetime.\n date_range : Create a fixed-frequency DatetimeIndex.\n\n Notes\n -----\n To learn more about the frequency strings, please see `this link\n <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.\n \"\"\"\n\n _typ = \"datetimeindex\"\n\n _engine_type = libindex.DatetimeEngine\n _supports_partial_string_indexing = True\n\n _comparables = [\"name\", \"freqstr\", \"tz\"]\n _attributes = [\"name\", \"tz\", \"freq\"]\n\n _is_numeric_dtype = False\n\n _data: DatetimeArray\n tz: Optional[tzinfo]\n\n # --------------------------------------------------------------------\n # methods that dispatch to array and wrap result in DatetimeIndex\n\n @doc(DatetimeArray.tz_localize)\n def tz_localize(\n self, tz, ambiguous=\"raise\", nonexistent=\"raise\"\n ) -> \"DatetimeIndex\":\n arr = self._data.tz_localize(tz, ambiguous, nonexistent)\n return type(self)._simple_new(arr, name=self.name)\n\n @doc(DatetimeArray.to_period)\n def to_period(self, freq=None) -> \"DatetimeIndex\":\n arr = self._data.to_period(freq)\n return type(self)._simple_new(arr, name=self.name)\n\n # --------------------------------------------------------------------\n # Constructors\n\n def __new__(\n cls,\n data=None,\n freq=lib.no_default,\n tz=None,\n normalize=False,\n closed=None,\n ambiguous=\"raise\",\n dayfirst=False,\n yearfirst=False,\n dtype=None,\n copy=False,\n name=None,\n ):\n\n if is_scalar(data):\n raise TypeError(\n f\"{cls.__name__}() must be called with a \"\n f\"collection of some kind, {repr(data)} was passed\"\n )\n\n # - Cases checked above all return/raise before reaching here - #\n\n name = maybe_extract_name(name, data, cls)\n\n dtarr = DatetimeArray._from_sequence(\n data,\n dtype=dtype,\n copy=copy,\n tz=tz,\n freq=freq,\n dayfirst=dayfirst,\n yearfirst=yearfirst,\n ambiguous=ambiguous,\n )\n\n subarr = cls._simple_new(dtarr, name=name)\n return subarr\n\n @classmethod\n def _simple_new(cls, values: DatetimeArray, name: Label = None):\n assert isinstance(values, DatetimeArray), type(values)\n\n result = object.__new__(cls)\n result._data = values\n result.name = name\n result._cache = {}\n result._no_setting_name = False\n # For groupby perf. See note in indexes/base about _index_data\n result._index_data = values._data\n result._reset_identity()\n return result\n\n # --------------------------------------------------------------------\n\n @cache_readonly\n def _is_dates_only(self) -> bool:\n \"\"\"\n Return a boolean if we are only dates (and don't have a timezone)\n\n Returns\n -------\n bool\n \"\"\"\n from pandas.io.formats.format import _is_dates_only\n\n return self.tz is None and _is_dates_only(self._values)\n\n def __reduce__(self):\n\n # we use a special reduce here because we need\n # to simply set the .tz (and not reinterpret it)\n\n d = dict(data=self._data)\n d.update(self._get_attributes_dict())\n return _new_DatetimeIndex, (type(self), d), None\n\n def _convert_for_op(self, value):\n \"\"\"\n Convert value to be insertable to ndarray.\n \"\"\"\n if self._has_same_tz(value):\n return Timestamp(value).asm8\n raise ValueError(\"Passed item and index have different timezone\")\n\n def _is_comparable_dtype(self, dtype: DtypeObj) -> bool:\n \"\"\"\n Can we compare values of the given dtype to our own?\n \"\"\"\n if not is_datetime64_any_dtype(dtype):\n return False\n if self.tz is not None:\n # If we have tz, we can compare to tzaware\n return is_datetime64tz_dtype(dtype)\n # if we dont have tz, we can only compare to tznaive\n return is_datetime64_dtype(dtype)\n\n # --------------------------------------------------------------------\n # Rendering Methods\n\n def _mpl_repr(self):\n # how to represent ourselves to matplotlib\n return ints_to_pydatetime(self.asi8, self.tz)\n\n @property\n def _formatter_func(self):\n from pandas.io.formats.format import _get_format_datetime64\n\n formatter = _get_format_datetime64(is_dates_only=self._is_dates_only)\n return lambda x: f\"'{formatter(x, tz=self.tz)}'\"\n\n # --------------------------------------------------------------------\n # Set Operation Methods\n\n def union_many(self, others):\n \"\"\"\n A bit of a hack to accelerate unioning a collection of indexes.\n \"\"\"\n this = self\n\n for other in others:\n if not isinstance(this, DatetimeIndex):\n this = Index.union(this, other)\n continue\n\n if not isinstance(other, DatetimeIndex):\n try:\n other = DatetimeIndex(other)\n except TypeError:\n pass\n\n this, other = this._maybe_utc_convert(other)\n\n if this._can_fast_union(other):\n this = this._fast_union(other)\n else:\n this = Index.union(this, other)\n return this\n\n # --------------------------------------------------------------------\n\n def _get_time_micros(self):\n \"\"\"\n Return the number of microseconds since midnight.\n\n Returns\n -------\n ndarray[int64_t]\n \"\"\"\n values = self.asi8\n if self.tz is not None and not timezones.is_utc(self.tz):\n values = self._data._local_timestamps()\n\n nanos = values % (24 * 3600 * 1_000_000_000)\n micros = nanos // 1000\n\n micros[self._isnan] = -1\n return micros\n\n def to_series(self, keep_tz=lib.no_default, index=None, name=None):\n \"\"\"\n Create a Series with both index and values equal to the index keys\n useful with map for returning an indexer based on an index.\n\n Parameters\n ----------\n keep_tz : optional, defaults True\n Return the data keeping the timezone.\n\n If keep_tz is True:\n\n If the timezone is not set, the resulting\n Series will have a datetime64[ns] dtype.\n\n Otherwise the Series will have an datetime64[ns, tz] dtype; the\n tz will be preserved.\n\n If keep_tz is False:\n\n Series will have a datetime64[ns] dtype. TZ aware\n objects will have the tz removed.\n\n .. versionchanged:: 1.0.0\n The default value is now True. In a future version,\n this keyword will be removed entirely. Stop passing the\n argument to obtain the future behavior and silence the warning.\n\n index : Index, optional\n Index of resulting Series. If None, defaults to original index.\n name : str, optional\n Name of resulting Series. If None, defaults to name of original\n index.\n\n Returns\n -------\n Series\n \"\"\"\n from pandas import Series\n\n if index is None:\n index = self._shallow_copy()\n if name is None:\n name = self.name\n\n if keep_tz is not lib.no_default:\n if keep_tz:\n warnings.warn(\n \"The 'keep_tz' keyword in DatetimeIndex.to_series \"\n \"is deprecated and will be removed in a future version. \"\n \"You can stop passing 'keep_tz' to silence this warning.\",\n FutureWarning,\n stacklevel=2,\n )\n else:\n warnings.warn(\n \"Specifying 'keep_tz=False' is deprecated and this \"\n \"option will be removed in a future release. If \"\n \"you want to remove the timezone information, you \"\n \"can do 'idx.tz_convert(None)' before calling \"\n \"'to_series'.\",\n FutureWarning,\n stacklevel=2,\n )\n else:\n keep_tz = True\n\n if keep_tz and self.tz is not None:\n # preserve the tz & copy\n values = self.copy(deep=True)\n else:\n values = self._values.view(\"M8[ns]\").copy()\n\n return Series(values, index=index, name=name)\n\n def snap(self, freq=\"S\"):\n \"\"\"\n Snap time stamps to nearest occurring frequency.\n\n Returns\n -------\n DatetimeIndex\n \"\"\"\n # Superdumb, punting on any optimizing\n freq = to_offset(freq)\n\n snapped = np.empty(len(self), dtype=DT64NS_DTYPE)\n\n for i, v in enumerate(self):\n s = v\n if not freq.is_on_offset(s):\n t0 = freq.rollback(s)\n t1 = freq.rollforward(s)\n if abs(s - t0) < abs(t1 - s):\n s = t0\n else:\n s = t1\n snapped[i] = s\n\n dta = DatetimeArray(snapped, dtype=self.dtype)\n return DatetimeIndex._simple_new(dta, name=self.name)\n\n def _parsed_string_to_bounds(self, reso: Resolution, parsed: datetime):\n \"\"\"\n Calculate datetime bounds for parsed time string and its resolution.\n\n Parameters\n ----------\n reso : str\n Resolution provided by parsed string.\n parsed : datetime\n Datetime from parsed string.\n\n Returns\n -------\n lower, upper: pd.Timestamp\n \"\"\"\n assert isinstance(reso, Resolution), (type(reso), reso)\n valid_resos = {\n \"year\",\n \"month\",\n \"quarter\",\n \"day\",\n \"hour\",\n \"minute\",\n \"second\",\n \"minute\",\n \"second\",\n \"microsecond\",\n }\n if reso.attrname not in valid_resos:\n raise KeyError\n\n grp = reso.freq_group\n per = Period(parsed, freq=grp)\n start, end = per.start_time, per.end_time\n\n # GH 24076\n # If an incoming date string contained a UTC offset, need to localize\n # the parsed date to this offset first before aligning with the index's\n # timezone\n if parsed.tzinfo is not None:\n if self.tz is None:\n raise ValueError(\n \"The index must be timezone aware when indexing \"\n \"with a date string with a UTC offset\"\n )\n start = start.tz_localize(parsed.tzinfo).tz_convert(self.tz)\n end = end.tz_localize(parsed.tzinfo).tz_convert(self.tz)\n elif self.tz is not None:\n start = start.tz_localize(self.tz)\n end = end.tz_localize(self.tz)\n return start, end\n\n def _validate_partial_date_slice(self, reso: Resolution):\n assert isinstance(reso, Resolution), (type(reso), reso)\n if (\n self.is_monotonic\n and reso.attrname in [\"day\", \"hour\", \"minute\", \"second\"]\n and self._resolution_obj >= reso\n ):\n # These resolution/monotonicity validations came from GH3931,\n # GH3452 and GH2369.\n\n # See also GH14826\n raise KeyError\n\n if reso == \"microsecond\":\n # _partial_date_slice doesn't allow microsecond resolution, but\n # _parsed_string_to_bounds allows it.\n raise KeyError\n\n def get_loc(self, key, method=None, tolerance=None):\n \"\"\"\n Get integer location for requested label\n\n Returns\n -------\n loc : int\n \"\"\"\n if not is_scalar(key):\n raise InvalidIndexError(key)\n\n orig_key = key\n if is_valid_nat_for_dtype(key, self.dtype):\n key = NaT\n\n if isinstance(key, self._data._recognized_scalars):\n # needed to localize naive datetimes\n key = self._maybe_cast_for_get_loc(key)\n\n elif isinstance(key, str):\n try:\n return self._get_string_slice(key)\n except (TypeError, KeyError, ValueError, OverflowError):\n pass\n\n try:\n key = self._maybe_cast_for_get_loc(key)\n except ValueError as err:\n raise KeyError(key) from err\n\n elif isinstance(key, timedelta):\n # GH#20464\n raise TypeError(\n f\"Cannot index {type(self).__name__} with {type(key).__name__}\"\n )\n\n elif isinstance(key, time):\n if method is not None:\n raise NotImplementedError(\n \"cannot yet lookup inexact labels when key is a time object\"\n )\n return self.indexer_at_time(key)\n\n else:\n # unrecognized type\n raise KeyError(key)\n\n try:\n return Index.get_loc(self, key, method, tolerance)\n except KeyError as err:\n raise KeyError(orig_key) from err\n\n def _maybe_cast_for_get_loc(self, key) -> Timestamp:\n # needed to localize naive datetimes\n key = Timestamp(key)\n if key.tzinfo is None:\n key = key.tz_localize(self.tz)\n else:\n key = key.tz_convert(self.tz)\n return key\n\n def _maybe_cast_slice_bound(self, label, side: str, kind):\n \"\"\"\n If label is a string, cast it to datetime according to resolution.\n\n Parameters\n ----------\n label : object\n side : {'left', 'right'}\n kind : {'loc', 'getitem'} or None\n\n Returns\n -------\n label : object\n\n Notes\n -----\n Value of `side` parameter should be validated in caller.\n \"\"\"\n assert kind in [\"loc\", \"getitem\", None]\n\n if is_float(label) or isinstance(label, time) or is_integer(label):\n self._invalid_indexer(\"slice\", label)\n\n if isinstance(label, str):\n freq = getattr(self, \"freqstr\", getattr(self, \"inferred_freq\", None))\n parsed, reso = parsing.parse_time_string(label, freq)\n reso = Resolution.from_attrname(reso)\n lower, upper = self._parsed_string_to_bounds(reso, parsed)\n # lower, upper form the half-open interval:\n # [parsed, parsed + 1 freq)\n # because label may be passed to searchsorted\n # the bounds need swapped if index is reverse sorted and has a\n # length > 1 (is_monotonic_decreasing gives True for empty\n # and length 1 index)\n if self._is_strictly_monotonic_decreasing and len(self) > 1:\n return upper if side == \"left\" else lower\n return lower if side == \"left\" else upper\n else:\n return label\n\n def _get_string_slice(self, key: str, use_lhs: bool = True, use_rhs: bool = True):\n freq = getattr(self, \"freqstr\", getattr(self, \"inferred_freq\", None))\n parsed, reso = parsing.parse_time_string(key, freq)\n reso = Resolution.from_attrname(reso)\n loc = self._partial_date_slice(reso, parsed, use_lhs=use_lhs, use_rhs=use_rhs)\n return loc\n\n def slice_indexer(self, start=None, end=None, step=None, kind=None):\n \"\"\"\n Return indexer for specified label slice.\n Index.slice_indexer, customized to handle time slicing.\n\n In addition to functionality provided by Index.slice_indexer, does the\n following:\n\n - if both `start` and `end` are instances of `datetime.time`, it\n invokes `indexer_between_time`\n - if `start` and `end` are both either string or None perform\n value-based selection in non-monotonic cases.\n\n \"\"\"\n # For historical reasons DatetimeIndex supports slices between two\n # instances of datetime.time as if it were applying a slice mask to\n # an array of (self.hour, self.minute, self.seconds, self.microsecond).\n if isinstance(start, time) and isinstance(end, time):\n if step is not None and step != 1:\n raise ValueError(\"Must have step size of 1 with time slices\")\n return self.indexer_between_time(start, end)\n\n if isinstance(start, time) or isinstance(end, time):\n raise KeyError(\"Cannot mix time and non-time slice keys\")\n\n # Pandas supports slicing with dates, treated as datetimes at midnight.\n # https://github.com/pandas-dev/pandas/issues/31501\n if isinstance(start, date) and not isinstance(start, datetime):\n start = datetime.combine(start, time(0, 0))\n if isinstance(end, date) and not isinstance(end, datetime):\n end = datetime.combine(end, time(0, 0))\n\n try:\n return Index.slice_indexer(self, start, end, step, kind=kind)\n except KeyError:\n # For historical reasons DatetimeIndex by default supports\n # value-based partial (aka string) slices on non-monotonic arrays,\n # let's try that.\n if (start is None or isinstance(start, str)) and (\n end is None or isinstance(end, str)\n ):\n mask = True\n if start is not None:\n start_casted = self._maybe_cast_slice_bound(start, \"left\", kind)\n mask = start_casted <= self\n\n if end is not None:\n end_casted = self._maybe_cast_slice_bound(end, \"right\", kind)\n mask = (self <= end_casted) & mask\n\n indexer = mask.nonzero()[0][::step]\n if len(indexer) == len(self):\n return slice(None)\n else:\n return indexer\n else:\n raise\n\n # --------------------------------------------------------------------\n\n def is_type_compatible(self, typ) -> bool:\n return typ == self.inferred_type or typ == \"datetime\"\n\n @property\n def inferred_type(self) -> str:\n # b/c datetime is represented as microseconds since the epoch, make\n # sure we can't have ambiguous indexing\n return \"datetime64\"\n\n def indexer_at_time(self, time, asof=False):\n \"\"\"\n Return index locations of values at particular time of day\n (e.g. 9:30AM).\n\n Parameters\n ----------\n time : datetime.time or str\n Time passed in either as object (datetime.time) or as string in\n appropriate format (\"%H:%M\", \"%H%M\", \"%I:%M%p\", \"%I%M%p\",\n \"%H:%M:%S\", \"%H%M%S\", \"%I:%M:%S%p\", \"%I%M%S%p\").\n\n Returns\n -------\n values_at_time : array of integers\n\n See Also\n --------\n indexer_between_time : Get index locations of values between particular\n times of day.\n DataFrame.at_time : Select values at particular time of day.\n \"\"\"\n if asof:\n raise NotImplementedError(\"'asof' argument is not supported\")\n\n if isinstance(time, str):\n from dateutil.parser import parse\n\n time = parse(time).time()\n\n if time.tzinfo:\n if self.tz is None:\n raise ValueError(\"Index must be timezone aware.\")\n time_micros = self.tz_convert(time.tzinfo)._get_time_micros()\n else:\n time_micros = self._get_time_micros()\n micros = _time_to_micros(time)\n return (micros == time_micros).nonzero()[0]\n\n def indexer_between_time(\n self, start_time, end_time, include_start=True, include_end=True\n ):\n \"\"\"\n Return index locations of values between particular times of day\n (e.g., 9:00-9:30AM).\n\n Parameters\n ----------\n start_time, end_time : datetime.time, str\n Time passed either as object (datetime.time) or as string in\n appropriate format (\"%H:%M\", \"%H%M\", \"%I:%M%p\", \"%I%M%p\",\n \"%H:%M:%S\", \"%H%M%S\", \"%I:%M:%S%p\",\"%I%M%S%p\").\n include_start : bool, default True\n include_end : bool, default True\n\n Returns\n -------\n values_between_time : array of integers\n\n See Also\n --------\n indexer_at_time : Get index locations of values at particular time of day.\n DataFrame.between_time : Select values between particular times of day.\n \"\"\"\n start_time = to_time(start_time)\n end_time = to_time(end_time)\n time_micros = self._get_time_micros()\n start_micros = _time_to_micros(start_time)\n end_micros = _time_to_micros(end_time)\n\n if include_start and include_end:\n lop = rop = operator.le\n elif include_start:\n lop = operator.le\n rop = operator.lt\n elif include_end:\n lop = operator.lt\n rop = operator.le\n else:\n lop = rop = operator.lt\n\n if start_time <= end_time:\n join_op = operator.and_\n else:\n join_op = operator.or_\n\n mask = join_op(lop(start_micros, time_micros), rop(time_micros, end_micros))\n\n return mask.nonzero()[0]\n\n\nDatetimeIndex._add_logical_methods_disabled()\n\n\ndef date_range(\n start=None,\n end=None,\n periods=None,\n freq=None,\n tz=None,\n normalize=False,\n name=None,\n closed=None,\n **kwargs,\n) -> DatetimeIndex:\n \"\"\"\n Return a fixed frequency DatetimeIndex.\n\n Parameters\n ----------\n start : str or datetime-like, optional\n Left bound for generating dates.\n end : str or datetime-like, optional\n Right bound for generating dates.\n periods : int, optional\n Number of periods to generate.\n freq : str or DateOffset, default 'D'\n Frequency strings can have multiples, e.g. '5H'. See\n :ref:`here <timeseries.offset_aliases>` for a list of\n frequency aliases.\n tz : str or tzinfo, optional\n Time zone name for returning localized DatetimeIndex, for example\n 'Asia/Hong_Kong'. By default, the resulting DatetimeIndex is\n timezone-naive.\n normalize : bool, default False\n Normalize start/end dates to midnight before generating date range.\n name : str, default None\n Name of the resulting DatetimeIndex.\n closed : {None, 'left', 'right'}, optional\n Make the interval closed with respect to the given frequency to\n the 'left', 'right', or both sides (None, the default).\n **kwargs\n For compatibility. Has no effect on the result.\n\n Returns\n -------\n rng : DatetimeIndex\n\n See Also\n --------\n DatetimeIndex : An immutable container for datetimes.\n timedelta_range : Return a fixed frequency TimedeltaIndex.\n period_range : Return a fixed frequency PeriodIndex.\n interval_range : Return a fixed frequency IntervalIndex.\n\n Notes\n -----\n Of the four parameters ``start``, ``end``, ``periods``, and ``freq``,\n exactly three must be specified. If ``freq`` is omitted, the resulting\n ``DatetimeIndex`` will have ``periods`` linearly spaced elements between\n ``start`` and ``end`` (closed on both sides).\n\n To learn more about the frequency strings, please see `this link\n <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.\n\n Examples\n --------\n **Specifying the values**\n\n The next four examples generate the same `DatetimeIndex`, but vary\n the combination of `start`, `end` and `periods`.\n\n Specify `start` and `end`, with the default daily frequency.\n\n >>> pd.date_range(start='1/1/2018', end='1/08/2018')\n DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',\n '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08'],\n dtype='datetime64[ns]', freq='D')\n\n Specify `start` and `periods`, the number of periods (days).\n\n >>> pd.date_range(start='1/1/2018', periods=8)\n DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',\n '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08'],\n dtype='datetime64[ns]', freq='D')\n\n Specify `end` and `periods`, the number of periods (days).\n\n >>> pd.date_range(end='1/1/2018', periods=8)\n DatetimeIndex(['2017-12-25', '2017-12-26', '2017-12-27', '2017-12-28',\n '2017-12-29', '2017-12-30', '2017-12-31', '2018-01-01'],\n dtype='datetime64[ns]', freq='D')\n\n Specify `start`, `end`, and `periods`; the frequency is generated\n automatically (linearly spaced).\n\n >>> pd.date_range(start='2018-04-24', end='2018-04-27', periods=3)\n DatetimeIndex(['2018-04-24 00:00:00', '2018-04-25 12:00:00',\n '2018-04-27 00:00:00'],\n dtype='datetime64[ns]', freq=None)\n\n **Other Parameters**\n\n Changed the `freq` (frequency) to ``'M'`` (month end frequency).\n\n >>> pd.date_range(start='1/1/2018', periods=5, freq='M')\n DatetimeIndex(['2018-01-31', '2018-02-28', '2018-03-31', '2018-04-30',\n '2018-05-31'],\n dtype='datetime64[ns]', freq='M')\n\n Multiples are allowed\n\n >>> pd.date_range(start='1/1/2018', periods=5, freq='3M')\n DatetimeIndex(['2018-01-31', '2018-04-30', '2018-07-31', '2018-10-31',\n '2019-01-31'],\n dtype='datetime64[ns]', freq='3M')\n\n `freq` can also be specified as an Offset object.\n\n >>> pd.date_range(start='1/1/2018', periods=5, freq=pd.offsets.MonthEnd(3))\n DatetimeIndex(['2018-01-31', '2018-04-30', '2018-07-31', '2018-10-31',\n '2019-01-31'],\n dtype='datetime64[ns]', freq='3M')\n\n Specify `tz` to set the timezone.\n\n >>> pd.date_range(start='1/1/2018', periods=5, tz='Asia/Tokyo')\n DatetimeIndex(['2018-01-01 00:00:00+09:00', '2018-01-02 00:00:00+09:00',\n '2018-01-03 00:00:00+09:00', '2018-01-04 00:00:00+09:00',\n '2018-01-05 00:00:00+09:00'],\n dtype='datetime64[ns, Asia/Tokyo]', freq='D')\n\n `closed` controls whether to include `start` and `end` that are on the\n boundary. The default includes boundary points on either end.\n\n >>> pd.date_range(start='2017-01-01', end='2017-01-04', closed=None)\n DatetimeIndex(['2017-01-01', '2017-01-02', '2017-01-03', '2017-01-04'],\n dtype='datetime64[ns]', freq='D')\n\n Use ``closed='left'`` to exclude `end` if it falls on the boundary.\n\n >>> pd.date_range(start='2017-01-01', end='2017-01-04', closed='left')\n DatetimeIndex(['2017-01-01', '2017-01-02', '2017-01-03'],\n dtype='datetime64[ns]', freq='D')\n\n Use ``closed='right'`` to exclude `start` if it falls on the boundary.\n\n >>> pd.date_range(start='2017-01-01', end='2017-01-04', closed='right')\n DatetimeIndex(['2017-01-02', '2017-01-03', '2017-01-04'],\n dtype='datetime64[ns]', freq='D')\n \"\"\"\n if freq is None and com.any_none(periods, start, end):\n freq = \"D\"\n\n dtarr = DatetimeArray._generate_range(\n start=start,\n end=end,\n periods=periods,\n freq=freq,\n tz=tz,\n normalize=normalize,\n closed=closed,\n **kwargs,\n )\n return DatetimeIndex._simple_new(dtarr, name=name)\n\n\ndef bdate_range(\n start=None,\n end=None,\n periods=None,\n freq=\"B\",\n tz=None,\n normalize=True,\n name=None,\n weekmask=None,\n holidays=None,\n closed=None,\n **kwargs,\n) -> DatetimeIndex:\n \"\"\"\n Return a fixed frequency DatetimeIndex, with business day as the default\n frequency.\n\n Parameters\n ----------\n start : str or datetime-like, default None\n Left bound for generating dates.\n end : str or datetime-like, default None\n Right bound for generating dates.\n periods : int, default None\n Number of periods to generate.\n freq : str or DateOffset, default 'B' (business daily)\n Frequency strings can have multiples, e.g. '5H'.\n tz : str or None\n Time zone name for returning localized DatetimeIndex, for example\n Asia/Beijing.\n normalize : bool, default False\n Normalize start/end dates to midnight before generating date range.\n name : str, default None\n Name of the resulting DatetimeIndex.\n weekmask : str or None, default None\n Weekmask of valid business days, passed to ``numpy.busdaycalendar``,\n only used when custom frequency strings are passed. The default\n value None is equivalent to 'Mon Tue Wed Thu Fri'.\n holidays : list-like or None, default None\n Dates to exclude from the set of valid business days, passed to\n ``numpy.busdaycalendar``, only used when custom frequency strings\n are passed.\n closed : str, default None\n Make the interval closed with respect to the given frequency to\n the 'left', 'right', or both sides (None).\n **kwargs\n For compatibility. Has no effect on the result.\n\n Returns\n -------\n DatetimeIndex\n\n Notes\n -----\n Of the four parameters: ``start``, ``end``, ``periods``, and ``freq``,\n exactly three must be specified. Specifying ``freq`` is a requirement\n for ``bdate_range``. Use ``date_range`` if specifying ``freq`` is not\n desired.\n\n To learn more about the frequency strings, please see `this link\n <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.\n\n Examples\n --------\n Note how the two weekend days are skipped in the result.\n\n >>> pd.bdate_range(start='1/1/2018', end='1/08/2018')\n DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',\n '2018-01-05', '2018-01-08'],\n dtype='datetime64[ns]', freq='B')\n \"\"\"\n if freq is None:\n msg = \"freq must be specified for bdate_range; use date_range instead\"\n raise TypeError(msg)\n\n if isinstance(freq, str) and freq.startswith(\"C\"):\n try:\n weekmask = weekmask or \"Mon Tue Wed Thu Fri\"\n freq = prefix_mapping[freq](holidays=holidays, weekmask=weekmask)\n except (KeyError, TypeError) as err:\n msg = f\"invalid custom frequency string: {freq}\"\n raise ValueError(msg) from err\n elif holidays or weekmask:\n msg = (\n \"a custom frequency string is required when holidays or \"\n f\"weekmask are passed, got frequency {freq}\"\n )\n raise ValueError(msg)\n\n return date_range(\n start=start,\n end=end,\n periods=periods,\n freq=freq,\n tz=tz,\n normalize=normalize,\n name=name,\n closed=closed,\n **kwargs,\n )\n\n\ndef _time_to_micros(time_obj: time) -> int:\n seconds = time_obj.hour * 60 * 60 + 60 * time_obj.minute + time_obj.second\n return 1_000_000 * seconds + time_obj.microsecond\n" ]
[ [ "pandas._libs.tslibs.ints_to_pydatetime", "pandas.Series", "pandas.core.arrays.datetimes.tz_to_dtype", "pandas.io.formats.format._is_dates_only", "pandas.core.dtypes.common.is_datetime64tz_dtype", "pandas.core.arrays.datetimes.DatetimeArray", "pandas.core.dtypes.common.is_datetime64_dtype", "pandas._libs.tslibs.Resolution.from_attrname", "pandas.core.tools.times.to_time", "pandas.core.arrays.datetimes.DatetimeArray._generate_range", "pandas.core.indexes.extension.inherit_names", "pandas._libs.tslibs.to_offset", "pandas.core.indexes.base.Index.slice_indexer", "pandas.core.common.any_none", "pandas.core.indexes.base.maybe_extract_name", "pandas.core.dtypes.common.is_float", "pandas._libs.Period", "pandas.core.indexes.base.Index.union", "pandas.errors.InvalidIndexError", "pandas.core.dtypes.common.is_datetime64_any_dtype", "pandas._libs.Timestamp", "pandas.core.dtypes.missing.is_valid_nat_for_dtype", "pandas.core.dtypes.common.is_scalar", "pandas._libs.tslibs.parsing.parse_time_string", "pandas.core.indexes.base.Index.get_loc", "pandas.core.dtypes.common.is_integer", "pandas._libs.tslibs.timezones.is_utc", "pandas.io.formats.format._get_format_datetime64", "pandas.util._decorators.doc", "pandas.core.arrays.datetimes.DatetimeArray._from_sequence" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
csiu/kick
[ "0ebc9166074b702fc8b5835685ad102957ab349c" ]
[ "src/python/sim_doc.py" ]
[ "import sys\nsys.path.append(\"/Users/csiu/repo/kick/src/python\")\n\nimport argparse\nimport custom\nimport pandas as pd\nimport numpy as np\nimport re\nimport os\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.utils.extmath import randomized_svd\nfrom sklearn.metrics import pairwise_distances\n\nusage = \"\"\"\nFor finding similar documents\n\"\"\"\n\ndef get_args():\n parser = argparse.ArgumentParser(description=usage)\n\n parser.add_argument('-s', '--num_singular_values', default=100, type=int,\n help=\"Number of singular values to use from SVD\")\n\n parser.add_argument('-n', '--num_results', default=None, type=int,\n help=\"Number of similar documents to print in the results\")\n\n parser.add_argument('-w', '--term_weight', default=\"tfidf\",\n choices=[\"tfidf\", \"raw\"],\n help=\"How should terms in document be weighted? 'tfidf' or 'raw' counts\")\n\n parser.add_argument('-d', '--distance', default=\"cosine\",\n help=\"Metric for calculating the distance between documents.\")\n\n parser.add_argument('-i', '--document0_id', default=None, type=int,\n help=\"Kickstarter ID of query document\")\n\n parser.add_argument('-c', '--cache_dir', default=\".\",\n help=\"Specify cache dir\")\n\n parser.add_argument('-v', '--verbose', action='store_true')\n\n args = parser.parse_args()\n\n return(args)\n\ndef get_data():\n \"\"\"\n Output dataframe w/ 2 columns: \"id\", \"document\"\n \"\"\"\n # Get data\n dk = custom.DatabaseKick()\n cur = dk.connect()\n\n cur.execute(\"SELECT id, concat_ws(name, blurb) FROM info\")\n rows = cur.fetchall()\n df = pd.DataFrame(rows, columns=[\"id\", \"document\"])\n\n dk.disconnect()\n\n return(df)\n\ndef preprocess_data(df):\n \"\"\"\n Preprocess 'document' of dataframe by\n - to lowercase\n - remove nonletters\n - tokenize\n - remove stopwords\n - stem\n Dataframe will contain additional 'doc_processed' column\n and df['doc_processed'] will be returned\n \"\"\"\n\n def join_output(func):\n \"\"\"\n Decorator function to join list output to string\n \"\"\"\n def func_wrapper(text, *arg, **karg):\n return ' '.join(func(text, *arg, **karg))\n return func_wrapper\n\n def doc_to_string(doc):\n \"\"\"\n Replace None -> empty string, and\n text newlines (\\n, \\r) -> whitespace\n \"\"\"\n if doc == None:\n return(\"\")\n else:\n return(re.sub(\"[\\n\\r]\", \"\", doc))\n\n df['document'] = df['document'].apply(\n lambda x: doc_to_string(x))\n\n text_processing = join_output(custom.text_processing)\n df['doc_processed'] = df['document'].apply(\n lambda x: text_processing(x, method=\"stem\"))\n\n return(df['doc_processed'])\n\ndef compute_distance(U, i=None, sort=False, top_n=None, metric='euclidean'):\n \"\"\"\n Compute distance of document U[i] with all documents in U\n \"\"\"\n if i != None:\n index_document0 = df[df[\"id\"] == i].index.tolist()\n else:\n index_document0 = 0\n\n document0 = np.asmatrix(U[index_document0])\n\n dist = pairwise_distances(document0, U, metric=metric)\n df_dist = pd.DataFrame(np.transpose(dist), columns=[\"dist\"])\n\n if sort:\n df_dist.sort_values(by=\"dist\", inplace=True)\n\n if top_n != None:\n assert type(top_n) is int\n df_dist = df_dist.head(top_n)\n\n return(df_dist)\n\n\nif __name__ == '__main__':\n args = get_args()\n num_singular_values = args.num_singular_values\n document0_id = args.document0_id\n num_results = args.num_results\n cache_dir = args.cache_dir\n verbose = args.verbose\n term_weight = args.term_weight\n distance_metric = args.distance\n\n preprocess_file = os.path.join(os.path.abspath(cache_dir),\n \"preprocessed.pkl\")\n\n\n msg = \"# Getting and preprocessing data...\"\n if os.path.isfile(preprocess_file):\n if verbose: print(msg, \"from cache...\")\n df = pd.read_pickle(preprocess_file)\n else:\n if verbose: print(msg)\n df = get_data()\n _ = preprocess_data(df)\n\n df.to_pickle(preprocess_file)\n\n if term_weight == \"raw\":\n if verbose: print(\"# Making count matrix...\")\n cv = CountVectorizer()\n X = cv.fit_transform(df['doc_processed'])\n else:\n if verbose: print(\"# Making TF-IDF matrix...\")\n vectorizer = TfidfVectorizer()\n X = vectorizer.fit_transform(df['doc_processed'])\n\n if verbose: print(\"# Computing SVD for %s singular values...\" %\n num_singular_values)\n U, s, Vh = randomized_svd(X, n_components=num_singular_values,\n n_iter=5, random_state=5)\n\n if verbose: print(\"# Computing distances (%s)...\" % distance_metric)\n top_n = compute_distance(U, i=document0_id,\n sort=True, top_n=num_results,\n metric=distance_metric)\n\n if verbose: print(\"# Printing results...\")\n results = []\n counter = 0\n for index, row in df.iloc[top_n.index].iterrows():\n row[\"dist\"] = top_n.iloc[counter][\"dist\"]\n results.append(row)\n counter += 1\n\n print('>> %s | %s' % (row['id'], row['doc_processed']),\n row['document'], \"\\n\", sep=\"\\n\")\n" ]
[ [ "sklearn.metrics.pairwise_distances", "sklearn.utils.extmath.randomized_svd", "pandas.DataFrame", "numpy.asmatrix", "sklearn.feature_extraction.text.CountVectorizer", "numpy.transpose", "pandas.read_pickle", "sklearn.feature_extraction.text.TfidfVectorizer" ] ]
[ { "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": [] } ]
virgile-hernicot/SPIN
[ "21871e3d333ef37866402ae21498b331aa771b2d" ]
[ "datasets/preprocess/mpi_inf_3dhp.py" ]
[ "import os\nimport sys\nimport cv2\nimport glob\nimport h5py\nimport json\nimport numpy as np\nimport scipy.io as sio\nimport scipy.misc\nfrom .read_openpose import read_openpose\n\ndef read_calibration(calib_file, vid_list):\n Ks, Rs, Ts = [], [], []\n file = open(calib_file, 'r')\n content = file.readlines()\n for vid_i in vid_list:\n K = np.array([float(s) for s in content[vid_i*7+5][11:-2].split()])\n K = np.reshape(K, (4, 4))\n RT = np.array([float(s) for s in content[vid_i*7+6][11:-2].split()])\n RT = np.reshape(RT, (4, 4))\n R = RT[:3,:3]\n T = RT[:3,3]/1000\n Ks.append(K)\n Rs.append(R)\n Ts.append(T)\n return Ks, Rs, Ts\n \ndef train_data(dataset_path, openpose_path, out_path, joints_idx, scaleFactor, extract_img=False, fits_3d=None):\n\n joints17_idx = [4, 18, 19, 20, 23, 24, 25, 3, 5, 6, 7, 9, 10, 11, 14, 15, 16]\n\n h, w = 2048, 2048\n imgnames_, scales_, centers_ = [], [], []\n parts_, Ss_, openposes_ = [], [], []\n\n # training data\n user_list = range(1,9)\n seq_list = range(1,3)\n vid_list = list(range(3)) + list(range(4,9))\n\n counter = 0\n\n for user_i in user_list:\n for seq_i in seq_list:\n seq_path = os.path.join(dataset_path,\n 'S' + str(user_i),\n 'Seq' + str(seq_i))\n # mat file with annotations\n annot_file = os.path.join(seq_path, 'annot.mat')\n annot2 = sio.loadmat(annot_file)['annot2']\n annot3 = sio.loadmat(annot_file)['annot3']\n # calibration file and camera parameters\n calib_file = os.path.join(seq_path, 'camera.calibration')\n Ks, Rs, Ts = read_calibration(calib_file, vid_list)\n\n for j, vid_i in enumerate(vid_list):\n\n # image folder\n imgs_path = os.path.join(seq_path, \n 'imageFrames',\n 'video_' + str(vid_i))\n\n # extract frames from video file\n if extract_img:\n\n # if doesn't exist\n if not os.path.isdir(imgs_path):\n os.makedirs(imgs_path)\n\n # video file\n vid_file = os.path.join(seq_path,\n 'imageSequence',\n 'video_' + str(vid_i) + '.avi')\n vidcap = cv2.VideoCapture(vid_file)\n\n # process video\n frame = 0\n while 1:\n # extract all frames\n success, image = vidcap.read()\n if not success:\n break\n frame += 1\n # image name\n imgname = os.path.join(imgs_path,\n 'frame_%06d.jpg' % frame)\n # save image\n cv2.imwrite(imgname, image)\n\n # per frame\n cam_aa = cv2.Rodrigues(Rs[j])[0].T[0]\n pattern = os.path.join(imgs_path, '*.jpg')\n img_list = glob.glob(pattern)\n for i, img_i in enumerate(img_list):\n\n # for each image we store the relevant annotations\n img_name = img_i.split('/')[-1]\n img_view = os.path.join('S' + str(user_i),\n 'Seq' + str(seq_i),\n 'imageFrames',\n 'video_' + str(vid_i),\n img_name)\n joints = np.reshape(annot2[vid_i][0][i], (28, 2))[joints17_idx]\n S17 = np.reshape(annot3[vid_i][0][i], (28, 3))/1000\n S17 = S17[joints17_idx] - S17[4] # 4 is the root\n bbox = [min(joints[:,0]), min(joints[:,1]),\n max(joints[:,0]), max(joints[:,1])]\n center = [(bbox[2]+bbox[0])/2, (bbox[3]+bbox[1])/2]\n scale = scaleFactor*max(bbox[2]-bbox[0], bbox[3]-bbox[1])/200\n\n # check that all joints are visible\n x_in = np.logical_and(joints[:, 0] < w, joints[:, 0] >= 0)\n y_in = np.logical_and(joints[:, 1] < h, joints[:, 1] >= 0)\n ok_pts = np.logical_and(x_in, y_in)\n if np.sum(ok_pts) < len(joints_idx):\n continue\n \n part = np.zeros([24,3])\n part[joints_idx] = np.hstack([joints, np.ones([17,1])])\n json_file = os.path.join(openpose_path, 'mpi_inf_3dhp',\n img_view.replace('.jpg', '_keypoints.json'))\n openpose = read_openpose(json_file, part, 'mpi_inf_3dhp')\n\n S = np.zeros([24,4])\n S[joints_idx] = np.hstack([S17, np.ones([17,1])])\n\n # because of the dataset size, we only keep every 10th frame\n counter += 1\n if counter % 10 != 1:\n continue\n\n # store the data\n imgnames_.append(img_view)\n centers_.append(center)\n scales_.append(scale)\n parts_.append(part)\n Ss_.append(S)\n openposes_.append(openpose)\n \n # store the data struct\n if not os.path.isdir(out_path):\n os.makedirs(out_path)\n out_file = os.path.join(out_path, 'mpi_inf_3dhp_train.npz')\n if fits_3d is not None:\n fits_3d = np.load(fits_3d)\n np.savez(out_file, imgname=imgnames_,\n center=centers_,\n scale=scales_,\n part=parts_,\n pose=fits_3d['pose'],\n shape=fits_3d['shape'],\n has_smpl=fits_3d['has_smpl'],\n S=Ss_,\n openpose=openposes_)\n else:\n np.savez(out_file, imgname=imgnames_,\n center=centers_,\n scale=scales_,\n part=parts_,\n S=Ss_,\n openpose=openposes_) \n \n \ndef test_data(dataset_path, out_path, joints_idx, scaleFactor):\n\n joints17_idx = [14, 11, 12, 13, 8, 9, 10, 15, 1, 16, 0, 5, 6, 7, 2, 3, 4]\n\n imgnames_, scales_, centers_, parts_, Ss_ = [], [], [], [], []\n\n # training data\n user_list = range(1,7)\n\n for user_i in user_list:\n seq_path = os.path.join(dataset_path,\n 'mpi_inf_3dhp_test_set',\n 'TS' + str(user_i))\n # mat file with annotations\n annot_file = os.path.join(seq_path, 'annot_data.mat')\n mat_as_h5 = h5py.File(annot_file, 'r')\n annot2 = np.array(mat_as_h5['annot2'])\n annot3 = np.array(mat_as_h5['univ_annot3'])\n valid = np.array(mat_as_h5['valid_frame'])\n for frame_i, valid_i in enumerate(valid):\n if valid_i == 0:\n continue\n img_name = os.path.join('mpi_inf_3dhp_test_set',\n 'TS' + str(user_i),\n 'imageSequence',\n 'img_' + str(frame_i+1).zfill(6) + '.jpg')\n\n joints = annot2[frame_i,0,joints17_idx,:]\n S17 = annot3[frame_i,0,joints17_idx,:]/1000\n S17 = S17 - S17[0]\n\n bbox = [min(joints[:,0]), min(joints[:,1]),\n max(joints[:,0]), max(joints[:,1])]\n center = [(bbox[2]+bbox[0])/2, (bbox[3]+bbox[1])/2]\n scale = scaleFactor*max(bbox[2]-bbox[0], bbox[3]-bbox[1])/200\n\n # check that all joints are visible\n img_file = os.path.join(dataset_path, img_name)\n I = scipy.misc.imread(img_file)\n h, w, _ = I.shape\n x_in = np.logical_and(joints[:, 0] < w, joints[:, 0] >= 0)\n y_in = np.logical_and(joints[:, 1] < h, joints[:, 1] >= 0)\n ok_pts = np.logical_and(x_in, y_in)\n if np.sum(ok_pts) < len(joints_idx):\n continue\n\n part = np.zeros([24,3])\n part[joints_idx] = np.hstack([joints, np.ones([17,1])])\n\n S = np.zeros([24,4])\n S[joints_idx] = np.hstack([S17, np.ones([17,1])])\n\n # store the data\n imgnames_.append(img_name)\n centers_.append(center)\n scales_.append(scale)\n parts_.append(part)\n Ss_.append(S)\n\n # store the data struct\n if not os.path.isdir(out_path):\n os.makedirs(out_path)\n out_file = os.path.join(out_path, 'mpi_inf_3dhp_test.npz')\n np.savez(out_file, imgname=imgnames_,\n center=centers_,\n scale=scales_,\n part=parts_,\n S=Ss_) \n\ndef mpi_inf_3dhp_extract(dataset_path, openpose_path, out_path, mode, extract_img=False, static_fits=None):\n\n scaleFactor = 1.2\n joints_idx = [14, 3, 4, 5, 2, 1, 0, 16, 12, 17, 18, 9, 10, 11, 8, 7, 6]\n \n if static_fits is not None:\n fits_3d = os.path.join(static_fits, \n 'mpi-inf-3dhp_mview_fits.npz')\n else:\n fits_3d = None\n \n if mode == 'train':\n train_data(dataset_path, openpose_path, out_path, \n joints_idx, scaleFactor, extract_img=extract_img, fits_3d=fits_3d)\n elif mode == 'test':\n test_data(dataset_path, out_path, joints_idx, scaleFactor)\n" ]
[ [ "numpy.savez", "numpy.logical_and", "numpy.reshape", "scipy.io.loadmat", "numpy.ones", "numpy.load", "numpy.array", "numpy.zeros", "numpy.sum" ] ]
[ { "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": [] } ]
4k4xs4pH1r3/tf_rl_tutorial
[ "c58d10c60cfd79b2e0661b4a49cccae8d4584c57" ]
[ "tf_rl_tutorial/models.py" ]
[ "# Copyright 2016 Mandiant, A FireEye Company\n# Authors: Brian Jones\n# License: Apache 2.0\n\n''' Model classes for \"Relational Learning with TensorFlow\" tutorial '''\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom .util import ContrastiveTrainingProvider\n\n\ndef least_squares_objective(output, target, add_bias=True):\n ''' Creates final model output and loss for least squares objective\n\n Args:\n output: Model output\n target: Training target placeholder\n add_bias: If True, a bias Variable will be added to the output\n\n Returns:\n tuple (final output, loss)\n '''\n y = output\n if add_bias:\n bias = tf.Variable([0.0])\n y = output + bias\n loss = tf.reduce_sum(tf.square(y - target))\n return y, loss\n\n\ndef logistic_objective(output, target, add_bias=True):\n ''' Creates final model output and loss for logistic objective\n\n Args:\n output: Model output\n target: Training target placeholder\n add_bias: If True, a bias Variable will be added to the output\n\n Returns:\n tuple (final output, loss)\n '''\n y = output\n if add_bias:\n bias = tf.Variable([0.0])\n y = output + bias\n sig_y = tf.clip_by_value(tf.sigmoid(y), 0.001, 0.999) # avoid NaNs\n loss = -tf.reduce_sum(target*tf.log(sig_y) + (1-target)*tf.log(1-sig_y))\n return sig_y, loss\n\n\ndef ranking_margin_objective(output, margin=1.0):\n ''' Create final model output and loss for pairwise ranking margin objective\n \n Loss for single pair (f(p), f(n)) = [margin - f(p) + f(n)]+\n This only works when given model output on alternating positive/negative \n pairs: [pos,neg,pos,neg,...]. TODO: check target placeholder\n at runtime to make sure this is the case?\n \n Args:\n output: Model output\n margin: The margin value for the pairwise hinge loss\n\n Returns:\n tuple (final output, loss)\n '''\n y_pairs = tf.reshape(output, [-1,2]) # fold: 1 x n -> [n/2 x 2]\n pos_scores, neg_scores = tf.split(1, 2, y_pairs) # separate pairs\n hinge_losses = tf.nn.relu(margin - pos_scores + neg_scores)\n total_hinge_loss = tf.reduce_sum(hinge_losses)\n return output, total_hinge_loss\n\n\ndef sparse_maxnorm_update(var_matrix, indices, maxnorm=1.0):\n '''Sparse update operation that ensures selected rows in var_matrix \n do not have a Euclidean norm greater than maxnorm. Rows that exceed \n it are scaled to length.\n \n Args:\n var_matrix: 2D mutable tensor (Variable) to operate on\n indices: 1D tensor with the row indices to constrain\n maxnorm: the maximum Euclidean norm\n\n Returns:\n An operation that will update var_matrix when run in a Session\n '''\n selected_rows = tf.nn.embedding_lookup(var_matrix, indices)\n row_norms = tf.sqrt(tf.reduce_sum(tf.square(selected_rows), 1))\n scaling = maxnorm / tf.maximum(row_norms, maxnorm)\n scaled = selected_rows * tf.expand_dims(scaling, 1)\n return tf.scatter_update(var_matrix, indices, scaled)\n\n\ndef dense_maxnorm_update(var_matrix, maxnorm=1.0):\n '''Dense update operation that ensures all rows in var_matrix \n do not have a Euclidean norm greater than maxnorm. Rows that exceed \n it are scaled to length.\n \n Args:\n var_matrix: 2D mutable tensor (Variable) to operate on\n maxnorm: the maximum Euclidean norm\n \n Returns:\n An operation that will update var_matrix when run in a Session\n '''\n row_norms = tf.sqrt(tf.reduce_sum(tf.square(var_matrix), 1))\n scaling = maxnorm / tf.maximum(row_norms, maxnorm)\n scaled = var_matrix * tf.expand_dims(scaling, 1)\n return tf.assign(var_matrix, scaled)\n\n\ndef dense_maxnorm(var_matrix, maxnorm=1.0):\n '''Similar to dense_maxnorm_update(), except this returns a new Tensor\n instead of an operation that modifies var_matrix.\n\n Args:\n var_matrix: 2D tensor (Variable)\n maxnorm: the maximum Euclidean norm\n\n Returns:\n A new tensor where all rows have been scaled as necessary\n '''\n axis_norms = tf.sqrt(tf.reduce_sum(tf.square(var_matrix), 1))\n scaling = maxnorm / tf.maximum(axis_norms, maxnorm)\n return var_matrix * tf.expand_dims(scaling, 1)\n\n\nclass BaseModel(object):\n ''' Base class for embedding-based relational learning models that use \n maxnorm regularization. Subclasses must implement _create_model() and\n populate self.train_step, and can optionally populate self.post_step for \n post-processing.\n \n Note: When model_type is 'ranking_margin', the mini-batch provider returned\n by _create_batch_provider() must provide instances in alternating \n pos/neg pairs: [pos, neg, pos, neg, ...]. This is satisfied when using \n ContrastiveTrainingProvider; be careful if you use a different one.\n \n Args:\n embedding_size: Embedding vector length\n maxnorm: Maximum Euclidean norm for embedding vectors\n batch_pos_cnt: Number of positive examples to use in each mini-batch\n max_iter: Maximum number of optimization iterations to perform\n model_type: Possible values:\n 'least_squares': squared loss on 0/1 targets\n 'logistic': sigmoid link function, crossent loss on 0/1 targets\n 'ranking_margin': ranking margin on pos/neg pairs\n add_bias: If True, a bias Variable will be added to the output for\n least_squares and logistic models. \n opt: An optimizer object to use. If None, the default optimizer is\n tf.train.AdagradOptimizer(1.0) \n \n TODO: add support for other regularizers like L2 \n '''\n\n def __init__(self, embedding_size, maxnorm=1.0,\n batch_pos_cnt=100, max_iter=1000, \n model_type='least_squares', add_bias=True, \n opt=None):\n self.embedding_size = embedding_size\n self.maxnorm = maxnorm\n self.batch_pos_cnt = batch_pos_cnt\n self.max_iter = max_iter\n self.model_type = model_type\n self.add_bias = add_bias\n if opt is None:\n opt = tf.train.AdagradOptimizer(1.0)\n self.opt = opt\n self.sess = None\n self.train_step = None\n self.post_step = None\n self.graph = tf.Graph()\n with self.graph.as_default():\n self.head_input = tf.placeholder(tf.int32, shape=[None])\n self.rel_input = tf.placeholder(tf.int32, shape=[None])\n self.tail_input = tf.placeholder(tf.int32, shape=[None])\n self.target = tf.placeholder(tf.float32, shape=[None])\n\n def _create_model(self, train_triples):\n ''' Subclasses must build Graph and set self.train_step '''\n raise Exception('subclass must implement')\n \n def _create_batch_provider(self, train_triples):\n ''' Default implementation '''\n return ContrastiveTrainingProvider(train_triples, self.batch_pos_cnt)\n \n def _create_output_and_loss(self, raw_output):\n if self.model_type == 'least_squares':\n return least_squares_objective(raw_output, self.target, self.add_bias)\n elif self.model_type == 'logistic':\n return logistic_objective(raw_output, self.target, self.add_bias)\n elif self.model_type == 'ranking_margin':\n return ranking_margin_objective(raw_output, 1.0)\n else:\n raise Exception('Unknown model_type')\n \n def _norm_constraint_op(self, var_matrix, row_indices, maxnorm): \n '''\n Args:\n var_matrix: A 2D Tensor holding the vectors to constrain (in rows)\n row_indices: The rows in var_tensor that are being considered for\n constraint application (typically embedding vectors for \n entities observed for a minibatch of training data). These \n will be used for a sparse variable update operation if the\n chosen optimizer only modified these entries. Otherwise \n a dense operation is used and row_indices are ignored.\n maxnorm: The maximum Euclidean norm for the rows in var_tensor\n \n Returns:\n An operation which will apply the constraints when run in a Session\n '''\n # Currently, TF optimizers do not update variables with zero gradient\n # except AdamOptimizer\n if isinstance(self.opt, tf.train.AdamOptimizer):\n return dense_maxnorm_update(var_matrix, maxnorm)\n else:\n return sparse_maxnorm_update(var_matrix, row_indices, maxnorm)\n \n def embeddings(self):\n ''' Subclass should override this if it uses different embedding\n variables\n \n Returns:\n A list of pairs: [(embedding name, embedding 2D Tensor)]\n '''\n return [('entity', self.entity_embedding_vars),\n ('rel', self.rel_embedding_vars)]\n \n def create_feed_dict(self, triples, labels=None, training=False):\n ''' Create a TensorFlow feed dict for relationship triples\n \n Args:\n triples: A numpy integer array of relationship triples, where each \n row contains [head idx, relationship idx, tail idx]\n labels: (optional) A label array for triples\n training: (optional) A flag indicating whether the feed dict is\n for training or test purposes. Useful for things like\n dropout where a dropout_probability variable is set differently\n in the two contexts.\n '''\n feed_dict = {self.head_input: triples[:, 0], \n self.rel_input: triples[:, 1], \n self.tail_input: triples[:, 2]}\n if labels is not None:\n feed_dict[self.target] = labels\n return feed_dict\n \n def close(self):\n ''' Closes the TensorFlow Session object '''\n self.sess.close();\n \n def fit(self, train_triples, step_callback=None):\n ''' Trains the model on relationship triples\n \n Args:\n train_triples: A numpy integer array of relationship triples, where \n each row of contains [head idx, relationship idx, tail idx]\n step_callback: (optional) A function that will be called before each \n optimization step, step_callback(iteration, feed_dict)\n '''\n if self.sess is not None:\n self.sess.close()\n self.sess = tf.Session(graph=self.graph)\n with self.graph.as_default():\n self._create_model(train_triples)\n self.sess.run(tf.initialize_all_variables())\n batch_provider = self._create_batch_provider(train_triples)\n for i in range(self.max_iter):\n batch_triples, batch_labels = batch_provider.next_batch()\n feed_dict = self.create_feed_dict(batch_triples, batch_labels, training=True)\n if step_callback:\n keep_going = step_callback(i, feed_dict)\n if not keep_going:\n break\n self.sess.run(self.train_step, feed_dict)\n if self.post_step is not None:\n self.sess.run(self.post_step, feed_dict)\n\n def predict(self, triples):\n ''' Runs a trained model on the supplied relationship triples. fit()\n must be called before calling this function.\n \n Args:\n triples: A numpy integer array of relationship triples, where each \n row of contains [head idx, relationship idx, tail idx]\n '''\n feed_dict = self.create_feed_dict(triples, training=False)\n return self.sess.run(self.output, feed_dict=feed_dict)\n \n\nclass Contrastive_CP(BaseModel):\n ''' Model with a scoring function based on CANDECOMP/PARAFAC tensor \n decomposition. Optimization differs, however, in the use of maxnorm \n regularization and contrastive negative sampling.\n \n Score for (head i, rel k, tail j) triple is: h_i^T * diag(r_k) * t_j, \n where h_i and t_j are embedding vectors for the head and tail entities, \n and r_k is an embedding vector for the relationship type.\n \n Args:\n embedding_size: Embedding vector length\n maxnorm: Maximum Euclidean norm for embedding vectors\n batch_pos_cnt: Number of positive examples to use in each mini-batch\n max_iter: Maximum number of optimization iterations to perform\n model_type: Possible values:\n 'least_squares': squared loss on 0/1 targets\n 'logistic': sigmoid link function, crossent loss on 0/1 targets\n 'ranking_margin': ranking margin on pos/neg pairs\n add_bias: If True, a bias Variable will be added to the output for\n least_squares and logistic models.\n opt: An optimizer object to use. If None, the default optimizer is\n tf.train.AdagradOptimizer(1.0) \n\n References:\n Kolda, Tamara G., and Brett W. Bader. \"Tensor decompositions and \n applications.\" SIAM review 51.3 (2009): 455-500.\n '''\n \n def _create_model(self, train_triples):\n # Count unique items to determine embedding matrix sizes\n head_cnt = len(set(train_triples[:,0]))\n rel_cnt = len(set(train_triples[:,1]))\n tail_cnt = len(set(train_triples[:,2]))\n init_sd = 1.0 / np.sqrt(self.embedding_size)\n # Embedding matrices for entities and relationship types\n head_init = tf.truncated_normal([head_cnt, self.embedding_size], stddev=init_sd)\n rel_init = tf.truncated_normal([rel_cnt, self.embedding_size], stddev=init_sd)\n tail_init = tf.truncated_normal([tail_cnt, self.embedding_size], stddev=init_sd)\n if self.maxnorm is not None:\n # Ensure maxnorm constraints are initially satisfied\n head_init = dense_maxnorm(head_init, self.maxnorm)\n rel_init = dense_maxnorm(rel_init, self.maxnorm)\n tail_init = dense_maxnorm(tail_init, self.maxnorm)\n self.head_embedding_vars = tf.Variable(head_init)\n self.rel_embedding_vars = tf.Variable(rel_init)\n self.tail_embedding_vars = tf.Variable(tail_init)\n # Embedding layer for each (head, rel, tail) triple being fed in as input\n head_embed = tf.nn.embedding_lookup(self.head_embedding_vars, self.head_input)\n rel_embed = tf.nn.embedding_lookup(self.rel_embedding_vars, self.rel_input)\n tail_embed = tf.nn.embedding_lookup(self.tail_embedding_vars, self.tail_input)\n # Model output\n raw_output = tf.reduce_sum(tf.mul(tf.mul(head_embed, rel_embed), tail_embed), 1)\n self.output, self.loss = self._create_output_and_loss(raw_output)\n # Optimization\n self.train_step = self.opt.minimize(self.loss)\n if self.maxnorm is not None:\n # Post-processing to limit embedding vars to L2 ball\n head_constraint = self._norm_constraint_op(self.head_embedding_vars, \n tf.unique(self.head_input)[0], \n self.maxnorm)\n rel_constraint = self._norm_constraint_op(self.rel_embedding_vars, \n tf.unique(self.rel_input)[0], \n self.maxnorm)\n tail_constraint = self._norm_constraint_op(self.tail_embedding_vars, \n tf.unique(self.tail_input)[0], \n self.maxnorm)\n self.post_step = [head_constraint, rel_constraint, tail_constraint]\n\n def _create_batch_provider(self, train):\n # CP treats head and tail entities separately\n return ContrastiveTrainingProvider(train, \n self.batch_pos_cnt, \n separate_head_tail=True)\n \n def embeddings(self):\n '''\n Returns:\n A list of pairs: [(embedding name, embedding 2D Tensor)]\n '''\n return [('head', self.head_embedding_vars),\n ('tail', self.head_embedding_vars),\n ('rel', self.rel_embedding_vars)]\n\n\nclass Bilinear(BaseModel):\n ''' Model with a scoring function based on the bilinear formulation of \n RESCAL. Optimization differs, however, in the use of maxnorm \n regularization and contrastive negative sampling.\n \n Score for (head i, rel k, tail j) triple is: e_i^T * R_k * e_j\n where e_i and e_j are D-dimensional embedding vectors for the head and tail \n entities, and R_k is a (D x D) matrix for the relationship type\n acting as a bilinear operator.\n \n Args:\n embedding_size: Embedding vector length\n maxnorm: Maximum Euclidean norm for embedding vectors\n rel_maxnorm_mult: Multiplier for the maxnorm threshold used for \n relationship embeddings. Example: If maxnorm=2.0 and \n rel_maxnorm_mult=4.0, then the maxnorm constrain for relationships\n will be 2.0 * 4.0 = 8.0.\n batch_pos_cnt: Number of positive examples to use in each mini-batch \n max_iter: Maximum number of optimization iterations to perform\n model_type: Possible values:\n 'least_squares': squared loss on 0/1 targets\n 'logistic': sigmoid link function, crossent loss on 0/1 targets\n 'ranking_margin': ranking margin on pos/neg pairs\n add_bias: If True, a bias Variable will be added to the output for\n least_squares and logistic models. \n opt: An optimizer object to use. If None, the default optimizer is\n tf.train.AdagradOptimizer(1.0) \n\n References:\n Nickel, Maximilian, Volker Tresp, and Hans-Peter Kriegel. \"A three-way \n model for collective learning on multi-relational data.\" Proceedings of \n the 28th international conference on machine learning (ICML-11). 2011. \n '''\n \n def __init__(self, embedding_size, maxnorm=1.0, rel_maxnorm_mult=3.0, \n batch_pos_cnt=100, max_iter=1000, \n model_type='least_squares', add_bias=True, opt=None):\n super(Bilinear, self).__init__(\n embedding_size=embedding_size,\n maxnorm=maxnorm,\n batch_pos_cnt=batch_pos_cnt,\n max_iter=max_iter,\n model_type=model_type,\n opt=opt)\n self.rel_maxnorm_mult = rel_maxnorm_mult\n \n def _create_model(self, train_triples):\n # Count unique items to determine embedding matrix sizes\n entity_cnt = len(set(train_triples[:,0]).union(train_triples[:,2]))\n rel_cnt = len(set(train_triples[:,1]))\n init_sd = 1.0 / np.sqrt(self.embedding_size)\n # Embedding variables for all entities and relationship types\n entity_embedding_shape = [entity_cnt, self.embedding_size]\n # Relationship embeddings will be stored in flattened format to make \n # applying maxnorm constraints easier\n rel_embedding_shape = [rel_cnt, self.embedding_size * self.embedding_size]\n entity_init = tf.truncated_normal(entity_embedding_shape, stddev=init_sd)\n rel_init = tf.truncated_normal(rel_embedding_shape, stddev=init_sd)\n if self.maxnorm is not None:\n # Ensure maxnorm constraints are initially satisfied\n entity_init = dense_maxnorm(entity_init, self.maxnorm)\n rel_init = dense_maxnorm(rel_init, self.maxnorm)\n self.entity_embedding_vars = tf.Variable(entity_init)\n self.rel_embedding_vars = tf.Variable(rel_init)\n # Embedding layer for each (head, rel, tail) triple being fed in as input\n head_embed = tf.nn.embedding_lookup(self.entity_embedding_vars, self.head_input)\n tail_embed = tf.nn.embedding_lookup(self.entity_embedding_vars, self.tail_input)\n rel_embed = tf.nn.embedding_lookup(self.rel_embedding_vars, self.rel_input)\n # Reshape rel_embed into square D x D matrices\n rel_embed_square = tf.reshape(rel_embed, (-1, self.embedding_size, self.embedding_size))\n # Reshape head_embed and tail_embed to be suitable for the matrix multiplication\n head_embed_row = tf.expand_dims(head_embed, 1) # embeddings as row vectors\n tail_embed_col = tf.expand_dims(tail_embed, 2) # embeddings as column vectors\n head_rel_mult = tf.batch_matmul(head_embed_row, rel_embed_square)\n # Output needs a squeeze into a 1d vector\n raw_output = tf.squeeze(tf.batch_matmul(head_rel_mult, tail_embed_col)) \n self.output, self.loss = self._create_output_and_loss(raw_output)\n # Optimization\n self.train_step = self.opt.minimize(self.loss)\n if self.maxnorm is not None:\n # Post-processing to limit embedding vars to L2 ball\n rel_maxnorm = self.maxnorm * self.rel_maxnorm_mult\n unique_ent_indices = tf.unique(tf.concat(0, [self.head_input, self.tail_input]))[0]\n unique_rel_indices = tf.unique(self.rel_input)[0]\n entity_constraint = self._norm_constraint_op(self.entity_embedding_vars, \n unique_ent_indices, \n self.maxnorm)\n rel_constraint = self._norm_constraint_op(self.rel_embedding_vars, \n unique_rel_indices, \n rel_maxnorm)\n self.post_step = [entity_constraint, rel_constraint]\n\n\nclass TransE(BaseModel):\n ''' TransE: Translational Embeddings Model\n \n Score for (head i, rel k, tail j) triple is: d(e_i + t_k, e_i) \n where e_i and e_j are D-dimensional embedding vectors for the head and\n tail entities, t_k is a another D-dimensional vector acting as a \n translation, and d() is a dissimilarity function like Euclidean distance.\n \n Optimization is performed uing SGD on ranking margin loss between \n contrastive training pairs. Entity embeddings are contrained to lie within\n the unit L2 ball, relationship vectors are left unconstrained.\n \n Args:\n embedding_size: Embedding vector length\n batch_pos_cnt: Number of positive examples to use in each mini-batch \n max_iter: Maximum number of optimization iterations to perform\n dist: Distance function used in loss:\n 'euclidean': sqrt(sum((x - y)^2))\n 'sqeuclidean': squared Euclidean, sum((x - y)^2)\n 'manhattan': sum of absolute differences, sum(|x - y|) \n margin: Margin parameter for parwise ranking hinge loss \n opt: An optimizer object to use. If None, the default optimizer is\n tf.train.AdagradOptimizer(1.0) \n \n References:\n Bordes, Antoine, et al. \"Translating embeddings for modeling multi-relational \n data.\" Advances in Neural Information Processing Systems. 2013.\n '''\n def __init__(self, embedding_size, batch_pos_cnt=100, \n max_iter=1000, dist='euclidean', \n margin=1.0, opt=None):\n super(TransE, self).__init__(embedding_size=embedding_size,\n maxnorm=1.0,\n batch_pos_cnt=batch_pos_cnt,\n max_iter=max_iter,\n model_type='ranking_margin',\n opt=opt)\n self.dist = dist\n self.margin = margin\n self.EPS = 1e-3 # for sqrt gradient when dist='euclidean'\n \n def _create_model(self, train_triples):\n # Count unique items to determine embedding matrix sizes\n entity_cnt = len(set(train_triples[:,0]).union(train_triples[:,2]))\n rel_cnt = len(set(train_triples[:,1]))\n init_sd = 1.0 / np.sqrt(self.embedding_size)\n # Embedding variables\n entity_var_shape = [entity_cnt, self.embedding_size]\n rel_var_shape = [rel_cnt, self.embedding_size]\n entity_init = tf.truncated_normal(entity_var_shape, stddev=init_sd)\n rel_init = tf.truncated_normal(rel_var_shape, stddev=init_sd)\n # Ensure maxnorm constraints are initially satisfied\n entity_init = dense_maxnorm(entity_init, self.maxnorm)\n self.entity_embedding_vars = tf.Variable(entity_init)\n self.rel_embedding_vars = tf.Variable(rel_init)\n # Embedding layer for each (head, rel, tail) triple being fed in as input\n head_embed = tf.nn.embedding_lookup(self.entity_embedding_vars, self.head_input)\n tail_embed = tf.nn.embedding_lookup(self.entity_embedding_vars, self.tail_input)\n rel_embed = tf.nn.embedding_lookup(self.rel_embedding_vars, self.rel_input)\n # Relationship vector acts as a translation in entity embedding space\n diff_vec = tail_embed - (head_embed + rel_embed)\n # negative dist so higher scores are better (important for pairwise loss)\n if self.dist == 'manhattan':\n raw_output = -tf.reduce_sum(tf.abs(diff_vec), 1)\n elif self.dist == 'euclidean':\n # +eps because gradients can misbehave for small values in sqrt\n raw_output = -tf.sqrt(tf.reduce_sum(tf.square(diff_vec), 1) + self.EPS)\n elif self.dist == 'sqeuclidean':\n raw_output = -tf.reduce_sum(tf.square(diff_vec), 1)\n else:\n raise Exception('Unknown distance type')\n # Model output\n self.output, self.loss = ranking_margin_objective(raw_output, self.margin)\n # Optimization with postprocessing to limit embedding vars to L2 ball\n self.train_step = self.opt.minimize(self.loss)\n unique_ent_indices = tf.unique(tf.concat(0, [self.head_input, self.tail_input]))[0]\n self.post_step = self._norm_constraint_op(self.entity_embedding_vars, \n unique_ent_indices, \n self.maxnorm)" ]
[ [ "tensorflow.scatter_update", "tensorflow.concat", "numpy.sqrt", "tensorflow.reduce_sum", "tensorflow.Graph", "tensorflow.batch_matmul", "tensorflow.Variable", "tensorflow.initialize_all_variables", "tensorflow.square", "tensorflow.Session", "tensorflow.train.AdagradOptimizer", "tensorflow.truncated_normal", "tensorflow.unique", "tensorflow.placeholder", "tensorflow.split", "tensorflow.nn.embedding_lookup", "tensorflow.nn.relu", "tensorflow.maximum", "tensorflow.reshape", "tensorflow.assign", "tensorflow.sigmoid", "tensorflow.expand_dims", "tensorflow.mul", "tensorflow.log", "tensorflow.abs" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
aspuru-guzik-group/kraken
[ "4eaad505c1343e6083032b4a3fda47e004e19734", "4eaad505c1343e6083032b4a3fda47e004e19734" ]
[ "conf_selection_and_DFT/PL_dft_library_201027.py", "conf_selection_and_DFT/vmin4.py" ]
[ "# 201005: rename/restructure .yml files for consistency with xtb-level data\r\n# 201006: in read_conformer() fix error message when log files are missing \r\n\r\nimport os,re,itertools,time\r\n#import pybel\r\n#from openbabel import pybel\r\nimport numpy as np\r\nimport pandas as pd\r\nimport pathlib as pl\r\ncwd = pl.Path.cwd()\r\nimport yaml\r\nfrom yaml import CLoader as Loader\r\nfrom yaml import CDumper as Dumper\r\nfrom rdkit import Chem,Geometry\r\nfrom rdkit.Chem import rdmolfiles, AllChem, rdMolAlign,rdmolops\r\nfrom multiprocessing import Pool\r\n\r\nimport morfeus # Kjell Jorner\r\nfrom PL_split_logs_201006 import split_log # TG\r\nfrom PL_conformer_selection_200411 import mirror_mol, delete_element_from_rdkitmol, delete_haloalkane_halides # TG #changed from PL_conformer_selection_201019 5/17/21 by EP\r\nimport PL_gaussian_properties_201021 as gp # TG\r\nimport vmin4 as vmin # TG/Iris Guo\r\nimport P_int_200916 as P_int # Robert Pollice (,TG(,ML))\r\n# import PL_visvol as visvol # Ellyn Peters\r\n\r\n# covalent radii, from Pyykko and Atsumi, Chem. Eur. J. 15, 2009, 188-197\r\n# values for metals decreased by 10% according to Robert Paton's Sterimol implementation\r\nrcov = {\r\n\"H\": 0.32,\"He\": 0.46,\"Li\": 1.2,\"Be\": 0.94,\"B\": 0.77,\"C\": 0.75,\"N\": 0.71,\"O\": 0.63,\"F\": 0.64,\"Ne\": 0.67,\"Na\": 1.4,\"Mg\": 1.25,\"Al\": 1.13,\"Si\": 1.04,\"P\": 1.1,\"S\": 1.02,\"Cl\": 0.99,\"Ar\": 0.96,\"K\": 1.76,\"Ca\": 1.54,\"Sc\": 1.33,\"Ti\": 1.22,\"V\": 1.21,\"Cr\": 1.1,\"Mn\": 1.07,\"Fe\": 1.04,\"Co\": 1.0,\"Ni\": 0.99,\"Cu\": 1.01,\"Zn\": 1.09,\"Ga\": 1.12,\"Ge\": 1.09,\"As\": 1.15,\"Se\": 1.1,\"Br\": 1.14,\"Kr\": 1.17,\"Rb\": 1.89,\"Sr\": 1.67,\"Y\": 1.47,\"Zr\": 1.39,\"Nb\": 1.32,\"Mo\": 1.24,\"Tc\": 1.15,\"Ru\": 1.13,\"Rh\": 1.13,\"Pd\": 1.08,\"Ag\": 1.15,\"Cd\": 1.23,\"In\": 1.28,\"Sn\": 1.26,\"Sb\": 1.26,\"Te\": 1.23,\"I\": 1.32,\"Xe\": 1.31,\"Cs\": 2.09,\"Ba\": 1.76,\"La\": 1.62,\"Ce\": 1.47,\"Pr\": 1.58,\"Nd\": 1.57,\"Pm\": 1.56,\"Sm\": 1.55,\"Eu\": 1.51,\"Gd\": 1.52,\"Tb\": 1.51,\"Dy\": 1.5,\"Ho\": 1.49,\"Er\": 1.49,\"Tm\": 1.48,\"Yb\": 1.53,\"Lu\": 1.46,\"Hf\": 1.37,\"Ta\": 1.31,\"W\": 1.23,\"Re\": 1.18,\"Os\": 1.16,\"Ir\": 1.11,\"Pt\": 1.12,\"Au\": 1.13,\"Hg\": 1.32,\"Tl\": 1.3,\"Pb\": 1.3,\"Bi\": 1.36,\"Po\": 1.31,\"At\": 1.38,\"Rn\": 1.42,\"Fr\": 2.01,\"Ra\": 1.81,\"Ac\": 1.67,\"Th\": 1.58,\"Pa\": 1.52,\"U\": 1.53,\"Np\": 1.54,\"Pu\": 1.55\r\n}\r\n\r\n# some constants\r\nR = 0.0019872036 #kcal mol^-1 K^-1\r\nT = 298.15 #K\r\nhartree_kcalmol = 627.50947 \r\n\r\nperiodictable = [\"Bq\",\"H\",\"He\",\"Li\",\"Be\",\"B\",\"C\",\"N\",\"O\",\"F\",\"Ne\",\"Na\",\"Mg\",\"Al\",\"Si\",\"P\",\"S\",\"Cl\",\"Ar\",\"K\",\"Ca\",\"Sc\",\"Ti\",\"V\",\"Cr\",\"Mn\",\"Fe\",\"Co\",\"Ni\",\"Cu\",\"Zn\",\"Ga\",\"Ge\",\"As\",\"Se\",\"Br\",\"Kr\",\"Rb\",\"Sr\",\"Y\",\"Zr\",\"Nb\",\"Mo\",\"Tc\",\"Ru\",\"Rh\",\"Pd\",\"Ag\",\"Cd\",\"In\",\"Sn\",\"Sb\",\"Te\",\"I\",\"Xe\",\"Cs\",\"Ba\",\"La\",\"Ce\",\"Pr\",\"Nd\",\"Pm\",\"Sm\",\"Eu\",\"Gd\",\"Tb\",\"Dy\",\"Ho\",\"Er\",\"Tm\",\"Yb\",\"Lu\",\"Hf\",\"Ta\",\"W\",\"Re\",\"Os\",\"Ir\",\"Pt\",\"Au\",\"Hg\",\"Tl\",\"Pb\",\"Bi\",\"Po\",\"At\",\"Rn\",\"Fr\",\"Ra\",\"Ac\",\"Th\",\"Pa\",\"U\",\"Np\",\"Pu\",\"Am\",\"Cm\",\"Bk\",\"Cf\",\"Es\",\"Fm\",\"Md\",\"No\",\"Lr\",\"Rf\",\"Db\",\"Sg\",\"Bh\",\"Hs\",\"Mt\",\"Ds\",\"Rg\",\"Uub\",\"Uut\",\"Uuq\",\"Uup\",\"Uuh\",\"Uus\",\"Uuo\",\"X\"]\r\n\r\ndef get_conmat(elements, coords): \r\n # partially based on code from Robert Paton's Sterimol script, which based this part on Grimme's D3 code\r\n # elements is a list of strings, coords is a numpy array or nested list of shape N_atoms x 3\r\n if type(coords) == list:\r\n coords = np.asarray(coords)\r\n natom = len(elements)\r\n #max_elem = 94\r\n k1 = 16.0\r\n k2 = 4.0/3.0\r\n conmat = np.zeros((natom,natom))\r\n for i in range(0,natom):\r\n if elements[i] not in rcov.keys():\r\n continue\r\n for iat in range(0,natom):\r\n if elements[iat] not in rcov.keys():\r\n continue\r\n if iat != i:\r\n dxyz = coords[iat]-coords[i]\r\n r = np.linalg.norm(dxyz)\r\n rco = rcov[elements[i]]+rcov[elements[iat]]\r\n rco = rco*k2\r\n rr=rco/r\r\n damp=1.0/(1.0+np.math.exp(-k1*(rr-1.0)))\r\n if damp > 0.85: #check if threshold is good enough for general purpose\r\n conmat[i,iat],conmat[iat,i] = 1,1\r\n return(conmat)\r\n \r\ndef add_valence(elements,coords,conmat,base_idx,add_element=\"Pd\"):\r\n # Adds a valence to base so that the angle to the previous substituents is maximized and reorders the coordinate output for convenience\r\n # add_element: add any of the following elements:\r\n distpx = {\"O\":1.5,\"Se\":2.12,\"Pd\":2.28,\"X\":1.8} # typical bond distances to P\r\n if type(coords) == list:\r\n coords = np.asarray(coords)\r\n num_atoms = len(elements)\r\n coord_base = coords[base_idx]\r\n base_element = elements[base_idx]\r\n vec = np.array([0.0,0.0,0.0])\r\n bonded = []\r\n for atom in range(num_atoms):\r\n if conmat[base_idx][atom]:\r\n bonded.append(atom)\r\n vec += coord_base - coords[atom]\r\n coordox = distpx[add_element]*vec/np.linalg.norm(vec) + coord_base\r\n atoms = [x for x in range(num_atoms+1)]\r\n coords_temp = np.vstack((coords,coordox))\r\n if sum(get_conmat(elements+[add_element],coords_temp)[-1]) != 1.0:\r\n print(\" Warning: possible collision!\")\r\n # sort coordinates so that base is first, add_element is second, and the other atoms bonded to base are next\r\n elements_new = [base_element,add_element]+[elements[a] for a in bonded] + [a for i,a in enumerate(elements) if i not in [base_idx]+bonded]\r\n coords_new = np.vstack((coord_base, coordox, coords[bonded], coords[[i for i,a in enumerate(elements) if i not in [base_idx]+bonded]]))\r\n return(elements_new, coords_new)\r\n\r\ndef write_xyz(elements,coords,filename):\r\n with open(filename,\"w\") as f:\r\n f.write(f\"{len(elements)}\\n\\n\")\r\n for i,a in enumerate(elements):\r\n f.write(f\"{a.title():>3} \" + \" \".join([f\"{coords[i][j]:15f}\" for j in range(3)]) + \"\\n\")\r\n\r\ndef rmsd_matrix(conformers):\r\n molobjects = [rdmolfiles.MolFromMolFile(str(cwd/conformer/f\"{conformer}_opt.sdf\"),removeHs=False,strictParsing=False) for conformer in conformers]\r\n molobjects = [Chem.RemoveHs(mol) for mol in molobjects] # Remove all H: optional but speeds up RMSD calculation\r\n molobjects = [delete_haloalkane_halides(mol) for mol in molobjects] # Remove halides in perhaloalkyl moieties. Improves RMSD matching and timing\r\n molobjects_inv = [mirror_mol(mol) for mol in molobjects] # create mirror images of each conformer\r\n rmsd_mat = np.zeros((len(conformers),len(conformers)))\r\n for i,j in itertools.product(range(len(conformers)),range(len(conformers))):\r\n if i<j: continue\r\n if i==j: \r\n rmsd_mat[i,j] = 1\r\n else:\r\n rmsd_mat[i,j] = min((rdMolAlign.GetBestRMS(molobjects[i],molobjects[j]),rdMolAlign.GetBestRMS(molobjects[i],molobjects_inv[j])))\r\n rmsd_mat[j,i] = rmsd_mat[i,j]\r\n return(rmsd_mat)\r\n\r\ndef dict_key_rmsd(candidate_pair):\r\n return float(rmsd_matrix(candidate_pair)[0,1])\r\n\r\n\r\n# which energies to read from which log-file\r\nenergylogs = {\r\n\"e_dz\":\"freq\",\r\n\"e_tz_gas\":\"nbo\",\r\n\"e_tz_gas\":\"sp\",\r\n\"e_tz_solv\":\"solv\",\r\n\"e_tz_ra\":\"ra\",\r\n\"e_tz_rc\":\"rc\",\r\n}\r\n\r\n# which properties to read from which log-file\r\nproplogs = {\r\n\"freq\":[\"nimag\",\"g\",\"t\"],\r\n\"sp\" :[\"dipole\",\"homo\",\"qpole\",\"t\"],\r\n\"ra\" :[\"homo\",\"nbo\",\"t\"],\r\n\"rc\" :[\"homo\",\"nbo\",\"t\"],\r\n\"nbo\" :[\"nbo\",\"nborbsP\",\"t\"],\r\n\"nmr\" :[\"nmr\",\"t\"],\r\n\"efg\" :[\"efg\",\"nuesp\",\"t\"],\r\n\"solv\":[\"ecds\",\"t\"],\r\n}\r\n\r\n# assign names to each descriptor\r\npropoutput = {\r\n\"freq_g\": [\"\",\"g\"],\r\n\"freq_nimag\": [\"nimag\"],\r\n\"sp_dipole\": [\"dipolemoment\",],\r\n\"sp_homo\": [\"fmo_e_homo\",\"fmo_e_lumo\",\"fmo_mu\",\"fmo_eta\",\"fmo_omega\"],\r\n\"ra_homo\":[\"somo_ra\",\"\",\"\",\"\",\"\"],\r\n\"rc_homo\":[\"somo_rc\",\"\",\"\",\"\",\"\"],\r\n\"sp_qpole\": [\"qpole_amp\",\"qpoletens_xx\",\"qpoletens_yy\",\"qpoletens_zz\"],\r\n\"nbo_nbo\": [\"nbo_P\"],\r\n\"ra_nbo\": [\"nbo_P_ra\",\"spindens_P_ra\"],\r\n\"rc_nbo\": [\"nbo_P_rc\",\"spindens_P_rc\"],\r\n\"nmr_nmr\": [\"nmr_P\",\"nmrtens_sxx_P\",\"nmrtens_syy_P\",\"nmrtens_szz_P\",],\r\n\"efg_efg\": [\"efg_amp_P\",\"efgtens_xx_P\",\"efgtens_yy_P\",\"efgtens_zz_P\"],\r\n\"efg_nuesp\": [\"nuesp_P\",],\r\n\"solv_ecds\": [\"E_solv_cds\"],\r\n\"nbo_dipole\": [\"dipolemoment\",],\r\n\"nbo_homo\": [\"fmo_e_homo\",\"fmo_e_lumo\",\"fmo_mu\",\"fmo_eta\",\"fmo_omega\"],\r\n\"nbo_qpole\": [\"qpole_amp\",\"qpoletens_xx\",\"qpoletens_yy\",\"qpoletens_zz\"],\r\n}\r\n\r\nboltzproperties = ['vmin_vmin','vmin_r','dipolemoment', 'fmo_e_homo', 'fmo_e_lumo', 'fmo_mu', 'fmo_eta', 'fmo_omega', 'somo_ra', 'somo_rc', 'qpole_amp', 'qpoletens_xx', 'qpoletens_yy', 'qpoletens_zz', 'nbo_P', 'nbo_P_ra', 'spindens_P_ra', 'nbo_P_rc', 'spindens_P_rc', 'nmr_P', 'nmrtens_sxx_P', 'nmrtens_syy_P', 'nmrtens_szz_P', 'efg_amp_P', 'efgtens_xx_P', 'efgtens_yy_P', 'efgtens_zz_P', 'nuesp_P', 'E_solv_cds', 'nbo_lp_P_percent_s', 'nbo_lp_P_occ', 'nbo_lp_P_e', 'nbo_bd_e_max', 'nbo_bd_e_avg', 'nbo_bds_e_min', 'nbo_bds_e_avg', 'nbo_bd_occ_min', 'nbo_bd_occ_avg', 'nbo_bds_occ_max', 'nbo_bds_occ_avg', 'E_solv_total', 'E_solv_elstat', 'E_oxidation', 'E_reduction', 'fukui_p', 'fukui_m', 'pyr_P', 'pyr_alpha', 'vbur_vbur', 'vbur_vtot', 'vbur_ratio_vbur_vtot', 'vbur_qvbur_min', 'vbur_qvbur_max', 'vbur_qvtot_min', 'vbur_qvtot_max', 'vbur_max_delta_qvbur', 'vbur_max_delta_qvtot', 'vbur_ovbur_min', 'vbur_ovbur_max', 'vbur_ovtot_min', 'vbur_ovtot_max', 'vbur_near_vbur', 'vbur_far_vbur', 'vbur_near_vtot', 'vbur_far_vtot', 'sterimol_B1', 'sterimol_B5', 'sterimol_L', 'sterimol_burB1', 'sterimol_burB5', 'sterimol_burL',\"Pint_P_int\",\"Pint_dP\",\"Pint_P_min\",\"Pint_P_max\",\"volume\",\"surface_area\",\"sphericity\"] # \"vv_total_visible_volume\",\"vv_proximal_visible_volume\",\"vv_distal_visible_volume\",\"vv_ratio_visible_total\",\"vv_ratio_proxvis_total\",\r\n\r\nmmproperties = ['dipolemoment', 'qpole_amp', 'qpoletens_xx', 'qpoletens_yy', 'qpoletens_zz', 'pyr_P', 'pyr_alpha', 'vbur_vbur', 'vbur_vtot', 'vbur_qvbur_min', 'vbur_qvbur_max', 'vbur_qvtot_min', 'vbur_qvtot_max', 'vbur_max_delta_qvbur', 'vbur_max_delta_qvtot', 'vbur_ovbur_min', 'vbur_ovbur_max', 'vbur_ovtot_min', 'vbur_ovtot_max', 'vbur_near_vbur', 'vbur_far_vbur', 'vbur_near_vtot', 'vbur_far_vtot', 'sterimol_B1', 'sterimol_B5', 'sterimol_L', 'sterimol_burB1', 'sterimol_burB5', 'sterimol_burL'] # ,\"vv_total_visible_volume\",\"vv_proximal_visible_volume\",\"vv_distal_visible_volume\",\"vv_ratio_visible_total\",\"vv_ratio_proxvis_total\",\r\n\r\nPintresults = [\"Pint_P_int\",\"Pint_dP\",\"Pint_P_min\",\"Pint_P_max\",\"volume\",\"surface_area\",\"sphericity\"]\r\n\r\ndef morfeus_properties(elements,coordinates,confdata):\r\n # Morfeus: Sterimol, Vbur, pyr\r\n morfdict = {}\r\n if \"pyr_P\" not in confdata.keys() and confdata[\"p_val\"] == 3:\r\n # Pyramidalization - two equivalent measurments P and alpha \r\n pyr = morfeus.Pyramidalization(elements=elements,coordinates=coordinates,atom_index=1,excluded_atoms=[2]) # remove Pd\r\n morfdict[\"pyr_P\"] = float(pyr.P)\r\n morfdict[\"pyr_alpha\"] = float(pyr.alpha)\r\n\r\n if \"vbur_vbur\" not in confdata.keys():\r\n #Buried volume - get quadrant volumes and distal volume \r\n # iterate through P-substituents, aligning the quadrants paralell to each once (= xz_plane definition)\r\n # Metal/point of reference should be 2.28 A away from P\r\n # z_axis_atoms: P \r\n # xz_plane_atoms: each of the substituents once\r\n # keep lowest and highest quadrant and octant volume across all three orientations of the coordinate system\r\n # keep highest difference of any neighboring quadrant volume\r\n # keep volume in each of the two hemispheres \r\n\r\n qvbur_all = np.array([])\r\n qvdist_all = np.array([])\r\n qvtot_all = np.array([])\r\n max_delta_qvbur_all = []\r\n max_delta_qvtot_all = []\r\n ovbur_all = np.array([])\r\n ovtot_all = np.array([])\r\n \r\n for i in range(3):#confdata[\"p_val\"]): \r\n bv = morfeus.BuriedVolume(elements,coordinates,2,excluded_atoms=[2],z_axis_atoms=[1],xz_plane_atoms=[3+i]) \r\n bv.octant_analysis()\r\n bv.compute_distal_volume(method=\"buried_volume\",octants=True)\r\n\r\n vbur = bv.buried_volume # these are identical for each iteration\r\n vdist = bv.distal_volume # \r\n vtot = vbur + vdist # \r\n\r\n qvbur = np.asarray(list(bv.quadrants[\"buried_volume\"].values()))\r\n qvdist = np.asarray(list(bv.quadrants[\"distal_volume\"].values()))\r\n qvtot = qvbur + qvdist\r\n\r\n qvbur_all = np.append(qvbur_all,qvbur)\r\n qvtot_all = np.append(qvtot_all,qvtot)\r\n\r\n max_delta_qvbur_all.append(max([abs(qvbur[j]-qvbur[j-1]) for j in range(4)]))\r\n max_delta_qvtot_all.append(max([abs(qvtot[j]-qvtot[j-1]) for j in range(4)]))\r\n\r\n ovbur = np.asarray(list(bv.octants[\"buried_volume\"].values()))\r\n ovdist = np.asarray(list(bv.octants[\"distal_volume\"].values()))\r\n ovtot = ovbur + ovdist\r\n\r\n ovbur_all = np.append(ovbur_all,ovbur)\r\n ovtot_all = np.append(ovtot_all,ovtot)\r\n\r\n near_vbur = ovbur[4:].sum() # these are identical for each iteration\r\n far_vbur = ovbur[:4].sum() # \r\n near_vtot = ovtot[4:].sum() # \r\n far_vtot = ovtot[:4].sum() # \r\n\r\n morfdict[\"vbur_vbur\"] = vbur\r\n morfdict[\"vbur_vtot\"] = float(vtot)\r\n morfdict[\"vbur_ratio_vbur_vtot\"] = float(vbur/vtot)\r\n\r\n morfdict[\"vbur_qvbur_min\"] = float(min(qvbur_all))\r\n morfdict[\"vbur_qvbur_max\"] = float(max(qvbur_all))\r\n morfdict[\"vbur_qvtot_min\"] = float(min(qvtot_all))\r\n morfdict[\"vbur_qvtot_max\"] = float(max(qvtot_all))\r\n\r\n morfdict[\"vbur_max_delta_qvbur\"] = float(max(max_delta_qvbur_all))\r\n morfdict[\"vbur_max_delta_qvtot\"] = float(max(max_delta_qvtot_all))\r\n\r\n morfdict[\"vbur_ovbur_min\"] = float(min(ovbur_all))\r\n morfdict[\"vbur_ovbur_max\"] = float(max(ovbur_all))\r\n morfdict[\"vbur_ovtot_min\"] = float(min(ovtot_all))\r\n morfdict[\"vbur_ovtot_max\"] = float(max(ovtot_all))\r\n\r\n morfdict[\"vbur_near_vbur\"] = float(near_vbur)\r\n morfdict[\"vbur_far_vbur\"] = float(far_vbur)\r\n morfdict[\"vbur_near_vtot\"] = float(near_vtot)\r\n morfdict[\"vbur_far_vtot\"] = float(far_vtot)\r\n\r\n if \"sterimol_B1\" not in confdata.keys():\r\n # Sterimol\r\n # for Sterimol values matching Rob Paton's implementation:\r\n patonradii = morfeus.helpers.get_radii(elements, radii_type=\"bondi\")\r\n patonradii = np.array(patonradii)\r\n patonradii[patonradii == 1.2] = 1.09\r\n\r\n sterimol = morfeus.Sterimol(elements, coordinates, 2, 1, radii=patonradii, n_rot_vectors=3600)\r\n morfdict[\"sterimol_B1\"] = float(sterimol.B_1_value)\r\n morfdict[\"sterimol_B5\"] = float(sterimol.B_5_value)\r\n morfdict[\"sterimol_L\"] = float(sterimol.L_value)\r\n # buried Sterimol\r\n sterimol_bur = morfeus.Sterimol(elements, coordinates, 2, 1,calculate=False,radii=patonradii, n_rot_vectors=3600)\r\n sterimol_bur.bury(sphere_radius=5.5,method=\"delete\",radii_scale=0.5) \r\n # sterimol.bury(sphere_radius=4.5,method=\"delete\",radii_scale=1) \r\n morfdict[\"sterimol_burB1\"] = float(sterimol_bur.B_1_value)\r\n morfdict[\"sterimol_burB5\"] = float(sterimol_bur.B_5_value)\r\n morfdict[\"sterimol_burL\"] = float(sterimol_bur.L_value)\r\n\r\n return(morfdict)\r\n\r\ndef gp_properties(ligand,conformer,p_idx):\r\n # reads gaussian log files\r\n gpdict = {} \r\n gpdict[\"properties\"] = {}\r\n contents = {\r\n \"streams\":{},\r\n \"filecont\":{},\r\n }\r\n # read energies\r\n for e,log in energylogs.items():\r\n contents[\"streams\"][log] = gp.get_outstreams(cwd/conformer/f\"{conformer}_{log}.log\")\r\n if contents[\"streams\"][log] == \"failed or incomplete job\":\r\n return({\"error\":True})\r\n else:\r\n gpdict[e] = gp.get_e_hf(contents[\"streams\"][log])\r\n gpdict[\"error\"] = False\r\n # going through each log file, get the relevant properties\r\n for log in proplogs.keys():\r\n contents[\"filecont\"][log] = gp.get_filecont(cwd/conformer/f\"{conformer}_{log}.log\")\r\n for prop in proplogs[log]:\r\n gpresults = gp.jobtypes[prop][0](contents[gp.jobtypes[prop][1]][log],p_idx)\r\n if prop == \"nborbsP\": # NBO orbital analysis returns a dictionary with the proper labels \r\n gpdict[\"properties\"].update(gpresults)\r\n elif prop == \"t\": # subjob time\r\n gpdict[f\"{log}_t\"] = gpresults\r\n elif prop in [\"e_dz\",\"g\",\"e_tz_gas\",\"e_tz_solv\",\"e_tz_ra\",\"e_tz_rc\",\"nimag\"]:\r\n gpdict.update({propoutput[f\"{log}_{prop}\"][i]: float(gpresults[i]) for i in range(len(gpresults))})\r\n else: # all other functions return a list. This is assigned into a dict with proper names here\r\n gpdict[\"properties\"].update({propoutput[f\"{log}_{prop}\"][i]: float(gpresults[i]) for i in range(len(gpresults))})\r\n\r\n gpdict[\"g_tz_gas\"] = gpdict[\"g\"] - gpdict[\"e_dz\"] + gpdict[\"e_tz_gas\"] # in Hartree\r\n gpdict[\"g_tz_solv\"] = gpdict[\"g\"] - gpdict[\"e_dz\"] + gpdict[\"e_tz_solv\"] # in Hartree\r\n gpdict[\"properties\"][\"E_solv_total\"] = (gpdict[\"e_tz_solv\"] - gpdict[\"e_tz_gas\"]) * hartree_kcalmol # in kcal/mol\r\n gpdict[\"properties\"][\"E_solv_elstat\"] = gpdict[\"properties\"][\"E_solv_total\"] - gpdict[\"properties\"][\"E_solv_cds\"] # in kcal/mol\r\n gpdict[\"properties\"][\"E_oxidation\"] = gpdict[\"e_tz_rc\"] - gpdict[\"e_tz_gas\"] # in Hartree\r\n gpdict[\"properties\"][\"E_reduction\"] = gpdict[\"e_tz_ra\"] - gpdict[\"e_tz_gas\"] # in Hartree\r\n gpdict[\"properties\"][\"fukui_p\"] = gpdict[\"properties\"][\"nbo_P\"]-gpdict[\"properties\"][\"nbo_P_ra\"] # fukui electrophilicity \r\n gpdict[\"properties\"][\"fukui_m\"] = gpdict[\"properties\"][\"nbo_P_rc\"]-gpdict[\"properties\"][\"nbo_P\"] # fukui nucleophilicity\r\n gpdict[\"t_total\"] = sum([gpdict[f\"{log}_t\"] for log in proplogs.keys()])\r\n if \"\" in gpdict.keys():\r\n del gpdict[\"\"]\r\n if \"\" in gpdict[\"properties\"].keys():\r\n del gpdict[\"properties\"][\"\"]\r\n return(gpdict)\r\n\r\ndef read_conformer(cwd, ligand, conformer): # cwd: pathlib path of current working directory. ligand: 0-digit ligand ID. conformer: full name of the conformer (including the ID at the beginnig)\r\n confdata = {}\r\n errors = []\r\n checklogs = [cwd/conformer/f\"{conformer}_{l}.log\" for l in proplogs.keys() if not (cwd/conformer/f\"{conformer}_{l}.log\").exists()]\r\n if len(checklogs) != 0:\r\n #! log this as a conformer-level error\r\n err = f\"Missing Gaussian log files, flagged in read_conformer: {','.join([chkl.name for chkl in checklogs])}\"\r\n errors.append(err)\r\n print(f\"{ligand};{conformer};{err}\")\r\n with open(cwd/f\"{ligand}_errors.txt\",\"a\") as f:\r\n f.write(f\"{ligand};{conformer};{err}\\n\")\r\n confdata[\"error\"] = True\r\n return(confdata,errors)\r\n\r\n if \"elements_pd\" not in confdata.keys():\r\n # mol = next(pybel.readfile(\"g09\",str(cwd/conformer/f\"{conformer}_nbo.log\")))\r\n #mol = next(pybel.readfile(\"g09\",str(cwd/conformer/f\"{conformer}_opt.log\")))\r\n #elements = [periodictable[a.atomicnum] for a in mol.atoms]\r\n #coordinates = [list(a.coords) for a in mol.atoms]\r\n #coordinates_a = np.array([a.coords for a in mol.atoms])\r\n\r\n def read_gaussian_logfile(fn):\r\n time0=time.time()\r\n read=False\r\n for line in open(fn,\"r\"):\r\n if read:\r\n if \"---\" in line and len(elements)>0:\r\n read=False\r\n if read:\r\n if \"X\" not in line and \"---\" not in line:\r\n atomnum = int(line.split()[1])\r\n #print(line.replace(\"\\n\",\"\"))\r\n #print(atomnum)\r\n el = periodictable[atomnum]\r\n elements.append(el)\r\n coordinates.append([float(line.split()[3]),float(line.split()[4]), float(line.split()[5])])\r\n if \"Coordinates (Angstroms)\" in line:\r\n coordinates, elements = [], []\r\n read=True\r\n time1=time.time()\r\n print(\"gaussian log parser done in %.2f seconds\"%(time1-time0))\r\n return(coordinates, elements)\r\n\r\n coordinates, elements = read_gaussian_logfile(str(cwd/conformer/f\"{conformer}_opt.log\"))\r\n coordinates_a = np.array(coordinates)\r\n\r\n conmat = get_conmat(elements,coordinates_a)\r\n p_idx = [i for i in range(len(elements)) if elements[i] == \"P\" and sum(conmat[i]) <= 3][0] # this removes quaternary P (phosphonium, phosphate etc) but allows for P with 2 substituents (phosphabenzene, phosphaimine etc). Can we be sure that we never have more than one non-quaternary P(III)? \r\n elements_pd, coordinates_pd = add_valence(elements,coordinates,conmat,p_idx,add_element=\"Pd\") # Add \"Pd\" at the reference position in the P-lone pair region\r\n if not (cwd/conformer/f\"{conformer}_opt_Pd.xyz\").exists():\r\n #out = pybel.Outputfile(\"xyz\",str(cwd/conformer/f\"{conformer}_opt.xyz\"))\r\n #out.write(mol)\r\n #out.close()\r\n write_xyz(elements, coordinates, cwd/conformer/f\"{conformer}_opt.xyz\")\r\n #out = pybel.Outputfile(\"sdf\",str(cwd/conformer/f\"{conformer}_opt.sdf\"))\r\n #out.write(mol)\r\n #out.close()\r\n os.system(\"obabel -ixyz %s -osdf >> %s\"%(str(cwd/conformer/f\"{conformer}_opt.xyz\"), str(cwd/conformer/f\"{conformer}_opt.sdf\")))\r\n write_xyz(elements_pd,coordinates_pd,cwd/conformer/f\"{conformer}_opt_Pd.xyz\")\r\n confdata[\"coords\"] = coordinates\r\n confdata[\"coords_pd\"] = coordinates_pd.tolist()\r\n confdata[\"elements\"] = elements\r\n confdata[\"elements_pd\"] = elements_pd\r\n confdata[\"conmat\"] = conmat.tolist()\r\n confdata[\"p_idx\"] = p_idx\r\n confdata[\"p_val\"] = int(sum(conmat[p_idx])) # how many substituents at P\r\n\r\n confdata[\"properties\"] = {}\r\n ## get properties\r\n # gp_properties: everything that can be read from the Gaussian log files (most electronic properties)\r\n confdata.update(gp_properties(ligand,conformer,confdata[\"p_idx\"]))\r\n if confdata[\"error\"]:\r\n #! log this as a conformer-level error\r\n err = \"Error in the Gaussian computations, flagged in read_conformer, please check log files.\"\r\n errors.append(err)\r\n print(f\"{ligand};{conformer};{err}\")\r\n with open(cwd/f\"{ligand}_errors.txt\",\"a\") as f:\r\n f.write(f\"{ligand};{conformer};{err}\\n\")\r\n with open(cwd/conformer/f\"{conformer}_data.yml\",\"w\") as f:\r\n yaml.dump(confdata,f,Dumper=Dumper)\r\n return(confdata,errors)\r\n\r\n if confdata[\"nimag\"] != 0:\r\n #! log this as a conformer-level error\r\n err = f\"Number of imaginary frequencies: {confdata['nimag']}.\"\r\n errors.append(err)\r\n print(f\"{ligand};{conformer};{err}\")\r\n with open(cwd/f\"{ligand}_errors.txt\",\"a\") as f:\r\n f.write(f\"{ligand};{conformer};{err}\\n\")\r\n with open(cwd/conformer/f\"{conformer}_data.yml\",\"w\") as f:\r\n yaml.dump(confdata,f,Dumper=Dumper)\r\n confdata[\"error\"] = True\r\n return(confdata,errors)\r\n\r\n # morfeus: properties that use the geometry/steric properties\r\n confdata[\"properties\"].update(morfeus_properties(confdata[\"elements_pd\"],confdata[\"coords_pd\"],confdata))\r\n\r\n # # P_int\r\n # if \"Pint_P_int\" not in confdata.keys():\r\n # confdata.update(P_int.P_int_main(name=conformer,directory=cwd/conformer))\r\n # read results\r\n disp = \"d3\"\r\n pint_read = P_int.read_dedout(cwd/conformer,conformer,disp)+P_int.read_multiwfnout(cwd/conformer,conformer)+P_int.read_disp(cwd/conformer,conformer,disp)\r\n confdata[\"properties\"].update({Pintresults[i]:float(pint_read[i]) for i in range(7)})\r\n \r\n # V_min\r\n try:\r\n if \"vmin_vmin\" not in confdata.keys():\r\n vminob = vmin.get_vmin(f\"{conformer}.fchk\",str(cwd/conformer)+\"/\",True)\r\n confdata[\"properties\"][\"vmin_vmin\"] = float(vminob.v_min)\r\n confdata[\"properties\"][\"vmin_r\"] = float(vminob.r_min)\r\n except:\r\n err = f\"Vmin FileNotFoundError.\"\r\n errors.append(err)\r\n print(f\"{ligand};{conformer};{err}\")\r\n with open(cwd/f\"{ligand}_errors.txt\",\"a\") as f:\r\n f.write(f\"{ligand};{conformer};{err}\\n\")\r\n confdata[\"error\"] = True\r\n\r\n # visvol\r\n # if \"vv_total_visible_volume\" not in confdata.keys():\r\n # confdata.update(visvol.get_vis_vol(cwd/conformer/f\"{conformer}_opt_Pd.xyz\",radii_type = 'rcov',prox_cutoff = 3.5,ignore_H = 0,write_results = 1, plot = 0))\r\n\r\n with open(cwd/conformer/f\"{conformer}_data.yml\",\"w\") as f:\r\n yaml.dump(confdata,f,Dumper=Dumper)\r\n\r\n return(confdata,errors)\r\n\r\ndef read_ligand(cwd, ligand, conformers, liganddata = {}): # cwd is the ligand-level directory\r\n status = {\"ligandlevel\": [],}\r\n if len(liganddata.keys()) == 0:\r\n if (cwd/f\"{ligand}_data.yml\").exists():\r\n with open(cwd/f\"{ligand}_data.yml\",\"r\") as f:\r\n liganddata = yaml.load(f,Loader=Loader)\r\n if (cwd/f\"{ligand}_confdata.yml\").exists():\r\n with open(cwd/f\"{ligand}_confdata.yml\",\"r\") as f:\r\n liganddata[\"confdata\"] = yaml.load(f,Loader=Loader)\r\n \r\n else:\r\n liganddata = {\r\n \"conformers_all\": conformers, \r\n \"conformers\": conformers.copy(), # Duplicates and computations with errors (including nimag=1) will be removed from this list \r\n \"number_of_conformers\": len(conformers),\r\n \"removed_duplicates\": [],\r\n \"confdata\": {},#{c:{} for c in conformers},\r\n \"boltzmann_averaged_data\": {},\r\n \"min_data\": {},\r\n \"max_data\": {},\r\n \"delta_data\": {},\r\n \"vburminconf_data\": {},\r\n }\r\n\r\n newconfs = 0\r\n for conformer in conformers:\r\n if conformer in liganddata[\"removed_duplicates\"]:\r\n continue\r\n\r\n print(conformer)\r\n if conformer in liganddata[\"confdata\"].keys():\r\n pass\r\n elif (cwd/conformer/f\"{conformer}_data.yml\").exists():\r\n with open(cwd/conformer/f\"{conformer}_data.yml\",\"r\") as f:\r\n liganddata[\"confdata\"][conformer] = yaml.load(f,Loader=Loader)\r\n newconfs += 1\r\n else:\r\n print(\"read conformer data\")\r\n liganddata[\"confdata\"][conformer],status[conformer] = read_conformer(cwd, ligand, conformer) # returns the dictionary with the conformer data and a list with errors\r\n newconfs += 1\r\n\r\n if newconfs > 0:\r\n # error, NIMAG removal\r\n liganddata[\"conformers_w_error\"] = [conformer for conformer in liganddata[\"conformers\"] if liganddata[\"confdata\"][conformer][\"error\"]]\r\n liganddata[\"conformers\"] = [c for c in liganddata[\"conformers\"] if c not in liganddata[\"conformers_w_error\"]]\r\n liganddata[\"number_of_conformers\"] = len(liganddata[\"conformers\"])\r\n energies = [\"e_dz\",\"g\",\"e_tz_gas\",\"g_tz_gas\",\"e_tz_solv\",\"g_tz_solv\"]\r\n liganddata[\"energies\"] = {}\r\n liganddata[\"relative_energies\"] = {}\r\n for e in energies:\r\n liganddata[\"energies\"][e] = {conformer: liganddata[\"confdata\"][conformer][e] for conformer in liganddata[\"conformers\"]}\r\n liganddata[e+\"_min\"] = min(liganddata[\"energies\"][e].values())\r\n liganddata[e+\"_minconf\"] = list(liganddata[\"energies\"][e].keys())[np.argmin(list(liganddata[\"energies\"][e].values()))]\r\n liganddata[\"relative_energies\"][e+\"_rel\"] = {conformer: (liganddata[\"energies\"][e][conformer]-liganddata[e+\"_min\"])*hartree_kcalmol for conformer in liganddata[\"conformers\"]}\r\n\r\n # erel_df = pd.DataFrame(np.array([list(liganddata[e+\"_rel\"].values()) for e in energies]).T ,columns=energies,index=liganddata[\"conformers\"] )\r\n erel_df = pd.DataFrame([liganddata[\"relative_energies\"][e+\"_rel\"] for e in energies],index=energies).T\r\n #liganddata[\"relative_energies_df\"] = erel_df\r\n liganddata[\"relative_energies_dict\"] = erel_df.to_dict()\r\n\r\n # Find duplicates: \r\n # 1) find pairs of conformers that are within E_rel < 0.1 kcal/mol (relative energies seem to be much more reliable than relative free energies)\r\n # 2) check these pairs to also have RMSD < 0.2 A \r\n # 3) Remove the conformer with higher relative free energy\r\n duplicates_candidates = [(i,j) for i,j in itertools.combinations(liganddata[\"conformers\"],2) if abs(erel_df[\"e_dz\"].loc[i] - erel_df[\"e_dz\"].loc[j]) < 0.1]\r\n try:\r\n # Throw a name error here if you wanna only run the except\r\n cores = max(os.cpu_count() - 2, 1)\r\n with Pool(cores) as p:\r\n values = p.map(dict_key_rmsd, duplicates_candidates)\r\n\r\n liganddata[\"rmsd_candidates\"] = {key: value for key, value in zip(duplicates_candidates, values)}\r\n\r\n # The less cool, non-parallel way\r\n #liganddata[\"rmsd_candidates\"] = {candidate_pair: float(rmsd_matrix(candidate_pair)[0,1]) for candidate_pair in duplicates_candidates} # keep all RMSD for potential debugging\r\n liganddata[\"duplicates\"] = [candidate_pair for candidate_pair in liganddata[\"rmsd_candidates\"] if liganddata[\"rmsd_candidates\"][candidate_pair] < 0.2] \r\n \r\n except: # RDkit failed to generate Mol objects and thus could not compute RMSD, or some of the internal structures in those mol files are different despite actually being the same. Default to duplicate detection based on dipole moment and chemical shift similarity\r\n #! log this on ligand level for double-checking\r\n err = \"Warning: RDKit error at duplicate RMSD testing. Please double check.\"\r\n status[\"ligandlevel\"].append(err)\r\n print(f\"{ligand};ligandlevel;{err}\")\r\n with open(cwd/f\"{ligand}_errors.txt\",\"a\") as f:\r\n f.write(f\"{ligand};ligandlevel;{err}\\n\")\r\n \r\n dipole_candidates = set([(i,j) for i,j in duplicates_candidates if abs(liganddata[\"confdata\"][i][\"properties\"][\"dipolemoment\"] - liganddata[\"confdata\"][j][\"properties\"][\"dipolemoment\"]) < 0.025])\r\n nmr_candidates = set([(i,j) for i,j in duplicates_candidates if abs(liganddata[\"confdata\"][i][\"properties\"][\"nmr_P\"] - liganddata[\"confdata\"][j][\"properties\"][\"nmr_P\"]) < 0.1])\r\n liganddata[\"duplicates\"] = sorted(dipole_candidates & nmr_candidates)\r\n\r\n liganddata[\"removed_duplicates\"] = [erel_df.loc[list(pair)][\"g_tz_gas\"].idxmax() for pair in liganddata[\"duplicates\"]]\r\n liganddata[\"conformers\"] = [c for c in liganddata[\"conformers\"] if c not in liganddata[\"removed_duplicates\"]]\r\n liganddata[\"number_of_conformers\"] = len(liganddata[\"conformers\"])\r\n\r\n # Boltzmann averaging \r\n #boltzfacs = {conformer: np.exp(-liganddata[\"relative_energies_df\"][\"g_tz_gas\"].loc[conformer]/(R*T)) for conformer in liganddata[\"conformers\"]}\r\n boltzfacs = {conformer: np.exp(-erel_df[\"g_tz_gas\"].loc[conformer]/(R*T)) for conformer in liganddata[\"conformers\"]}\r\n\r\n Q = sum(boltzfacs.values())\r\n liganddata[\"boltzmann_weights\"] = {conformer: float(boltzfacs[conformer]/Q) for conformer in liganddata[\"conformers\"] } # probability\r\n for prop in boltzproperties:\r\n confsmissingprop = [conf for conf in liganddata[\"conformers\"] if prop not in liganddata[\"confdata\"][conf][\"properties\"].keys()]\r\n if len(confsmissingprop) == 0:\r\n liganddata[\"boltzmann_averaged_data\"][prop] = sum([liganddata[\"boltzmann_weights\"][conf] * liganddata[\"confdata\"][conf][\"properties\"][prop] for conf in liganddata[\"conformers\"]])\r\n else: # if a single conformer is missing a property value, set Boltzmann-average to None\r\n #! log this as a ligand-level error with prop and confsmissingprop\r\n err = f\"Warning: {len(confsmissingprop)}/{len(liganddata['conformers'])} conformers missing values for property {prop}: {','.join(confsmissingprop)}.\"\r\n status[\"ligandlevel\"].append(err)\r\n print(f\"{ligand};ligandlevel;{err}\")\r\n with open(cwd/f\"{ligand}_errors.txt\",\"a\") as f:\r\n f.write(f\"{ligand};ligandlevel;{err}\\n\")\r\n liganddata[\"boltzmann_averaged_data\"][prop] = None\r\n continue\r\n\r\n # \"Condensed\" properties\r\n liganddata[\"vburminconf\"] = liganddata[\"conformers\"][np.argmin([liganddata[\"confdata\"][conf][\"properties\"][\"vbur_vbur\"] for conf in liganddata[\"conformers\"]])]\r\n for prop in mmproperties:\r\n proplist = [liganddata[\"confdata\"][conf][\"properties\"][prop] for conf in liganddata[\"conformers\"] if prop in liganddata[\"confdata\"][conf][\"properties\"].keys()] \r\n # if a single conformer is missing a property value, still perform min/max analysis (Boltzmann-average will be None to indicate missing value(s))\r\n # if all confs are missing this prop, set min/max/delta to None\r\n if len(proplist) == 0:\r\n liganddata[\"min_data\"][prop] = None\r\n liganddata[\"max_data\"][prop] = None\r\n liganddata[\"delta_data\"][prop] = None\r\n liganddata[\"vburminconf_data\"][prop] = None\r\n else:\r\n liganddata[\"min_data\"][prop] = min(proplist)\r\n liganddata[\"max_data\"][prop] = max(proplist)\r\n liganddata[\"delta_data\"][prop] = liganddata[\"max_data\"][prop] - liganddata[\"min_data\"][prop]\r\n liganddata[\"vburminconf_data\"][prop] = liganddata[\"confdata\"][liganddata[\"vburminconf\"]][\"properties\"][prop]\r\n \r\n liganddata[\"time_all\"] = sum([liganddata[\"confdata\"][conf][\"t_total\"] for conf in liganddata[\"conformers_all\"] if \"t_total\" in liganddata[\"confdata\"][conf].keys()])\r\n\r\n with open(cwd/f\"{ligand}_data.yml\",\"w\") as f:\r\n yaml.dump({k:v for k,v in liganddata.items() if k != \"confdata\"},f,Dumper=Dumper)\r\n with open(cwd/f\"{ligand}_confdata.yml\",\"w\") as f:\r\n yaml.dump(liganddata[\"confdata\"],f,Dumper=Dumper)\r\n erel_df.to_csv(cwd/f\"{ligand}_relative_energies.csv\",sep=\";\")\r\n\r\n return(liganddata,status)\r\n\r\n\r\ndef main_split_logs(cwd, ligand):\r\n if not (cwd/\"ERR\").exists():\r\n (cwd/\"ERR\").mkdir()\r\n # if not (cwd/\"done\").exists():\r\n # (cwd/\"done\").mkdir() \r\n conformers = [i.name for i in (cwd/ligand).iterdir() if i.is_dir()]\r\n conformers_good = []\r\n for conformer in conformers:\r\n logs = [i.name for i in (cwd/ligand/conformer).rglob(\"*.log\")]\r\n if f\"{conformer}.log\" in logs and f\"{conformer}_opt.log\" not in logs:\r\n status = split_log(ligand, conformer)\r\n if status != \"Error\":\r\n #(cwd/ligand/conformer/f\"{conformer}.log\").rename(cwd/f\"done/{conformer}.log\")\r\n conformers_good.append(conformer)\r\n return(conformers_good)\r\n\r\nif __name__ == '__main__': \r\n starttime_all = time.time()\r\n\r\n ligname = re.compile(\"[0-9]{8}\") \r\n ligands = sorted([i.name for i in cwd.iterdir() if (ligname.match(i.name) and i.is_dir())])\r\n conformers = {ligand: [i.name for i in (cwd/ligand).iterdir() if i.is_dir()] for ligand in ligands}\r\n\r\n if not (cwd/\"ERR\").exists():\r\n (cwd/\"ERR\").mkdir()\r\n if not (cwd/\"done\").exists():\r\n (cwd/\"done\").mkdir() \r\n\r\n for ligand in ligands:\r\n for conformer in conformers[ligand]:\r\n logs = [i.name for i in (cwd/ligand/conformer).rglob(\"*.log\")]\r\n if f\"{conformer}.log\" in logs and f\"{conformer}_opt.log\" not in logs:\r\n status = split_log(ligand,conformer)\r\n if status != \"Error\":\r\n (cwd/ligand/conformer/f\"{conformer}.log\").rename(cwd/f\"done/{conformer}.log\")\r\n\r\n \r\n if (cwd/\"allligands_data.yml\").exists():\r\n with open(cwd/\"allligands_data.yml\",\"r\") as f:\r\n allliganddata = yaml.load(f,Loader=Loader)\r\n else:\r\n allliganddata = {}\r\n\r\n for ligand in ligands:\r\n print(ligand)\r\n print(conformers[ligand])\r\n if ligand in allliganddata.keys():\r\n allliganddata[ligand],status = read_ligand(cwd,ligand,conformers[ligand],allliganddata[ligand])\r\n else:\r\n allliganddata[ligand],status = read_ligand(cwd,ligand,conformers[ligand])\r\n\r\n with open(cwd/\"allligands_data.yml\",\"w\") as f:\r\n yaml.dump(allliganddata,f,Dumper=Dumper)\r\n\r\n variants = [\"boltz\",\"min\",\"max\",\"delta\",\"vburminconf\"]\r\n columns = [i+\"_boltz\" for i in boltzproperties if i not in mmproperties] + [f\"{i}_{j}\" for i,j in itertools.product(mmproperties,variants)]# + [\"t_total\",\"number_of_conformers\"] \r\n df = pd.DataFrame(columns = columns,index = ligands)\r\n for l in ligands:\r\n for c in columns:\r\n print(allliganddata[l][\"properties\"])\r\n exit()\r\n df.loc[l][c] = allliganddata[l][\"properties\"][c]\r\n df[\"t_total\"] = [allliganddata[l][\"t_total\"] for l in ligands]\r\n df[\"number_of_conformers\"] = [allliganddata[l][\"number_of_conformers\"] for l in ligands]\r\n df.to_csv(\"allligands_data.csv\",sep=\";\")\r\n\r\n print(f\"All done. Total time: {round((time.time()-starttime_all),2)} sec\")\r\n \r\n", "import os,sys,re\nimport numpy as np\nimport pandas as pd\nimport subprocess\nimport multiprocessing\nfrom shutil import copyfileobj\nimport bz2\nfrom distutils.util import strtobool\n\n# parameters\nBA = 0.529177 # Bohr - Angstrom conversion\nnumbers_pattern = re.compile(r\"[-+]?\\d*\\.\\d+|\\d+\") \n\n# box dimensions:\n# standard presets for Phosphines\nclass Grid_def:\n def __init__(self,size):\n if size == 0:\n self.dxy = 0.85/BA # dimensions perpendicular to P-LP\n self.dz = 0.8/BA #0.5 dimension in P-LP direction\n self.d_lp = 2.0/BA #1.9# distance of grid center from P\n self.npoints = [25,25,40] # number of grid points in x,y,z directions\n elif size == 1:\n self.dxy = 1.9/BA # dimensions perpendicular to P-LP\n self.dz = 1.0/BA #0.5 dimension in P-LP direction\n self.d_lp = 2.15/BA #1.9# distance of grid center from P\n self.npoints = [50,50,50] # number of grid points in x,y,z directions\n\n\n \ndxy = 0.85/BA # dimensions perpendicular to P-LP\ndz = 0.8/BA #0.5 dimension in P-LP direction\nd_lp = 2.0/BA #1.9# distance of grid center from P\nnpoints = [25,25,40] # number of grid points in x,y,z directions\n\n# alternative presets for very electron-poor phosphines\n# dxy = 1.5/BA # dimensions perpendicular to P-LP\n# dz = 1.50/BA # dimension in P-LP direction\n# d_lp = 2.5/BA # distance of grid center from P\n# npoints = [30,30,50] # number of grid points in x,y,z directions\n# dxy = 1.9/BA # dimensions perpendicular to P-LP\n# dz = 1.0/BA # dimension in P-LP direction\n# d_lp = 2.0/BA # distance of grid center from P\n# npoints = [50,50,50] # number of grid points in x,y,z directions\n\n# for N ligands\n# dxy = 0.9/BA # dimensions perpendicular to P-LP\n# dz = 0.5/BA # dimension in P-LP direction\n# d_lp = 1.4/BA # distance of grid center from P\n# npoints = [25,25,25] # number of grid points in x,y,z directions\n\nrcov = {\n\"H\": 0.32,\"He\": 0.46,\"Li\": 1.2,\"Be\": 0.94,\"B\": 0.77,\"C\": 0.75,\"N\": 0.71,\"O\": 0.63,\"F\": 0.64,\"Ne\": 0.67,\"Na\": 1.4,\"Mg\": 1.25,\"Al\": 1.13,\"Si\": 1.04,\"P\": 1.1,\"S\": 1.02,\"Cl\": 0.99,\"Ar\": 0.96,\"K\": 1.76,\"Ca\": 1.54,\"Sc\": 1.33,\"Ti\": 1.22,\"V\": 1.21,\"Cr\": 1.1,\"Mn\": 1.07,\"Fe\": 1.04,\"Co\": 1.0,\"Ni\": 0.99,\"Cu\": 1.01,\"Zn\": 1.09,\"Ga\": 1.12,\"Ge\": 1.09,\"As\": 1.15,\"Se\": 1.1,\"Br\": 1.14,\"Kr\": 1.17,\"Rb\": 1.89,\"Sr\": 1.67,\"Y\": 1.47,\"Zr\": 1.39,\"Nb\": 1.32,\"Mo\": 1.24,\"Tc\": 1.15,\"Ru\": 1.13,\"Rh\": 1.13,\"Pd\": 1.08,\"Ag\": 1.15,\"Cd\": 1.23,\"In\": 1.28,\"Sn\": 1.26,\"Sb\": 1.26,\"Te\": 1.23,\"I\": 1.32,\"Xe\": 1.31,\"Cs\": 2.09,\"Ba\": 1.76,\"La\": 1.62,\"Ce\": 1.47,\"Pr\": 1.58,\"Nd\": 1.57,\"Pm\": 1.56,\"Sm\": 1.55,\"Eu\": 1.51,\"Gd\": 1.52,\"Tb\": 1.51,\"Dy\": 1.5,\"Ho\": 1.49,\"Er\": 1.49,\"Tm\": 1.48,\"Yb\": 1.53,\"Lu\": 1.46,\"Hf\": 1.37,\"Ta\": 1.31,\"W\": 1.23,\"Re\": 1.18,\"Os\": 1.16,\"Ir\": 1.11,\"Pt\": 1.12,\"Au\": 1.13,\"Hg\": 1.32,\"Tl\": 1.3,\"Pb\": 1.3,\"Bi\": 1.36,\"Po\": 1.31,\"At\": 1.38,\"Rn\": 1.42,\"Fr\": 2.01,\"Ra\": 1.81,\"Ac\": 1.67,\"Th\": 1.58,\"Pa\": 1.52,\"U\": 1.53,\"Np\": 1.54,\"Pu\": 1.55\n}\n\nelements = {\n\"1\": \"H\",\n\"5\": \"B\",\n\"6\": \"C\",\n\"7\": \"N\",\n\"8\": \"O\",\n\"9\": \"F\",\n\"14\": \"Si\",\n\"15\": \"P\",\n\"16\": \"S\",\n\"17\": \"Cl\",\n\"26\": \"Fe\",\n\"33\": \"As\",\n\"34\": \"Se\",\n\"35\": \"Br\",\n\"44\": \"Ru\",\n\"46\": \"Pd\",\n\"51\": \"Sb\",\n\"53\": \"I\",\n}\n\nclass Vminob:\n def __init__(self,name,ext,status):\n self.name = name\n self.ext = ext\n if status == \"\" or status == \"stdcube\":\n self.dxy = 0.85/BA # dimensions perpendicular to P-LP\n self.dz = 0.8/BA #0.5 dimension in P-LP direction\n self.d_lp = 2.0/BA #1.9# distance of grid center from P\n self.npoints = [25,25,40] # number of grid points in x,y,z directions\n elif status == \"follow_edge\":\n self.dxy = 1.9/BA # dimensions perpendicular to P-LP\n self.dz = 1.0/BA #0.5 dimension in P-LP direction\n self.d_lp = 2.15/BA #1.9# distance of grid center from P\n self.npoints = [50,50,50] # number of grid points in x,y,z directions\n\n def p_lp(self,iteration): \n # expects a three-coordinate P containing compound. Adds a valence to P so that the angle to the three previous substituents is maximized and resorts the coordinate output for convenience\n\n for i,atom in enumerate(self.coords):\n if (atom[0] == \"P\" or atom[0] == \"As\" or atom[0] == \"Sb\") and sum(self.conmat[i]) <=3:\n self.nop = i\n self.coordp = np.array(self.coords[i][1:])\n break\n\n vec = np.array([0.0,0.0,0.0])\n bonded = []\n for atom in range(len(self.coords)):\n if self.conmat[self.nop][atom]:\n bonded.append(atom)\n coorda = np.array(self.coords[atom][1:])\n vec += self.coordp - coorda\n self.coordlp = self.d_lp*vec/np.linalg.norm(vec) + self.coordp # coordinates of grid center\n\n atomno = max(iteration-1,0)\n dir_bond1 = np.array((self.coords[bonded[atomno]][1:]))-np.array((self.coords[self.nop][1:])) # direction of first P-R bond \n dirx = np.cross(dir_bond1,vec) # defines the x-direction of the grid\n diry = np.cross(vec,dirx) # defines the y-direction of the grid\n\n self.dirx = dirx/np.linalg.norm(dirx) # normalization of the grid-coordinate system\n self.diry = diry/np.linalg.norm(diry)\n self.dirz = vec/np.linalg.norm(vec)\n self.grid_coords = [self.dirx*self.dxy/self.npoints[0],self.diry*self.dxy/self.npoints[1],self.dirz*self.dz/self.npoints[2]]\n # grid_coords = [2*dirx/npoints[0],2*diry/npoints[1],dirz/2*npoints[2]]\n self.grid_or = self.coordlp - self.dz*0.5 * self.dirz - 0.5*self.dxy * self.diry - 0.5*self.dxy * self.dirx # grid_origin\n return()\n\n def copy_info(self,prev):\n self.coords = prev.coords\n self.conmat = prev.conmat\n self.nop = prev.nop\n self.coordp = prev.coordp\n self.coordlp = prev.coordlp\n self.dirx = prev.dirx\n self.diry = prev.diry\n self.dirz = prev.dirz\n self.grid_coords = prev.grid_coords\n self.grid_or = prev.grid_or\n\n def follow_vmin(self,coords_vmin_prev):\n vec_P_vmin_prev = coords_vmin_prev - self.coordp\n grid_center = self.coordp + vec_P_vmin_prev / np.linalg.norm(vec_P_vmin_prev) * (np.linalg.norm(vec_P_vmin_prev)+0.5)\n self.dirx = np.cross(self.coordlp,vec_P_vmin_prev)\n self.diry = np.cross(vec_P_vmin_prev,self.dirx)\n self.dirx = self.dirx/np.linalg.norm(self.dirx) # normalization of the grid-coordinate system\n self.diry = self.diry/np.linalg.norm(self.diry)\n self.dirz = vec_P_vmin_prev/np.linalg.norm(vec_P_vmin_prev)\n self.grid_coords = [self.dirx*self.dxy/self.npoints[0],self.diry*self.dxy/self.npoints[1],self.dirz*self.dz/self.npoints[2]]\n self.grid_or = grid_center - self.dz*0.5 * self.dirz - 0.5*self.dxy * self.diry - 0.5*self.dxy * self.dirx # grid_origin\n\n # print(\"coords_vmin_prev: {:.2f},{:.2f},{:.2f}\\ngrid_center: {:.2f},{:.2f},{:.2f}\\ngrid_or: {:.2f},{:.2f},{:.2f}\\n\".format(*coords_vmin_prev,*grid_center,*self.grid_or))\n\n def read_cubtxt(self,directory=\"./\"):\n name = directory + self.name\n get_permission(name + \"_Pesp_out\"+self.suffix+\".txt\")\n with open(name + \"_Pesp_out\"+self.suffix+\".txt\") as f:\n cubtxt = f.readlines()\n self.esp = np.array(([float(line.split()[-1]) for line in cubtxt]))\n self.v_min = np.amin(self.esp)\n self.vmin_ind = int(np.where(self.esp==self.v_min)[0][0])\n self.coords_min = np.array(([float(i) for i in cubtxt[self.vmin_ind].split()[:3]])) # find index of v_min, get coordinates in Bohr\n return()\n\n def analyze_vmin(self,directory=\"./\"):\n npoints = self.npoints\n name = directory + self.name\n self.r_min = np.linalg.norm(self.coords_min - self.coordp)*BA\n self.line_pos = self.vmin_ind + 1\n\n if self.line_pos % npoints[2] in [0,1]:\n self.on_edge = True\n elif (self.line_pos <= npoints[2] * npoints[1]) or (npoints[2] * npoints[1] * npoints[0] - self.line_pos <= npoints[2] * npoints[1]):\n self.on_edge = True\n elif (self.line_pos % (npoints[2] * npoints[1]) <= npoints[2]) or (npoints[2] * npoints[1] - (self.line_pos % (npoints[2] * npoints[1])) <= npoints[2]):\n self.on_edge = True\n else:\n self.on_edge = False\n\n self.vminatom,self.vmindist = \"\",\"\"\n rmin_other = {(i[0]+str(j+1)): np.linalg.norm(self.coords_min - np.array(i[1:])) * BA for j,i in enumerate(self.coords) if i[0] not in [\"H\",\"P\"]}\n rmin_other_S = pd.Series(rmin_other)\n\n if rmin_other_S.min() < self.r_min/1.1: # scaled P to account for larger radius vs. most other elements\n self.wrongatom = True\n # print(\"{};Vmin of other atom;{}\".format(self.name,rmin_other_S.idxmin()))\n self.vminatom = rmin_other_S.idxmin()\n self.vmindist = rmin_other_S.min()\n else:\n self.wrongatom = False\n\n self.coords_min_A = self.coords_min * BA\n\n with open(name + \"_vmin_results2.txt\",\"a\") as f:\n f.write(\"{};{};{};{:.5f};{};{};{:.4f};{:.4f};{:.4f}\\n\".format(self.name,self.suffix,self.v_min,self.r_min,self.on_edge,self.wrongatom,*self.coords_min_A))\n \n # print(self.name,\";\",self.r_min)\n \n return()\n\n def get_geom_cub(self,directory=\"./\"):\n # reads the geometry out of a cube file (in Bohr)\n file = directory + self.name + \"_Pesp_out.cub\" \n self.coords = []\n self.grid_coords = [[],[],[]]\n get_permission(file)\n with open(file) as f:\n fcont = f.readlines()\n natoms = int(re.findall(numbers_pattern,fcont[2])[0])\n self.grid_or = np.asarray([float(i) for i in re.findall(numbers_pattern,fcont[2])[1:]])\n for i in range(3):\n self.npoints[i] = int(re.findall(numbers_pattern,fcont[3+i])[0])\n self.grid_coords[i] = np.asarray([float(j) for j in re.findall(numbers_pattern,fcont[3+i])[1:]])\n self.dirx = self.grid_coords[0]/np.linalg.norm(self.grid_coords[0]) # normalization of the grid-coordinate system\n self.diry = self.grid_coords[1]/np.linalg.norm(self.grid_coords[1])\n self.dirz = self.grid_coords[2]/np.linalg.norm(self.grid_coords[2])\n\n # self.dxy = self.grid_coords[0]*self.npoints[0]/self.dirx\n # self.dz = self.grid_coords[2]*self.npoints[2]/self.dirz\n # self.d_lp = (self.grid_or - (self.coordp - self.dz*0.5 * self.dirz - 0.5*self.dxy * self.diry - 0.5*self.dxy * self.dirx))/self.dirz\n\n \n\n\n for line in fcont[6:6+natoms]:\n linesplit = re.findall(numbers_pattern,line)\n if len(linesplit) != 5:\n break\n if linesplit[0] not in elements.keys():\n print(\"Element not implemented in code: \"+linesplit[0])\n continue\n else: \n self.coords.append([elements[linesplit[0]]]+[float(i) for i in linesplit[2:]])\n return()\n\n\ndef get_permission(filepath):\n if not os.access(filepath,os.R_OK):\n os.chmod(filepath, 0o777)\n\n\ndef get_files(ext):\n files = []\n for file in os.listdir(\".\"):\n if file[-len(ext):] == ext:\n files.append(file)\n return(files)\n\ndef get_geom_fch(vminob,directory=\"./\"):\n file = directory + vminob.name + \".\" + vminob.ext\n get_permission(file)\n with open(file) as f:\n natoms = 250\n content = []\n for line in f:\n content.append(line)\n if len(content) == 3:\n natoms = int(content[-1].split()[-1])\n elif \"Atomic numbers\" in line:\n atomnumbersstart = len(content)-1\n elif \"Nuclear charges\" in line:\n atomnumbersend = len(content)-1\n elif \"Current cartesian coordinates\" in line:\n coordsstart = len(content)-1\n elif \"Number of symbols\" in line:\n coordsend = len(content)-1\n break\n elif \"Force Field\" in line:\n coordsend = len(content)-1\n break\n\n atoms,atomnos = [],[]\n for line in range(atomnumbersstart+1,atomnumbersend):\n atomnos += content[line].split()\n for atom in atomnos:\n if atom in elements:\n atoms.append(elements[atom]),\n else: \n atoms.append(atom)\n\n coords = []\n coordsstream = []\n for line in range(coordsstart+1,coordsend):\n coordsstream += content[line].split()\n coordsstream = [float(i) for i in coordsstream]\n for atom in range(natoms):\n coords.append([atoms[atom]]+coordsstream[atom*3:atom*3+3])\n #print(coords)\n return(coords)\n\ndef get_conmat(rcov, coords): # partially based on code from Robert Paton's Sterimol script, which based this part on Grimme's D3 code\n natom = len(coords)\n max_elem = 94\n k1 = 16.0\n k2 = 4.0/3.0\n conmat = np.zeros((natom,natom))\n for i in range(0,natom):\n if coords[i][0] not in rcov.keys():\n continue\n for iat in range(0,natom):\n if coords[iat][0] not in rcov.keys():\n continue\n if iat != i:\n dx = coords[iat][1] - coords[i][1]\n dy = coords[iat][2] - coords[i][2]\n dz = coords[iat][3] - coords[i][3]\n r = np.linalg.norm([dx,dy,dz])*BA # with conversion Bohr - Angstrom\n rco = rcov[coords[i][0]]+rcov[coords[iat][0]]\n rco = rco*k2\n rr=rco/r\n damp=1.0/(1.0+np.math.exp(-k1*(rr-1.0)))\n if damp > 0.85: \n conmat[i,iat],conmat[iat,i] = 1,1\n return(conmat)\n\ndef write_inpcube(vminob,directory=\"./\"):\n name = directory + vminob.name\n writecont = \" \" + name + \" potential=scf\\n Electrostatic potential from Total SCF Density\\n\"\n writecont += \"{0:>5}{1[0]:>12.6f}{1[1]:>12.6f}{1[2]:>12.6f}\\n\".format(len(vminob.coords),vminob.grid_or)\n for i in range(3):\n writecont += \"{0:>5}{1[0]:>12.6f}{1[1]:>12.6f}{1[2]:>12.6f}\\n\".format(vminob.npoints[i],vminob.grid_coords[i])\n\n with open(name+\"_Pesp_in\"+vminob.suffix+\".cub\",\"w\",newline=\"\\n\") as f:\n f.write(writecont) \n return()\n\ndef run_cubman(n_in,suffix,directory=\"./\"):\n name = directory + n_in\n a = subprocess.Popen(\"cubman\", stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n inputargs = \"to\\n\"+ name + \"_Pesp_out\"+suffix+\".cub\\ny\\n\" + name + \"_Pesp_out\"+suffix+\".txt\\n\"\n a_out = a.communicate(input=inputargs.encode()) \n return()\n\ndef run_cubegen(n_in,suffix,directory=\"./\"):\n name = directory + n_in\n #nproc = str(multiprocessing.cpu_count() - 2)\n nproc = '1'\n try: \n os.stat(name + \"_Pesp_out\"+suffix+\".cub\")\n except:\n a = subprocess.run(\"cubegen \"+nproc+\" potential=scf \" + name + \".fchk \" + name + \"_Pesp_out\"+suffix+\".cub -1 h \" + name + \"_Pesp_in\"+suffix+\".cub\",shell=True, stdout=subprocess.PIPE)\n os.remove(name + \"_Pesp_in\"+suffix+\".cub\")\n return()\n\ndef read_cubes(n_in,suffix,directory=\"./\"):\n name = directory + n_in\n get_permission(name+\"_Pesp_out\"+suffix+\".cub\")\n with open(name+\"_Pesp_out\"+suffix+\".cub\") as f:\n cube = f.readlines()\n natoms = int(cube[2].split()[0])\n esp = np.array(([float(num) for line in cube[6+natoms:] for num in line.split()]))\n with open(directory+\"vmin_results.txt\",\"a\") as f:\n f.write(\"%s;%s\\n\" %(n_in,np.amin(esp)))\n return(np.amin(esp))\n\n# def analyze_vmin(self,writefile=True,suffix=\"\"):\n# self.rmin = np.linalg.norm(self.coords_vmin - self.coordp) * BA\n# vec0 = self.coords_vmin - self.coordlp\n\n\n# line_pos = self.vmin_ind + 1\n# if line_pos % self.npoints[2] in [0,1]:\n# self.on_edge = \"true\"\n# elif (line_pos <= self.npoints[2] * self.npoints[1]) or (self.npoints[2] * self.npoints[1] * self.npoints[0] - line_pos <= self.npoints[2] * self.npoints[1]):\n# self.on_edge = \"true\"\n# elif (line_pos % (self.npoints[2] * self.npoints[1]) <= self.npoints[2]) or (self.npoints[2] * self.npoints[1] - (line_pos % (self.npoints[2] * self.npoints[1])) <= self.npoints[2]):\n# self.on_edge = \"true\"\n# else:\n# self.on_edge = \"false\"\n\n# #on_edge = \"false\"\n# #for i in range(3):\n# # crit = np.linalg.norm(self.grid_info[i+1] * (self.npoints[i] - 2) / 2.0) # should be (self.npoints[i] - 1) instead of 2\n# # dist = np.absolute(np.dot(vec0, norm_vec(self.grid_info[i + 1])))\n# # print(dim[i],self.grid_info[i+1],self.npoints[i],crit,dist)\n# # if dist > crit:\n# # on_edge = \"true\"\n# # break\n# self.vminatom,self.vmindist = \"\",\"\"\n# rmin_other = {(i[0]+str(j+1)): np.linalg.norm(self.coords_vmin - np.array(i[1:])) * BA for j,i in enumerate(self.coords) if i[0] not in [\"H\",\"P\"]}\n# rmin_other_S = pd.Series(rmin_other)\n\n# if rmin_other_S.min() < self.rmin/1.1: # scaled P to account for larger radius vs. most other elements\n# self.wrongatom = True\n# print(\"{};Vmin of other atom;{}\".format(self.name,rmin_other_S.idxmin()))\n# self.vminatom = rmin_other_S.idxmin()\n# self.vmindist = rmin_other_S.min()\n# else:\n# self.wrongatom=False\n# coords_min_A = self.coords_vmin * BA\n# if writefile:\n# with open(\"vmin_results.txt\", \"a\") as f:\n# f.write(\"%s;%s;%s;%s;%s;coordinates;%s;%s;%s;%s;%s\\n\" % (self.name,suffix, self.vmin, self.rmin, self.on_edge, coords_min_A[0], coords_min_A[1], coords_min_A[2],self.vminatom,self.vmindist))\n# return()\n\n\ndef get_vmin(infile,directory=\"./\",runcub=False):\n if \"_Pesp_out\" in infile:\n name = infile.split(\"_Pesp_out.\")[0]\n ext = infile.split(\"_Pesp_out.\")[1]\n else:\n name = infile.split(\".\")[0]\n ext = infile.split(\".\")[1] \n\n vminobjects = []\n\n # if f\"{name}_vmin_results2.txt\" in os.listdir(directory):\n # with open(directory+name+\"_vmin_results2.txt\",\"r\") as f:\n # vmincont = f.readlines()\n # for line in vmincont[1:]: \n # result = vmincont[-1].strip().split(\";\")\n # vminob = Vminob(name,\"txt\",\"done\")\n # vminob.suffix = result[1]\n # vminob.v_min = float(result[2])\n # vminob.r_min = float(result[3])\n # vminob.on_edge = bool(strtobool(result[4]))\n # vminob.wrongatom = bool(strtobool(result[4]))\n # vminobjects.append(vminob)\n # if not vminob.on_edge and not vminob.wrongatom:\n # return(vminob) \n # stdcubes = [i for i in vminobjects if \"stdcube\" in i.suffix]\n # if len(stdcubes) == 3:\n # mincubeno = np.argmin([i.v_min for i in stdcubes])\n # return(stdcubes[mincubeno]) \n \n # try:\n # os.stat(name+\"_vmin_results.txt\")\n # print(\"reading results \"+ name)\n # v_min,r_min = read_vmin_results(name,\"./\")\n # with open(\"vmin_results.txt\",\"a\") as f:\n # f.write(\"%s;%s\\n\" %(v_min,r_min))\n # except:\n #print(\"writing cub \" + name)\n\n with open(directory+name+\"_vmin_results2.txt\",\"w\") as f:\n f.write(\"Name;Suffix;Vmin;R(Vmin);On_edge;Wrong_atom;X_Vmin;Y_Vmin;Z_Vmin\\n\")\n\n status = \"\"\n # status:\n # \"\": normal/first pass\n # \"follow_edge\": previous vmin was on edge of cube\n # \"stdcube\": no vmin was found at P; generate three cubes around expected P lone pair\n # \"done\": finished procedure\n\n iteration = 0\n while status != \"done\":\n vminob = Vminob(name,ext,status)\n if iteration == 0 and \"fch\" in ext:\n vminob.coords = get_geom_fch(vminob,directory)\n vminob.conmat = get_conmat(rcov, vminob.coords)\n elif iteration == 0 and ext == \"cub\":\n vminob.get_geom_cub(directory)\n vminob.conmat = get_conmat(rcov, vminob.coords) \n else:\n vminob.coords = vminobjects[0].coords\n vminob.conmat = vminobjects[0].conmat\n\n if status == \"follow_edge\":\n vminob.copy_info(vminobjects[0])\n vminob.follow_vmin(vminobjects[-1].coords_min)\n else:\n vminob.p_lp(iteration)\n\n vminob.suffix = (\"_\"+status+str(iteration))*bool(len(status))\n\n try:\n os.stat(directory+name + \"_Pesp_out\"+vminob.suffix+\".cub\")\n except:\n if vminob.ext == \"cub\":\n if runcub == False: # perform analysis only\n with open(directory+name + \"_vmin_results2.txt\",\"a\") as f:\n f.write(\"{};{};Problem encountered, run additional cubegens\\n\".format(vminob.name,vminob.suffix))\n print(\"{};{};Problem encountered, run additional cubegens\".format(vminob.name,vminob.suffix))\n break\n elif name+\".fchk\" in os.listdir(directory):\n vminob.ext = \"fchk\"\n write_inpcube(vminob,directory)\n run_cubegen(name,vminob.suffix,directory)\n elif name+\".fchk.bz2\" in os.listdir(directory):\n try:\n get_permission(directory+name+\".fchk.bz2\")\n with bz2.BZ2File(directory+name+\".fchk.bz2\", 'rb', compresslevel=9) as i:\n with open(directory+name+\".fchk\", 'wb') as o:\n copyfileobj(i, o)\n vminob.ext = \"fchk\"\n write_inpcube(vminob)\n run_cubegen(name,vminob.suffix,directory)\n except:\n with open(directory+name + \"_vmin_results2.txt\",\"a\") as f:\n f.write(\"{};{};Problem extracting .fchk.bz2 for further analysis\\n\".format(vminob.name,vminob.suffix))\n print(\"{};{};Problem extracting .fchk.bz2 for further analysis\\n\".format(vminob.name,vminob.suffix))\n break\n else:\n with open(directory+name + \"_vmin_results2.txt\",\"a\") as f:\n f.write(\"{};{};Missing .fchk for further analysis\\n\".format(vminob.name,vminob.suffix))\n print(\"{};{};Missing .fchk for further analysis\\n\".format(vminob.name,vminob.suffix))\n break\n else:\n write_inpcube(vminob,directory)\n run_cubegen(name,vminob.suffix,directory)\n\n try:\n os.stat(directory+name + \"_Pesp_out\"+vminob.suffix+\".txt\")\n except:\n run_cubman(name,vminob.suffix,directory)\n\n vminob.read_cubtxt(directory)\n vminob.analyze_vmin(directory)\n\n vminobjects.append(vminob)\n\n # print(\"\\non_edge: {}\\nwrongatom: {}\\niteration: {}\\nstatus: {}\".format(vminob.on_edge,vminob.wrongatom,iteration,status))\n if vminob.on_edge == False and vminob.wrongatom == False:\n status = \"done\"\n with open(\"vmin_results.txt\",\"a\") as f:\n f.write(\"%s;%s;%s\\n\" %(name,vminob.v_min,vminob.r_min))\n return(vminob)\n\n elif vminob.on_edge == True and iteration <3 and status != \"stdcube\":\n status = \"follow_edge\"\n # print(\"changed: \"+status)\n else: \n if status != \"stdcube\":\n iteration = 0\n status = \"stdcube\"\n # print(\"changed: \"+status)\n \n elif iteration == 3:\n status = \"done\"\n foundmin = np.argwhere(np.array([not(i.on_edge or i.wrongatom) for i in vminobjects[-3:]]) == True ) # check if any of the three stdcubes found an actual Vmin\n if len(foundmin) > 0:\n mincubeno = np.argmin([vminobjects[-3+i].v_min for i in foundmin])\n else:\n mincubeno = np.argmin([i.v_min for i in vminobjects[-3:]])\n mincube = vminobjects[-3+mincubeno]\n with open(directory+name + \"_vmin_results2.txt\",\"a\") as f:\n f.write(\"{};{};{};{:.5f};{};{};{:.4f};{:.4f};{:.4f}\\n\".format(mincube.name,mincube.suffix,mincube.v_min,mincube.r_min,mincube.on_edge,mincube.wrongatom,*mincube.coords_min_A))\n\n with open(\"vmin_results.txt\",\"a\") as f:\n f.write(\"%s;%s;%s\\n\" %(mincube.name,mincube.v_min,mincube.r_min))\n return(mincube)\n\n iteration +=1\n\n return(vminobjects[-1])\n\nif __name__ == \"__main__\":\n # arguments can be an individual file of the following kind: name.fch, name.fchk, name.cub\n # if no argument is passed, all .fchk files in the current directory will be parsed. \n # if no .fchks are present, all .cub files will be parsed.\n todo = []\n if \"fch\" in sys.argv[-1] or \"cub\" in sys.argv[-1]:\n todo = [sys.argv[-1]]\n\n else:\n todo = get_files(\"fch\") + get_files(\"fchk\")\n if len(todo) == 0:\n todo = get_files(\"_Pesp_out.cub\")\n try:\n os.stat(\"vmin_results.txt\")\n except:\n with open(\"vmin_results.txt\",\"w\",newline=\"\\n\") as f:\n f.write(\"\\n\") \n\n for todofile in sorted(todo):\n get_vmin(todofile,\"./\",True)\n\n\n\n \n" ]
[ [ "numpy.math.exp", "numpy.asarray", "numpy.linalg.norm", "pandas.DataFrame", "numpy.append", "numpy.argmin", "numpy.exp", "numpy.array", "numpy.zeros", "numpy.vstack" ], [ "numpy.math.exp", "pandas.Series", "numpy.amin", "numpy.linalg.norm", "numpy.argmin", "numpy.cross", "numpy.array", "numpy.zeros", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "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": [] } ]
dptam/text-to-text-transfer-transformer
[ "3662823b126ebf39d9d8ed147a8af0c6973f0ba9" ]
[ "t5/seqio/dataset_providers.py" ]
[ "# Copyright 2021 The T5 Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"Classes for data loading and processing.\n\nDefines Tasks, TaskRegistry, Mixture, and MixtureRegistry\n\"\"\"\n\nimport abc\nimport collections\nimport inspect\nimport json\nimport os\nimport re\nfrom typing import Any, Callable, Iterable, Mapping, MutableMapping, Optional, Sequence, Tuple, Type, Union\n\nfrom absl import logging\nimport dataclasses\nimport numpy as np\nfrom packaging import version\nfrom t5.seqio import utils\nfrom t5.seqio.feature_converters import FeatureConverter\nfrom t5.seqio.vocabularies import Vocabulary\nimport tensorflow.compat.v2 as tf\nimport tensorflow_datasets as tfds\nimport typing_extensions\n\n\n_DEFAULT_FEATURE_KEYS = [\"inputs\", \"targets\"]\n\n_VALID_TASK_NAME_REGEX = re.compile(r\"^[\\w\\d\\._]+$\")\n_MAX_EXAMPLES_TO_MEM_CACHE = 10000\nSHUFFLE_BUFFER_SIZE = 1000\n\n\[email protected](frozen=True)\nclass Feature:\n \"\"\"A container for attributes of output features of data providers.\"\"\"\n vocabulary: Vocabulary\n add_eos: bool = True\n required: bool = True\n dtype: tf.DType = tf.int32\n\n\[email protected](frozen=True)\nclass ShardInfo:\n \"\"\"A container for specifying sharding info.\"\"\"\n index: int\n num_shards: int\n\n\nclass DatasetProviderBase(metaclass=abc.ABCMeta):\n \"\"\"Abstract base for classes that provide a tf.data.Dataset.\"\"\"\n\n @abc.abstractproperty\n def output_features(self) -> Mapping[str, Feature]:\n raise NotImplementedError\n\n @abc.abstractproperty\n def splits(self) -> Sequence[str]:\n raise NotImplementedError\n\n @abc.abstractmethod\n def get_dataset(\n self,\n sequence_length: int,\n split: str,\n use_cached: bool = False,\n shuffle: bool = True,\n seed: Optional[int] = None,\n shard_info: Optional[ShardInfo] = None,\n num_epochs: int = 1\n ) -> tf.data.Dataset:\n \"\"\"Returns the requested tf.data.Dataset.\"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def num_input_examples(self, split: str) -> int:\n raise NotImplementedError\n\n\nclass DatasetProviderRegistry(object):\n \"\"\"Base for registry of data providers.\n\n Subclasses must wrap `get` method to override the return type for pytype.\n TODO(adarob): Remove the need to override `get`.\n \"\"\"\n # Class variables must be defined in subclasses.\n _REGISTRY: MutableMapping[str, DatasetProviderBase]\n _PROVIDER_TYPE: Type[DatasetProviderBase]\n\n @classmethod\n def add_provider(cls, name: str, provider):\n \"\"\"Adds a data provider instance to the registry.\"\"\"\n if name in cls._REGISTRY:\n raise ValueError(\"Attempting to register duplicate provider: %s\" % name)\n if not isinstance(provider, cls._PROVIDER_TYPE):\n raise ValueError(\n \"Attempting to register a class not of an invalid type. \"\n \"Expecting instance of %s, got %s\" %\n (cls._PROVIDER_TYPE, type(provider).__name__))\n\n cls._REGISTRY[name] = provider\n\n @classmethod\n def add(\n cls,\n name: str,\n provider_cls,\n *provider_args,\n **provider_kwargs\n ):\n \"\"\"Instantiates and adds provider to the registry.\"\"\"\n if not issubclass(provider_cls, cls._PROVIDER_TYPE):\n raise ValueError(\n \"Attempting to register a class not of an invalid type. \"\n \"Expecting instance of %s, got %s\" %\n (cls._PROVIDER_TYPE, provider_cls))\n provider = provider_cls(*provider_args, **provider_kwargs)\n cls.add_provider(name, provider)\n return provider\n\n @classmethod\n def remove(cls, name):\n \"\"\"Remove provider from the registry, if it exists.\"\"\"\n if name in cls._REGISTRY:\n del cls._REGISTRY[name]\n\n @classmethod\n def get(cls, name):\n \"\"\"Returns provider from the registry.\"\"\"\n if name not in cls._REGISTRY:\n raise ValueError(\"Provider name not registered: %s\" % name)\n return cls._REGISTRY[name]\n\n @classmethod\n def names(cls):\n \"\"\"Returns all provider names in registry.\"\"\"\n return cls._REGISTRY.keys()\n\n @classmethod\n def reset(cls):\n \"\"\"Removes all of the registered tasks.\"\"\"\n cls._REGISTRY = {}\n\n @classmethod\n def get_dataset(\n cls,\n name,\n sequence_length,\n split,\n use_cached=False,\n shuffle=True,\n seed=None,\n shard_info=None,\n num_epochs=1):\n \"\"\"Returns the requested tf.data.Dataset.\"\"\"\n return cls.get(name).get_dataset(\n sequence_length=sequence_length, split=split, use_cached=use_cached,\n shuffle=shuffle, seed=seed, shard_info=shard_info,\n num_epochs=num_epochs)\n\n\n# =============================== DataSources ==================================\n\n\nclass DataSource(DatasetProviderBase):\n \"\"\"A `DatasetProvider` that provides raw data from an input source.\n\n Inherits all abstract methods and properties of `DatasetProviderBase` except\n those overidden below.\n \"\"\"\n\n def __init__(\n self,\n splits: Iterable[str],\n num_input_examples: Optional[Mapping[str, int]] = None):\n self._splits = tuple(splits)\n self._num_input_examples = (\n dict(num_input_examples) if num_input_examples is not None else None)\n\n @property\n def splits(self) -> Sequence[str]:\n return self._splits\n\n @property\n def output_features(self) -> Mapping[str, Feature]:\n \"\"\"Override unused property of `DatasetProviderBase`.\"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def list_shards(self, split: str) -> Sequence[str]:\n \"\"\"Returns string identifiers of input shards.\"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def get_dataset(\n self,\n split: str,\n shuffle: bool = True,\n seed: Optional[int] = None,\n shard_info: Optional[ShardInfo] = None\n ) -> tf.data.Dataset:\n \"\"\"Overrides base class to add shard identifier and remove use_cached.\n\n Args:\n split: string, the split to return.\n shuffle: bool, whether to shuffle the input source.\n seed: tf.int64 scalar tf.Tensor (or None) for shuffling input source.\n shard_info: optional specification for loading a shard of the split.\n \"\"\"\n raise NotImplementedError\n\n def num_input_examples(self, split: str) -> Optional[int]:\n if self._num_input_examples is None:\n return None\n return self._num_input_examples[split]\n\n\ndef _validate_args(fn, expected_pos_args):\n \"\"\"Ensure function has exactly expected positional args.\"\"\"\n argspec = inspect.getfullargspec(fn)\n expected_pos_args = tuple(expected_pos_args)\n actual_args = tuple(argspec.args)\n if actual_args[:len(expected_pos_args)] != expected_pos_args:\n raise ValueError(\n \"'%s' must have positional args %s, got: %s\" % (\n fn.__name__, expected_pos_args, actual_args))\n actual_pos_args = tuple(\n argspec.args[:-len(argspec.defaults)]\n if argspec.defaults else argspec.args)\n if actual_pos_args != expected_pos_args[:len(actual_pos_args)]:\n raise ValueError(\n \"'%s' may only have positional args %s, got: %s\" % (\n fn.__name__, expected_pos_args, actual_pos_args))\n\n\nclass DatasetFnCallable(typing_extensions.Protocol):\n\n def __call__(self,\n split: str,\n shuffle_files: bool,\n seed: Optional[int] = None) -> tf.data.Dataset:\n ...\n\n\nclass FunctionDataSource(DataSource):\n \"\"\"A `DataSource` that uses a function to provide the input data.\"\"\"\n\n def __init__(\n self,\n dataset_fn: DatasetFnCallable,\n splits: Iterable[str],\n num_input_examples: Optional[Mapping[str, int]] = None\n ):\n \"\"\"FunctionDataSource constructor.\n\n Args:\n dataset_fn: a function with the signature `dataset_fn(split,\n shuffle_files)' (and optionally the variable `seed`) that returns a\n `tf.data.Dataset`.\n splits: an iterable of applicable string split names.\n num_input_examples: dict or None, an optional dictionary mapping split\n to its size in number of input examples (before preprocessing). The\n `num_input_examples` method will return None if not provided.\n \"\"\"\n _validate_args(dataset_fn, [\"split\", \"shuffle_files\"])\n self._dataset_fn = dataset_fn\n super().__init__(splits=splits, num_input_examples=num_input_examples)\n\n def get_dataset(\n self,\n split: str,\n shuffle: bool = True,\n seed: Optional[int] = None,\n shard_info: Optional[ShardInfo] = None\n ) -> tf.data.Dataset:\n if shard_info and shard_info.num_shards > 1:\n raise ValueError(\n \"`FunctionDataSource` does not support low-level sharding. Use \"\n \"tf.data.Dataset.shard instead.\")\n\n if seed is None:\n ds = self._dataset_fn(split=split, shuffle_files=shuffle)\n else:\n _validate_args(self._dataset_fn, [\"split\", \"shuffle_files\", \"seed\"])\n ds = self._dataset_fn(split=split, shuffle_files=shuffle, seed=seed)\n return ds\n\n def list_shards(self, split: str) -> Sequence[str]:\n return [split]\n\n\nclass TfdsDataSource(DataSource):\n \"\"\"A `DataSource` that uses TensorFlow Datasets to provide the input data.\"\"\"\n\n def __init__(\n self,\n tfds_name: str,\n tfds_data_dir: Optional[str] = None,\n splits: Optional[Union[Iterable[str], Mapping[str, str]]] = None\n ):\n \"\"\"TfdsTask constructor.\n\n Args:\n tfds_name: string, the name and version number of a TFDS dataset,\n optionally with a config.\n tfds_data_dir: string, an optional path to a specific TFDS data directory\n to use.\n splits: an iterable of allowable string split names, a dict mapping\n allowable canonical splits (e.g., 'validation') to TFDS splits or slices\n (e.g., 'train[':1%']), or None. The default, None, uses all available\n splits from the TFDS dataset info.\n \"\"\"\n if \":\" not in tfds_name:\n raise ValueError(\"TFDS name must contain a version number, got: %s\" %\n tfds_name)\n\n self._tfds_dataset = utils.LazyTfdsLoader(\n tfds_name,\n data_dir=tfds_data_dir,\n split_map=splits if isinstance(splits, dict) else None)\n\n # If splits are not provided, we pass an empty tuple and use the lazy\n # lookup in the `splits` property.\n super().__init__(splits=splits or ())\n\n @property\n def splits(self):\n \"\"\"Overrides since we can't call `info.splits` until after init.\"\"\"\n return self._splits or self._tfds_dataset.info.splits\n\n @property\n def tfds_dataset(self):\n return self._tfds_dataset\n\n def get_dataset(\n self,\n split: str,\n shuffle: bool = True,\n seed: Optional[int] = None,\n shard_info: Optional[ShardInfo] = None\n ) -> tf.data.Dataset:\n return self.tfds_dataset.load(\n split, shuffle_files=shuffle, seed=seed, shard_info=shard_info)\n\n def num_input_examples(self, split: str) -> int:\n \"\"\"Overrides since we can't call `info.splits` until after init.\"\"\"\n return self.tfds_dataset.size(split)\n\n def list_shards(self, split: str) -> Sequence[str]:\n return self.tfds_dataset.files(split)\n\n\nclass FileDataSource(DataSource):\n \"\"\"A `DataSource` that reads a file to provide the input dataset.\"\"\"\n\n def __init__(\n self,\n read_file_fn: Callable[[tf.data.Dataset], tf.data.Dataset],\n split_to_filepattern: Mapping[str, Union[str, Iterable[str]]],\n num_input_examples: Optional[Mapping[str, int]] = None,\n ):\n \"\"\"FileDataSource constructor.\n\n Args:\n read_file_fn: a callable for creating a `tf.data.Dataset` from a\n `tf.data.Dataset` of file paths, e.g., `tf.data.TFRecordDataset`.\n split_to_filepattern: a mapping from split names to filepatterns to be\n expanded with glob.\n num_input_examples: dict or None, an optional dictionary mapping split\n to its size in number of input examples (before preprocessing). The\n `num_input_examples` method will return None if not provided.\n \"\"\"\n self._split_to_filepattern = split_to_filepattern\n self._reader = read_file_fn\n super().__init__(\n splits=split_to_filepattern.keys(),\n num_input_examples=num_input_examples)\n\n def get_dataset(\n self,\n split: str,\n shuffle: bool = True,\n seed: Optional[int] = None,\n shard_info: Optional[ShardInfo] = None\n ) -> tf.data.Dataset:\n files = self.list_shards(split)\n\n if not files:\n raise ValueError(\n \"No file is found for the file pattern: \"\n f\"{self._split_to_filepattern[split]}.\"\n )\n files_ds = tf.data.Dataset.from_tensor_slices(np.array(files, dtype=np.str))\n\n if shard_info:\n if len(files) < shard_info.num_shards:\n raise ValueError(\n f\"Dataset has too few files to shard. {len(files)} files vs \"\n f\"{shard_info.num_shards} shards requested.\")\n files_ds = files_ds.shard(shard_info.num_shards, shard_info.index)\n\n if shuffle:\n files_ds = files_ds.shuffle(buffer_size=16, seed=seed)\n\n return files_ds.interleave(\n self._reader,\n cycle_length=16,\n block_length=16,\n num_parallel_calls=tf.data.experimental.AUTOTUNE)\n\n def list_shards(self, split: str) -> Sequence[str]:\n return tf.io.gfile.glob(self._split_to_filepattern[split])\n\n\nclass TextLineDataSource(FileDataSource):\n \"\"\"A `FileDataSource` that reads lines of text from a file as input.\"\"\"\n\n def __init__(\n self,\n split_to_filepattern: Mapping[str, Union[str, Iterable[str]]],\n skip_header_lines: int = 0,\n num_input_examples: Optional[Mapping[str, int]] = None,\n ):\n \"\"\"TextLineDataSource constructor.\n\n Args:\n split_to_filepattern: a mapping from split names to filepatterns to be\n expanded with glob.\n skip_header_lines: int, number of header lines to skip in each source\n file.\n num_input_examples: dict or None, an optional dictionary mapping split to\n its size in number of input examples (before preprocessing). The\n `num_input_examples` method will return None if not provided.\n \"\"\"\n # Used during caching.\n self._skip_header_lines = skip_header_lines\n\n def read_file_fn(filepattern):\n return tf.data.TextLineDataset(filepattern).skip(skip_header_lines)\n\n super().__init__(\n read_file_fn=read_file_fn,\n split_to_filepattern=split_to_filepattern,\n num_input_examples=num_input_examples)\n\n\nclass TFExampleDataSource(FileDataSource):\n \"\"\"A `FileDataSource` that reads files of tf.train.Example protos as input.\"\"\"\n\n def __init__(\n self,\n split_to_filepattern: Mapping[str, Union[str, Iterable[str]]],\n feature_description: Mapping[str, Union[tf.io.FixedLenFeature,\n tf.io.VarLenFeature]],\n reader_cls: Type[tf.data.Dataset] = tf.data.TFRecordDataset,\n num_input_examples: Optional[Mapping[str, int]] = None,\n ):\n \"\"\"TFExampleDataSource constructor.\n\n Args:\n split_to_filepattern: dict of string (split name) to either string\n (filename or filepattern) or list of strings (filenames or\n filepatterns).\n feature_description: dict, a mapping of string feature keys to\n `tf.io.FixedLenFeature` or `tf.io.VarLenFeature` values.\n reader_cls: `tf.data.Dataset`, a dataset class to read the input files.\n num_input_examples: dict or None, an optional dictionary mapping split to\n its size in number of input examples (before preprocessing). The\n `num_input_examples` method will return None if not provided.\n \"\"\"\n\n def read_file_fn(filepattern):\n return reader_cls(filepattern).map(\n lambda pb: tf.io.parse_single_example(pb, feature_description),\n num_parallel_calls=tf.data.experimental.AUTOTUNE)\n\n super().__init__(\n read_file_fn=read_file_fn,\n split_to_filepattern=split_to_filepattern,\n num_input_examples=num_input_examples)\n\n\n# ========================== Offline Caching Helpers ===========================\n\n\ndef _rename_plaintext_to_pretokenized(\n dataset: tf.data.Dataset) -> tf.data.Dataset:\n \"\"\"Rename cached _plaintext features to new _pretokenized standard.\"\"\"\n def _rename(inputs):\n outputs = {}\n for k, v in inputs.items():\n if k.endswith(\"_plaintext\"):\n k = k[:-len(\"plaintext\")] + \"pretokenized\"\n outputs[k] = v\n return outputs\n return dataset.map(\n _rename, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n\n\nclass _CachedDataSource(FileDataSource):\n \"\"\"A `FileDataSource` for reading datasets cached offline.\"\"\"\n\n def __init__(self, cache_dir: str, split: str):\n\n with tf.io.gfile.GFile(utils.get_cached_info_path(cache_dir, split)) as f:\n split_info = json.load(f)\n features = split_info[\"features\"]\n\n with tf.io.gfile.GFile(utils.get_cached_stats_path(cache_dir, split)) as f:\n stats = json.load(f)\n\n version_when_cached = version.Version(\n split_info.get(\"seqio_version\", \"0.pre\"))\n version_with_true_dtypes = version.Version(\"0.0.0\")\n if version_when_cached < version_with_true_dtypes:\n # Assume that all int64 features are really int32.\n for name, feat in features.items():\n if feat[\"dtype\"] == \"int64\":\n logging.info(\"Casting cached '%s' to int32.\", name)\n feat[\"dtype\"] = \"int32\"\n\n # Use `FixedLenSequenceFeature` for sequences with variable length.\n def _feature_config(shape, dtype):\n if dtype in (\"int32\", \"bool\"):\n # int32 and bool are stored as int64 in the tf.train.Example protobuf.\n # TODO(adarob): Support other conversions.\n dtype = \"int64\"\n if shape and shape[0] is None:\n return tf.io.FixedLenSequenceFeature(\n shape[1:], dtype, allow_missing=True)\n return tf.io.FixedLenFeature(shape, dtype)\n\n feature_description = {\n feat: _feature_config(**desc) for feat, desc in features.items()\n }\n\n def read_file_fn(filepattern):\n ds = tf.data.TFRecordDataset(filepattern)\n ds = ds.map(\n lambda pb: tf.io.parse_single_example(pb, feature_description),\n num_parallel_calls=tf.data.experimental.AUTOTUNE)\n # Cast features back to the types from the info JSON since some features\n # must be cast for storage (e.g., in32 is stored as int64).\n ds = ds.map(\n lambda x: {k: tf.cast(v, features[k][\"dtype\"]) for k, v in x.items()},\n num_parallel_calls=tf.data.experimental.AUTOTUNE)\n # Legacy cached datasets may use old \"_plaintext\" suffix. Rename to\n # \"_pretokenized\".\n ds = _rename_plaintext_to_pretokenized(ds)\n return ds\n\n split_to_filepattern = {\n split: \"%s-*-of-*%d\" % (\n utils.get_cached_tfrecord_prefix(cache_dir, split),\n split_info[\"num_shards\"])\n }\n\n super().__init__(\n read_file_fn=read_file_fn,\n split_to_filepattern=split_to_filepattern,\n num_input_examples={split: stats[\"examples\"]}\n )\n\n\nclass CacheDatasetPlaceholder(object):\n \"\"\"A placeholder to signal when in the pipeline offline caching will occur.\"\"\"\n\n def __init__(self, required=False):\n \"\"\"CacheDatasetPlaceholder constructor.\n\n Args:\n required: whether the dataset must be accessed in its cached form, and\n on-the-fly preprocessing is disallowed.\n \"\"\"\n self._required = required\n\n @property\n def required(self):\n return self._required\n\n def __call__(self, dataset):\n raise RuntimeError(\"`CacheDatasetPlaceholder` should never be called.\")\n\n\n# ================================ Tasks =======================================\n\n\nMetricFnCallable = Callable[..., Mapping[str, float]]\n\n\nclass Task(DatasetProviderBase):\n \"\"\"A class to manage a dataset and its related metrics.\"\"\"\n\n def __init__(\n self,\n name: str,\n source: DataSource,\n output_features: Mapping[str, Feature],\n preprocessors: Optional[Sequence[Callable[..., tf.data.Dataset]]] = None,\n postprocess_fn: Optional[Callable[..., Any]] = None,\n metric_fns: Optional[Sequence[MetricFnCallable]] = None,\n shuffle_buffer_size: Optional[int] = SHUFFLE_BUFFER_SIZE):\n \"\"\"Task constructor.\n\n Args:\n name: a unique name for the Task.\n source: a `DataSource` that provides a raw `tf.data.Dataset`.\n output_features: dict(str, Feature), output features of the Task to be\n passed to the model. After preprocessing, examples will be validated to\n ensure they include features that match this specification. Note that\n additional features may be included (e.g., for evaluation), but they\n will not be passed to the model.\n preprocessors: list(callable), an optional list of functions that receive\n a tf.data.Dataset and return a tf.data.Dataset. These will be executed\n sequentually and the final dataset must include features matching\n `output_features`.\n postprocess_fn: callable, an optional function that receives decoded model\n outputs and converts them to a form that is ready for evaluation using\n the metric functions in `metric_fns`.\n metric_fns: list(callable), an optional list of metric functions with the\n signature `metric_fn(targets, predictions)` to use during evaluation. If\n undefined or empty, no evaluation will occur on the task.\n shuffle_buffer_size: an optional integer to set the shuffle buffer size.\n If None, shuffling will be disallowed.\n \"\"\"\n if not _VALID_TASK_NAME_REGEX.match(name):\n raise ValueError(\n \"Task name '%s' contains invalid characters. Must match regex: %s\" % (\n name, _VALID_TASK_NAME_REGEX.pattern))\n\n metric_fns = metric_fns or []\n self._predict_metric_fns = []\n self._score_metric_fns = []\n for metric_fn in metric_fns:\n pos_args = tuple(\n key for key, param in inspect.signature(metric_fn).parameters.items()\n if param.default == inspect.Parameter.empty\n )\n if pos_args == (\"targets\", \"scores\"):\n self._score_metric_fns.append(metric_fn)\n elif pos_args == (\"targets\", \"predictions\"):\n self._predict_metric_fns.append(metric_fn)\n else:\n raise ValueError(\n \"Metric functions must have positional arguments matching either \"\n \"('targets', 'predictions') or ('targets', 'scores'). \"\n f\"Got: {pos_args}\")\n\n self._name = name\n self._source = source\n\n # Find optional CacheDatasetPlaceholder.\n preprocessors = tuple(preprocessors or [])\n cache_step_idxs = [\n i for i, p in enumerate(preprocessors)\n if isinstance(p, CacheDatasetPlaceholder)\n ]\n if len(cache_step_idxs) > 1:\n raise ValueError(\n \"`CacheDatasetPlaceholder` can appear at most once in the \"\n f\"preprocessing pipeline. Found {len(cache_step_idxs)} in '{name}'.\")\n cache_step_idx = cache_step_idxs[0] if cache_step_idxs else None\n if cache_step_idx is not None:\n for prep in preprocessors[:cache_step_idx]:\n prep_args = inspect.signature(prep).parameters.keys()\n if \"sequence_length\" in prep_args:\n raise ValueError(\n f\"'{prep.__name__}' has a `sequence_length` argument but occurs \"\n f\"before `CacheDatasetPlaceholder` in '{name}'. This is not \"\n \"allowed since the sequence length is specified at run time.\")\n if \"seed\" in prep_args or \"seeds\" in prep_args:\n raise logging.warning( # pylint:disable=logging-format-interpolation\n f\"'{prep.__name__}' has a `seed(s)` argument but occurs before \"\n f\"`CacheDatasetPlaceholder` in '{name}'. This is not recommended \"\n \"since the same samples will be used each epoch when reading \"\n \"from the cache.\")\n self._cache_step_idx = cache_step_idx\n self._preprocessors = preprocessors\n\n self._metric_fns = tuple(metric_fns)\n self._postprocess_fn = postprocess_fn\n\n self._cache_dir = None\n self._stats = {}\n self._shuffle_buffer_size = shuffle_buffer_size\n\n self._output_features = collections.OrderedDict(\n sorted(list(output_features.items()))\n )\n\n @property\n def name(self) -> str:\n return self._name\n\n @property\n def metric_fns(self) -> Sequence[MetricFnCallable]:\n \"\"\"List of all metric functions.\"\"\"\n return self._predict_metric_fns + self._score_metric_fns\n\n @property\n def score_metric_fns(self) -> Sequence[MetricFnCallable]:\n \"\"\"List of metric functions that use log likelihood scores.\"\"\"\n return self._score_metric_fns\n\n @property\n def predict_metric_fns(self) -> Sequence[MetricFnCallable]:\n \"\"\"List of metric functions that use model predictions.\"\"\"\n return self._predict_metric_fns\n\n @property\n def output_features(self) -> Mapping[str, Feature]:\n return self._output_features\n\n @property\n def splits(self) -> Sequence[str]:\n s = self.source.splits\n if not s:\n raise ValueError(f\"Task {self.name} has no splits\")\n return s\n\n @property\n def source(self) -> DataSource:\n return self._source\n\n @property\n def preprocessors(self) -> Sequence[Callable[..., tf.data.Dataset]]:\n return self._preprocessors\n\n def num_input_examples(self, split: str) -> Optional[int]:\n return self.source.num_input_examples(split)\n\n def _preprocess_dataset(\n self,\n dataset: tf.data.Dataset,\n preprocessors: Sequence[Callable[..., tf.data.Dataset]],\n sequence_length: Optional[Mapping[str, int]] = None) -> tf.data.Dataset:\n \"\"\"Sequentially applies preprocessors.\"\"\"\n for prep_fn in preprocessors:\n # prep_fn must not rely on variable length keyword args such as **kwargs.\n fn_args = set(inspect.signature(prep_fn).parameters.keys())\n kwargs = {}\n if \"sequence_length\" in fn_args:\n kwargs[\"sequence_length\"] = sequence_length\n if \"output_features\" in fn_args:\n kwargs[\"output_features\"] = self.output_features\n dataset = prep_fn(dataset, **kwargs)\n return dataset\n\n def _validate_preprocessing(\n self, dataset: tf.data.Dataset\n ) -> tf.data.Dataset:\n \"\"\"Validates preprocessed dataset, raising Exceptions if needed.\n\n Args:\n dataset: a tf.data.Dataset to validate.\n\n Returns:\n a validated tf.data.Dataset.\n \"\"\"\n actual_specs = dataset.element_spec\n for feat, feat_spec in self.output_features.items():\n if feat not in actual_specs:\n if feat_spec.required:\n raise ValueError(\n \"Task dataset is missing expected output feature after \"\n f\"preprocessing: {feat}\")\n else:\n # It's ok that this feature does not exist.\n continue\n actual_spec = actual_specs[feat]\n if feat_spec.dtype != actual_spec.dtype:\n raise ValueError(\n f\"Task dataset has incorrect type for feature '{feat}' after \"\n f\"preprocessing: Got {actual_spec.dtype.name}, expected \"\n f\"{feat_spec.dtype.name}\")\n if actual_spec.shape.rank != 1:\n raise ValueError(\n f\"Task dataset has incorrect rank for feature '{feat}' after \"\n f\"preprocessing: Got {actual_spec.shape.rank}, expected 1\")\n\n return dataset\n\n def _trim_output_features(\n self,\n dataset: tf.data.Dataset,\n sequence_length: Optional[Mapping[str, int]]\n ) -> tf.data.Dataset:\n \"\"\"Trim output features to sequence length.\"\"\"\n def _trim(k: str, v: tf.Tensor) -> tf.Tensor:\n if k not in self.output_features or not sequence_length:\n return v\n return v[:sequence_length[k]]\n\n return dataset.map(\n lambda ex: {k: _trim(k, v) for k, v in ex.items()},\n num_parallel_calls=tf.data.experimental.AUTOTUNE)\n\n def preprocess_precache(\n self,\n dataset: tf.data.Dataset,\n seed: Optional[int] = None\n ) -> tf.data.Dataset:\n \"\"\"Runs preprocessing steps before the optional CacheDatasetPlaceholder.\"\"\"\n if not self.supports_caching:\n return dataset\n\n with utils.map_seed_manager(seed):\n return self._preprocess_dataset(\n dataset,\n self._preprocessors[:self._cache_step_idx],\n )\n\n def preprocess_postcache(\n self,\n dataset: tf.data.Dataset,\n sequence_length: Optional[Mapping[str, int]],\n seed: Optional[int] = None\n ) -> tf.data.Dataset:\n \"\"\"Runs preprocessing steps after the optional CacheDatasetPlaceholder.\n\n Args:\n dataset: a tf.data.Dataset\n sequence_length: dict mapping feature key to int length for that feature.\n If None, the features will not be truncated.\n seed: an optional random seed for deterministic preprocessing.\n Returns:\n a tf.data.Dataset\n \"\"\"\n start_idx = 0\n if self.supports_caching:\n # Skip a sufficient number of seeds to avoid duplicating any from\n # pre-cache preprocessing.\n seed = None if seed is None else seed + 42 * self._cache_step_idx\n start_idx = self._cache_step_idx + 1\n with utils.map_seed_manager(seed):\n dataset = self._preprocess_dataset(\n dataset,\n self._preprocessors[start_idx:],\n sequence_length=sequence_length,\n )\n return dataset\n\n @property\n def cache_dir(self) -> Optional[str]:\n \"\"\"Returns the cache directory (or None), initializing if needed.\"\"\"\n if not self._cache_dir:\n # See if cached data exists in any of the cache directories.\n potential_cache_dirs = [\n os.path.join(d, self.name) for d in utils.get_global_cache_dirs()]\n for cache_dir in potential_cache_dirs:\n try:\n if tf.io.gfile.exists(os.path.join(cache_dir, \"COMPLETED\")):\n self._cache_dir = cache_dir\n logging.info(\"'%s' is cached at %s.\", self.name, self.cache_dir)\n break\n except tf.errors.PermissionDeniedError:\n logging.warning(\n \"Permission denied for global cache folder: %s\", cache_dir)\n\n if not self._cache_dir:\n logging.info(\n \"'%s' does not exist in any task cache directories (searched %s).\",\n self.name,\n potential_cache_dirs,\n )\n return self._cache_dir\n\n @property\n def supports_caching(self) -> bool:\n \"\"\"Whether or not this task supports offline caching.\"\"\"\n return self._cache_step_idx is not None\n\n @property\n def requires_caching(self) -> bool:\n \"\"\"Whether or not this task requires offline caching.\"\"\"\n return (self._cache_step_idx is not None and\n self.preprocessors[self._cache_step_idx].required)\n\n def assert_cached(self) -> None:\n \"\"\"Raises an assertion error if cached dataset does not exist.\"\"\"\n assert self.cache_dir, (\n f\"'{self.name}' does not exist in any of the task cache directories.\")\n\n def get_cached_stats(self,\n split: str = tfds.Split.TRAIN\n ) -> Mapping[str, Union[int, float]]:\n \"\"\"Returns basic statistics for cached dataset.\"\"\"\n self.assert_cached()\n if split not in self._stats:\n stats_path = utils.get_cached_stats_path(self.cache_dir, split)\n if not tf.io.gfile.exists(stats_path):\n raise ValueError(\n \"Stats do not exist for '%s' split: %s\" % (self.name, split))\n with tf.io.gfile.GFile(stats_path) as f:\n self._stats[split] = json.load(f)\n return self._stats[split]\n\n def get_dataset(\n self,\n sequence_length: Optional[Mapping[str, int]],\n split: str = tfds.Split.TRAIN,\n use_cached: bool = False,\n shuffle: bool = True,\n shuffle_buffer_size: Optional[int] = None,\n seed: Optional[int] = None,\n shard_info: Optional[ShardInfo] = None,\n num_epochs: Optional[int] = 1\n ) -> tf.data.Dataset:\n \"\"\"Returns a tf.data.Dataset from cache or generated on the fly.\n\n Args:\n sequence_length: dict mapping feature key to maximum int length for that\n feature. If longer after preprocessing, the feature will be truncated.\n May be set to None to avoid truncation.\n split: string, the split to return.\n use_cached: bool, whether to use the cached dataset instead of processing\n it on the fly. Defaults to False.\n shuffle: bool, whether to shuffle the dataset. Only used when generating\n on the fly (use_cached=False).\n shuffle_buffer_size: an integer or None to use task-specific buffer size.\n seed: tf.int64 scalar tf.Tensor (or None) for shuffling tf.data.\n shard_info: optional specification for loading a shard of the split. If\n the Task's DataSource contains at least the number of shards in the\n specification, it will be passed the shard info to avoid loading the\n full source dataset. Otherwise, the full source dataset will be loaded\n and sharded at the individual examples.\n num_epochs: the number of times to iterate through the dataset, or `None`\n to repeat indefinitely. Note that the repeat occurs in the pipeline\n after offline caching, but before applying potentially stochastic\n post-cache preprocessors and is therefore typically preferred to calling\n `repeat()` on the returned dataset. Defaults to `1`.\n Returns:\n A tf.data.Dataset.\n \"\"\"\n if use_cached and not self.supports_caching:\n logging.warning(\n \"Task '%s' does not support caching. Switching to on-the-fly \"\n \"preprocessing.\", self.name)\n use_cached = False\n elif self.requires_caching and not use_cached:\n raise ValueError(\n f\"Task '{self.name}' requires caching, but was called with \"\n \"`use_cached=False`.\")\n\n if shard_info:\n # Whether we should shard at source or on the examples from the source.\n shard_data_source = (\n len(self.source.list_shards(split=split)) >= shard_info.num_shards)\n logging.info(\"Sharding at the %s: %d of %d\",\n \"data source\" if shard_data_source else \"examples\",\n shard_info.index, shard_info.num_shards)\n else:\n # No sharding.\n shard_data_source = False\n shard_info = ShardInfo(0, 1)\n\n if use_cached:\n source = self._get_cached_source(split)\n else:\n source = self.source\n\n if shard_data_source:\n ds = source.get_dataset(\n split=split, shuffle=shuffle, seed=seed, shard_info=shard_info)\n else:\n ds = source.get_dataset(split=split, shuffle=shuffle, seed=seed)\n ds = ds.shard(shard_info.num_shards, shard_info.index)\n\n if ((use_cached and\n self.get_cached_stats(split)[\"examples\"] < _MAX_EXAMPLES_TO_MEM_CACHE)\n or (self.num_input_examples(split) and\n self.num_input_examples(split) < _MAX_EXAMPLES_TO_MEM_CACHE)):\n logging.info(\n \"Automatically caching small dataset in memory: '%s:%s'\",\n self.name, split)\n ds = ds.cache()\n\n if not use_cached:\n ds = self.preprocess_precache(ds, seed=seed)\n\n ds = ds.prefetch(tf.data.experimental.AUTOTUNE)\n\n # We repeat before calling any (potentially) stochastic post-cache\n # preprocessing in order to take new samples each epoch.\n ds = ds.repeat(num_epochs)\n\n # Post cache processing.\n ds = self.preprocess_postcache(\n ds, sequence_length=sequence_length, seed=seed)\n ds = self._validate_preprocessing(ds)\n ds = self._trim_output_features(ds, sequence_length=sequence_length)\n\n if shuffle:\n if self._shuffle_buffer_size is None:\n raise ValueError(\n f\"Shuffling is disallowed for Task '{self.name}' since its \"\n \"`shuffle_buffer_size` was set to `None` on construction.\")\n shuffle_buffer_size = shuffle_buffer_size or self._shuffle_buffer_size\n # Shuffle before mixing since preprocessor can output multiple\n # (correlated) examples per input.\n ds = ds.shuffle(shuffle_buffer_size, seed=seed)\n\n return ds.prefetch(tf.data.experimental.AUTOTUNE)\n\n def _get_cached_source(self, split) -> _CachedDataSource:\n \"\"\"Returns a DataSource to read cached files for split.\"\"\"\n self.assert_cached()\n return _CachedDataSource(self.cache_dir, split)\n\n def postprocess_fn(self, decoded_model_output: Any,\n **postprocess_kwargs) -> Any:\n \"\"\"Returns the model output after applying the postprocess function.\"\"\"\n if self._postprocess_fn:\n return self._postprocess_fn(decoded_model_output, **postprocess_kwargs)\n return decoded_model_output\n\n\nclass TaskRegistry(DatasetProviderRegistry):\n \"\"\"Registry of Tasks.\"\"\"\n _REGISTRY = {}\n _PROVIDER_TYPE = Task\n\n @classmethod\n def add(\n cls,\n name: str,\n source: DataSource,\n output_features: Mapping[str, Feature],\n preprocessors: Optional[Sequence[Callable[..., tf.data.Dataset]]] = None,\n postprocess_fn: Optional[Callable[..., Any]] = None,\n metric_fns: Optional[Sequence[Callable[..., Mapping[str, float]]]] = None,\n **kwargs) -> Task:\n return super().add(name, Task, name, source, output_features, preprocessors,\n postprocess_fn, metric_fns, **kwargs)\n\n @classmethod\n def get(cls, name) -> Task:\n return super().get(name)\n\n\n# ================================ Mixtures ====================================\nclass Mixture(DatasetProviderBase):\n \"\"\"Class for mixing multiple tasks.\"\"\"\n\n def __init__(self,\n name: str,\n tasks: Union[Sequence[str],\n Sequence[Tuple[str, Union[int, float,\n Callable[[Task],\n float]]]]],\n default_rate: Union[float, Callable[[Task], float]] = None):\n \"\"\"Mixture constructor.\n\n A mixture specifies a set of tasks with associated mixing rates.\n\n Mixing happens on preprocessed tokenized examples.\n\n The mixing rates represent relative numbers of examples to use from their\n associated tasks. Setting the mixing rates to be equal to the numbers of\n examples in the tasks will result in each task going through an epoch in\n about the same amount of time - i.e. all examples are sampled equally across\n all tasks.\n\n Rates can be expressed either as absolute numbers or as functions that\n receive the Task as an argument.\n\n Args:\n name: string, a unique name for the Mixture.\n tasks: a list where each element is either a string (task name) or a\n pair whose first element is the task name and whose second element\n is either a float (rate) or a function from Task to float.\n default_rate: a float or a function from Task to float. This specifies the\n default rate if rates are not provided in the `tasks` argument.\n \"\"\"\n self._task_to_rate = {}\n self._tasks = []\n self._sub_mixtures = []\n self._name = name\n for t in tasks:\n if isinstance(t, str):\n task_name = t\n rate = default_rate\n if default_rate is None:\n raise ValueError(\"need a rate for each task\")\n else:\n task_name, rate = t\n\n if task_name in TaskRegistry.names():\n self._tasks.append(TaskRegistry.get(task_name))\n self._task_to_rate[task_name] = rate\n else:\n self._sub_mixtures.append(MixtureRegistry.get(task_name)) # pytype:disable=name-error\n self._task_to_rate[task_name] = rate\n\n if len(set(tuple(t.output_features) for t in self.tasks)) != 1:\n raise ValueError(\n \"All Tasks in a Mixture must have the same output features.\"\n )\n\n @property\n def name(self) -> str:\n return self._name\n\n @property\n def tasks(self) -> Sequence[Task]:\n sub_tasks = (mix.tasks for mix in self._sub_mixtures)\n return list(sorted(set(sum(sub_tasks, self._tasks)), key=lambda t: t.name))\n\n @property\n def total_rate(self) -> float:\n return sum(float(rate(TaskRegistry.get(name)) if callable(rate) else rate)\n for name, rate in self._task_to_rate.items())\n\n def get_rate(self, task: Task) -> float:\n \"\"\"Computes the mixing rate for the given task.\"\"\"\n value = 0.0\n\n for mix in self._sub_mixtures:\n if task in mix.tasks:\n rate = self._task_to_rate[mix.name]\n value += rate * mix.get_rate(task) / mix.total_rate\n\n if task.name in self._task_to_rate:\n rate = self._task_to_rate[task.name]\n value += float(rate(task) if callable(rate) else rate)\n\n return value\n\n def num_input_examples(self, split: str) -> int:\n return sum(t.num_input_examples(split) for t in self.tasks)\n\n @property\n def splits(self) -> Sequence[str]:\n splits = set()\n for task in self.tasks:\n splits.update(task.splits)\n return tuple(splits)\n\n @property\n def output_features(self) -> Mapping[str, Feature]:\n # We require all tasks to have the same output_features in __init__\n # so we can just get the output_features for the 0th task\n return self.tasks[0].output_features\n\n def _check_compatible_features(self) -> None:\n \"\"\"Throw Exception if features across tasks have different vocabs or dtypes.\n \"\"\"\n for name, feature in self.tasks[0].output_features.items():\n for task in self.tasks[1:]:\n if task.output_features[name].vocabulary != feature.vocabulary:\n raise ValueError(\n \"Features across tasks in a mixture must use the same vocabulary.\"\n )\n if task.output_features[name].dtype != feature.dtype:\n raise ValueError(\n \"Features across tasks in a mixture must use the same dtype.\"\n )\n\n def get_dataset(\n self,\n sequence_length: Optional[Mapping[str, int]],\n split: str = tfds.Split.TRAIN,\n use_cached: bool = False,\n shuffle: bool = True,\n seed: Optional[int] = None,\n shard_info: Optional[ShardInfo] = None,\n num_epochs: Optional[int] = None,\n copy_pretokenized: bool = False,\n compute_stats_empirically: bool = False,\n ) -> tf.data.Dataset:\n \"\"\"Returns the dataset of mixed tasks using the object-specified rates.\n\n Args:\n sequence_length: dict mapping feature key to maximum int length for that\n feature. If longer after preprocessing, the feature will be truncated.\n May be set to None to avoid truncation.\n split: string, the split to return for all tasks.\n use_cached: bool, whether to use the cached dataset instead of processing\n it on the fly. Defaults to False.\n shuffle: bool, whether to shuffle the dataset. Only used when generating\n on the fly (use_cached=False).\n seed: tf.int64 scalar tf.Tensor (or None) for shuffling tf.data.\n shard_info: optional specification for loading a shard of the split.\n num_epochs: the number of times to iterate through the dataset, or `None`\n to repeat indefinitely. Note that the repeat occurs in the pipeline\n after offline caching, but before applying potentially stochastic\n post-cache preprocessors and is therefore typically preferred to calling\n `repeat()` on the returned dataset. Defaults to `None`.\n copy_pretokenized: bool, whether to pass through copies of pretokenized\n features a \"_pretokenized\" suffix added to the key.\n compute_stats_empirically: a boolean - does not work on TPU\n \"\"\"\n self._check_compatible_features()\n tasks = []\n for task in self.tasks:\n if split not in task.splits:\n logging.warning(\n \"Task %s has no '%s' split, skipping.\", task.name, split\n )\n continue\n tasks.append(task)\n if not tasks:\n raise ValueError(\"No datasets have a '{}' split\".format(split))\n\n output_feature_keys = set(self.output_features.keys())\n if copy_pretokenized:\n output_feature_keys.update(\n {f + \"_pretokenized\" for f in output_feature_keys})\n\n def filter_features(ex):\n return {k: v for k, v in ex.items() if k in output_feature_keys}\n datasets = [\n task.get_dataset( # pylint:disable=g-complex-comprehension\n sequence_length,\n split=split,\n use_cached=use_cached,\n shuffle=shuffle,\n seed=seed,\n shard_info=shard_info,\n num_epochs=num_epochs)\n .map(filter_features, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n for task in tasks]\n rates = [self.get_rate(task) for task in tasks]\n # Sample from the dataset with the rates rates\n if seed is not None:\n sample_seed = seed\n elif shuffle:\n sample_seed = None\n else:\n sample_seed = 42\n dataset = tf.data.experimental.sample_from_datasets(\n datasets, rates, sample_seed)\n if (split == \"train\" and use_cached and\n all(t.supports_caching for t in tasks)):\n _log_mixing_proportions(tasks, datasets, rates, dataset, sequence_length,\n compute_stats_empirically)\n return dataset\n\n\ndef _log_padding_fractions(dataset, sequence_length, num_examples=100):\n \"\"\"Empirically compute the fraction of padding - log the results.\n\n Args:\n dataset: a tf.data.Dataset\n sequence_length: dict from string to int (packed lengths)\n num_examples: an integer\n \"\"\"\n logging.info(\"computing padding fractions\")\n keys = sequence_length.keys()\n padding_frac = {k: 0 for k in keys}\n for ex in tfds.as_numpy(dataset.take(num_examples)):\n for k in keys:\n padding_frac[k] += 1 - (sequence_length[k] / len(ex[k]))\n for k in keys:\n logging.info(\"%s padding fraction = %g\", k, padding_frac[k])\n\n\ndef _log_mixing_proportions(\n tasks, datasets, rates, mixed_dataset,\n sequence_length, compute_stats_empirically):\n \"\"\"Log information about the mixing proportions.\n\n Called from Mixture.get_dataset.\n\n Args:\n tasks: a list of Task\n datasets: a list of tf.data.Dataset\n rates: a list of floats\n mixed_dataset: a tf.data.Dataset\n sequence_length: dict from string to int (packed lengths)\n compute_stats_empirically: a boolean - does not work on TPU\n \"\"\"\n def _normalize(l):\n denom = sum(l)\n if not denom:\n return l\n return [x / denom for x in l]\n # compute some stats about the mixture\n examples_fraction = _normalize(rates)\n if compute_stats_empirically:\n stats_examples = 100\n mean_inputs_length = []\n mean_targets_length = []\n for dataset in datasets:\n inputs_sum = 0\n targets_sum = 0\n for ex in tfds.as_numpy(dataset.take(stats_examples)):\n # Some tasks, like LMs, don't have inputs.\n if \"inputs\" in ex:\n inputs_sum += ex[\"inputs\"].size\n targets_sum += ex[\"targets\"].size\n mean_inputs_length.append(inputs_sum / float(stats_examples))\n mean_targets_length.append(targets_sum / float(stats_examples))\n else:\n def _estimated_mean_length(task, key):\n if key not in sequence_length:\n return 0\n if (task.supports_caching and\n task._cache_step_idx < len(task._preprocessors) - 1): # pylint:disable=protected-access\n # There is processing after caching, so we can't rely on the stats.\n return sequence_length[key]\n # Some tasks, like LMs, don't have inputs.\n if key + \"_tokens\" in task.get_cached_stats(\"train\"):\n return min(sequence_length[key],\n (task.get_cached_stats(\"train\")[key + \"_tokens\"] /\n task.get_cached_stats(\"train\")[\"examples\"]))\n else:\n return 0\n\n mean_inputs_length = [_estimated_mean_length(task, \"inputs\")\n for task in tasks]\n mean_targets_length = [_estimated_mean_length(task, \"targets\")\n for task in tasks]\n inputs_fraction = _normalize(\n [l * r for l, r in zip(mean_inputs_length, rates)])\n targets_fraction = _normalize(\n [l * r for l, r in zip(mean_targets_length, rates)])\n logging.info(\"%12s %12s %12s %12s %12s %12s %s\",\n \"rate\", \"ex.frac.\", \"inp.frac.\", \"tgt.frac.\",\n \"inp.len.\", \"tgt.len\", \"task\")\n for i in range(len(rates)):\n logging.info(\"%12g %12g %12g %12g %12g %12g %s\",\n rates[i], examples_fraction[i],\n inputs_fraction[i], targets_fraction[i],\n mean_inputs_length[i], mean_targets_length[i],\n tasks[i].name)\n if compute_stats_empirically:\n _log_padding_fractions(mixed_dataset, sequence_length)\n\n\nclass MixtureRegistry(DatasetProviderRegistry):\n \"\"\"Registry of Mixtures.\"\"\"\n _REGISTRY = {}\n _PROVIDER_TYPE = Mixture\n\n @classmethod\n def add(cls, name, tasks, default_rate=None) -> Mixture:\n return super().add(name, Mixture, name, tasks, default_rate)\n\n @classmethod\n def get(cls, name) -> Mixture:\n return super().get(name)\n\n\ndef get_mixture_or_task(task_or_mixture_name):\n \"\"\"Return the Task or Mixture from the appropriate registry.\"\"\"\n mixtures = MixtureRegistry.names()\n tasks = TaskRegistry.names()\n if task_or_mixture_name in mixtures:\n if task_or_mixture_name in tasks:\n logging.warning(\"%s is both a Task and a Mixture, returning Mixture\",\n task_or_mixture_name)\n return MixtureRegistry.get(task_or_mixture_name)\n if task_or_mixture_name in tasks:\n return TaskRegistry.get(task_or_mixture_name)\n else:\n raise ValueError(\"No Task or Mixture found with name: %s\" %\n task_or_mixture_name)\n\n\ndef get_subtasks(task_or_mixture):\n \"\"\"Returns all the Tasks in a Mixture as a list or the Task itself.\"\"\"\n if isinstance(task_or_mixture, Task):\n return [task_or_mixture]\n else:\n return task_or_mixture.tasks\n\n\ndef get_dataset(\n mixture_or_task_name: str,\n task_feature_lengths: Mapping[str, int],\n feature_converter: FeatureConverter,\n dataset_split: str = \"train\",\n use_cached: bool = False,\n shuffle: bool = False,\n num_epochs: Optional[int] = 1,\n shard_info: ShardInfo = None,\n verbose: bool = True,\n seed: Optional[int] = None\n) -> tf.data.Dataset:\n \"\"\"Get processed dataset with the model features.\n\n In order to use options specific to a feature converter, e.g., packing,\n `feature_converter` instance should be instantiated with those options before\n being pased to this function.\n\n Getting sharded datasets is supported. To use this feature, pass in\n `shard_info`, with shard_index and num_shards information. Sharding is done\n before the feature converter stage. Therefore, if packing is used it will be\n done on the sharded dataset.\n\n Args:\n mixture_or_task_name: mixture or task name for the Task API.\n task_feature_lengths: dict mapping task feature key to its sequence length.\n This specifies the sequence length of the dataset from the Task API.\n feature_converter: a feature converter object to use to convert the task\n features to model features.\n Must be a subclass of FeatureConverter.\n dataset_split: the split to use.\n use_cached: whether to use the cached dataset instead of processing it on\n the fly.\n shuffle: whether to shuffle the dataset.\n num_epochs: the number of times to iterate through the dataset, or `None` to\n repeat indefinitely. Note that the repeat occurs in the pipeline after\n offline caching, but before applying potentially stochastic post-cache\n preprocessors and is therefore typically preferred to calling `repeat()`\n on the returned dataset. Defaults to `1`.\n shard_info: number of shards and shard index information.\n verbose: if true, log the feature shapes.\n seed: a random seed to for shuffling tf.data.\n\n Returns:\n ds: the processed dataset.\n \"\"\"\n if not isinstance(feature_converter, FeatureConverter):\n raise TypeError(\n \"feature_converter should be an instance of FeatureConverter.\")\n\n mixture_or_task = get_mixture_or_task(mixture_or_task_name)\n\n ds = mixture_or_task.get_dataset(\n task_feature_lengths,\n split=dataset_split,\n use_cached=use_cached,\n shuffle=shuffle,\n seed=seed,\n shard_info=shard_info,\n num_epochs=num_epochs)\n\n ds = feature_converter(ds, task_feature_lengths=task_feature_lengths)\n\n if verbose:\n logging.info(\n \"The output dataset from seqio.get_dataset has the following features\")\n for feature_name, tensor_spec in ds.element_spec.items():\n logging.info(\"feature: %s \\t shape: %s \\t dtype: %s\", feature_name,\n tensor_spec.shape.as_list(), tensor_spec.dtype.name)\n return ds\n" ]
[ [ "tensorflow.compat.v2.io.parse_single_example", "tensorflow.compat.v2.io.gfile.GFile", "tensorflow.compat.v2.io.gfile.exists", "tensorflow.compat.v2.data.experimental.sample_from_datasets", "tensorflow.compat.v2.cast", "tensorflow.compat.v2.data.TFRecordDataset", "tensorflow.compat.v2.io.FixedLenSequenceFeature", "tensorflow.compat.v2.data.TextLineDataset", "numpy.array", "tensorflow.compat.v2.io.FixedLenFeature", "tensorflow.compat.v2.io.gfile.glob" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
bmalezieux/unrolled_dl
[ "5854a6991e44db025a99a9f0d38be6b1e669aa83", "5854a6991e44db025a99a9f0d38be6b1e669aa83" ]
[ "experiments_approximate/experiments/create_dico_alphacsc.py", "experiments_approximate/experiments/optim_images.py" ]
[ "import numpy as np\n\natoms_to_save = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 15, 18])\n\nu_cdl = np.load(\"u_cdl.npy\")\nv_cdl = np.load(\"v_cdl.npy\")\n\nnp.save(\"u_cdl_modified.npy\", u_cdl[atoms_to_save])\nnp.save(\"v_cdl_modified.npy\", v_cdl[atoms_to_save])\n", "import numpy as np\nimport pickle\nimport time\n\nfrom tqdm import tqdm\nfrom pathlib import Path\nfrom PIL import Image\nfrom utils import (create_patches_overlap,\n patch_average)\nfrom plipy.ddl import DeepDictionaryLearning, AMDictionaryLearning\n\n\nRESULTS = Path(__file__).resolve().parents[1] / \"results\"\nRNG = np.random.default_rng(2022)\nSIGMA = 0.1\n\n\nclass FISTA():\n \"\"\"\n FISTA algorithm\n \"\"\"\n def __init__(self, y, D, lambd=1):\n self.y = y\n self.D = D\n\n # Regularization term\n self.lambd = lambd\n\n # Lipschitz constant of the gradient\n self.lipschitz = self.compute_lipschitz()\n\n # Step\n self.gamma = 1 / self.lipschitz\n\n def compute_lipschitz(self, eps=1e-5):\n \"\"\"\n Computes the lispchitz constant of the gradient\n with power iteration.\n\n Parameters\n ----------\n eps : float\n Convergence tolerance.\n\n Returns\n -------\n norm : float\n Norm of the gradient.\n \"\"\"\n x_random = RNG.random(self.D.shape[1])\n x_random /= np.linalg.norm(x_random)\n old_norm = 0.\n norm = 1.\n while np.abs(old_norm - norm) > eps:\n old_norm = norm\n x_random = self.D.T @ self.D @ x_random\n norm = np.linalg.norm(x_random)\n x_random /= norm\n\n return norm\n\n def f(self, x):\n \"\"\" Data fitting term of the loss \"\"\"\n res = self.D @ x - self.y\n res *= res\n return res.sum(axis=0) / 2\n\n def g(self, x):\n \"\"\" L1 norm \"\"\"\n return np.linalg.norm(x, ord=1, axis=0)\n\n def energy(self, x):\n \"\"\" Lasso cost function \"\"\"\n return self.f(x) + self.lambd * self.g(x)\n\n def grad_f(self, x):\n \"\"\" Gradient of data fitting term \"\"\"\n return self.D.T @ (self.D @ x - self.y)\n\n def prox_g(self, x, gamma):\n \"\"\" Soft thresholding \"\"\"\n return np.sign(x) * np.maximum(0, np.abs(x) - gamma * self.lambd)\n\n def gradientDescent(self, x, gamma):\n \"\"\" Proximal gradient descent \"\"\"\n return self.prox_g(x - gamma * self.grad_f(x), gamma)\n\n def iter(self, n_iter):\n \"\"\" FISTA algorithm with n_iter iterations \"\"\"\n x = self.D.T @ np.zeros(self.y.shape)\n z = x.copy()\n xold = x.copy()\n told = 1\n for i in range(n_iter):\n x = self.gradientDescent(z, self.gamma)\n t = 0.5 * (1 + np.sqrt(1 + 4 * told*told))\n z = x + ((told-1) / t) * (x - xold)\n told = t\n xold = x.copy()\n return x\n\n\nclass ImageDenoising():\n \"\"\"\n Image denoising with dictionary learning\n \"\"\"\n def __init__(self, y, n_iter=20, lambd=1, m=12,\n n_components=None, algo=\"fista\"):\n self.m = m\n self.r, self.c = y.shape\n self.y, _ = create_patches_overlap(y, m)\n self.lambd = lambd\n self.n_iter = n_iter\n self.D = None\n\n if n_components is not None:\n self.n_components = n_components\n else:\n self.n_components = 2 * m * m\n\n self.algo = algo\n\n def get_prior(self):\n return self.D\n\n def training_process(self, grad=True, steps=True):\n if not grad:\n ddl = AMDictionaryLearning(self.n_components,\n self.n_iter,\n lambd=self.lambd)\n loss = ddl.fit(self.y)\n elif steps:\n ddl = DeepDictionaryLearning(self.n_components,\n self.n_iter,\n lambd=self.lambd)\n loss = ddl.fit(self.y)\n else:\n ddl = DeepDictionaryLearning(self.n_components,\n self.n_iter,\n lambd=self.lambd,\n learn_steps=steps)\n loss = ddl.fit(self.y)\n\n self.D = ddl.get_prior()\n result1 = ddl.eval()\n sparse_coding = FISTA(self.y, self.D, lambd=self.lambd)\n result2 = sparse_coding.iter(1000)\n im_result1 = patch_average(self.D @ result1, self.m, self.r, self.c)\n im_result2 = patch_average(self.D @ result2, self.m, self.r, self.c)\n return im_result1, im_result2, loss\n\n\npath = Path(__file__).resolve().parents[1]\nim = Image.open(str(path / \"data/flowers.png\"))\nim_gray = im.convert(\"L\")\nim_gray_resized = im_gray.resize((128, 128), Image.ANTIALIAS)\nim_to_process = np.array(im_gray_resized) / 255.\n\nnoise = RNG.normal(scale=SIGMA, size=im_to_process.shape)\nim_noisy = np.clip(im_to_process + noise, 0, 1)\n\n\n# Optimization\nlambd = 0.1\nn_components = 128\nm_patch = 10\n\n\ndef psnr(im, imref, d=1):\n mse = np.mean((im - imref)**2)\n return 10 * np.log(d * d / mse) / np.log(10)\n\n\ndenoiser = ImageDenoising(im_noisy, lambd=lambd,\n m=m_patch, n_components=n_components)\n\n\niterations = np.unique(np.logspace(0, np.log10(100), num=50, dtype=int))\nresults = {\n \"AM\": {\"psnr1\": [], \"psnr2\": [], \"loss\": [], \"time\": []},\n \"DDL\": {\"psnr1\": [], \"psnr2\": [], \"loss\": [], \"time\": []},\n \"DDL_steps\": {\"psnr1\": [], \"psnr2\": [], \"loss\": [], \"time\": []},\n \"DL\": {\"psnr1\": [], \"psnr2\": [], \"loss\": [], \"time\": []}\n }\n\n\nfor i in tqdm(iterations):\n denoiser.n_iter = i\n start = time.time()\n im1_ddl, im2_ddl, loss_ddl = denoiser.training_process(grad=True,\n steps=False)\n stop = time.time()\n results[\"DDL\"][\"psnr1\"].append(psnr(im1_ddl, im_to_process))\n results[\"DDL\"][\"psnr2\"].append(psnr(im2_ddl, im_to_process))\n results[\"DDL\"][\"loss\"].append(loss_ddl)\n results[\"DDL\"][\"time\"].append(stop - start)\n\n start = time.time()\n im1_ddl_steps, im2_ddl_steps, loss_ddl_steps = denoiser.training_process(grad=True,\n steps=True)\n stop = time.time()\n results[\"DDL_steps\"][\"psnr1\"].append(psnr(im1_ddl_steps, im_to_process))\n results[\"DDL_steps\"][\"psnr2\"].append(psnr(im2_ddl_steps, im_to_process))\n results[\"DDL_steps\"][\"loss\"].append(loss_ddl_steps)\n results[\"DDL_steps\"][\"time\"].append(stop - start)\n\n start = time.time()\n im1_am, im2_am, loss_am = denoiser.training_process(grad=False,\n steps=False)\n stop = time.time()\n results[\"AM\"][\"psnr1\"].append(psnr(im1_am, im_to_process))\n results[\"AM\"][\"psnr2\"].append(psnr(im2_am, im_to_process))\n results[\"AM\"][\"loss\"].append(loss_am)\n results[\"AM\"][\"time\"].append(stop - start)\n\n\nstart = time.time()\ndenoiser.n_iter = 1000\nim1_am, im2_am, loss_am = denoiser.training_process(grad=False,\n steps=False)\n\nstop = time.time()\nresults[\"DL\"][\"psnr1\"].append(psnr(im1_am, im_to_process))\nresults[\"DL\"][\"psnr2\"].append(psnr(im2_am, im_to_process))\nresults[\"DL\"][\"loss\"].append(loss_am)\nresults[\"DL\"][\"time\"].append(stop - start)\n\n\nnp.save(str(RESULTS / \"image_iterations.npy\"), iterations)\n\nwith open(str(RESULTS / 'optim_image.pickle'), 'wb') as file1:\n pickle.dump(results, file1)\n" ]
[ [ "numpy.load", "numpy.array", "numpy.save" ], [ "numpy.log", "numpy.abs", "numpy.sqrt", "numpy.clip", "numpy.linalg.norm", "numpy.sign", "numpy.log10", "numpy.mean", "numpy.array", "numpy.zeros", "numpy.random.default_rng" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
KevHg/reddit-sentiment
[ "383407105957b8a582a524fa29b9f21d7b2cbd23" ]
[ "main.py" ]
[ "import os\nfrom scrapy.crawler import CrawlerProcess\nimport pandas as pd\nimport logging\nimport nltk\n\nimport json_reader\nfrom sentiment_score import clean_text, calculate_sentiment_score\nfrom reddit_scraper.reddit_scraper.spiders.reddit_post_scraper import RedditPostCrawler\n\nif __name__ == '__main__':\n # Initial setup: Disable scrapy logs and download NLTK files\n logging.getLogger('scrapy').propagate = False\n nltk.download('averaged_perceptron_tagger', quiet=True)\n nltk.download('wordnet', quiet=True)\n\n # Ask for user query\n subreddit = input('Subreddit: ')\n term = input('Search term: ')\n term = term.replace(' ', '+')\n\n # Start crawler process\n print('[LOG] Crawling Reddit, this will take a little time...')\n process = CrawlerProcess(settings={\n 'FEED_FORMAT': 'jl',\n 'FEED_URI': 'data.jl'\n })\n process.crawl(RedditPostCrawler,\n domain=f'https://old.reddit.com/r/{subreddit}/search?q={term}&restrict_sr=on&sort=relevance&t=all')\n process.start()\n\n # Convert data file to class\n print('[LOG] Creating DataFrame table...')\n reddit_posts = json_reader.convert_json('data.jl')\n all_comments = []\n all_upvotes = []\n for post in reddit_posts:\n for comment in post.comments:\n all_comments.append(clean_text(comment.text))\n\n # Convert upvote text to float, e.g. '15.3k upvotes' -> 15300\n upvote = comment.upvotes.split(' ')[0]\n if 'k' in upvote:\n upvote = upvote[:-1]\n upvote = float(upvote) * 1000\n all_upvotes.append(float(upvote))\n\n df = pd.DataFrame({'comment': all_comments, 'upvotes': all_upvotes})\n df = df[df.upvotes >= 1]\n\n print('[LOG] Calculating sentiment score, this may take a longer time...')\n df = calculate_sentiment_score(df)\n\n # df.to_csv('results.csv')\n normalized_result = df.sentiment.mean()\n\n print('[LOG] Completed!\\n')\n print('Average sentiment:', normalized_result)\n print('where +1 is most positive and -1 is most negative')\n\n os.remove('data.jl')\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": [] } ]